blob: 243560a4d8bc43d69ee13a1e007455ee456ce9da [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Math module -- standard C math library functions, pi and e */
2
Christian Heimes53876d92008-04-19 00:31:39 +00003/* Here are some comments from Tim Peters, extracted from the
4 discussion attached to http://bugs.python.org/issue1640. They
5 describe the general aims of the math module with respect to
6 special values, IEEE-754 floating-point exceptions, and Python
7 exceptions.
8
9These are the "spirit of 754" rules:
10
111. If the mathematical result is a real number, but of magnitude too
12large to approximate by a machine float, overflow is signaled and the
13result is an infinity (with the appropriate sign).
14
152. If the mathematical result is a real number, but of magnitude too
16small to approximate by a machine float, underflow is signaled and the
17result is a zero (with the appropriate sign).
18
193. At a singularity (a value x such that the limit of f(y) as y
20approaches x exists and is an infinity), "divide by zero" is signaled
21and the result is an infinity (with the appropriate sign). This is
22complicated a little by that the left-side and right-side limits may
23not be the same; e.g., 1/x approaches +inf or -inf as x approaches 0
24from the positive or negative directions. In that specific case, the
25sign of the zero determines the result of 1/0.
26
274. At a point where a function has no defined result in the extended
28reals (i.e., the reals plus an infinity or two), invalid operation is
29signaled and a NaN is returned.
30
31And these are what Python has historically /tried/ to do (but not
32always successfully, as platform libm behavior varies a lot):
33
34For #1, raise OverflowError.
35
36For #2, return a zero (with the appropriate sign if that happens by
37accident ;-)).
38
39For #3 and #4, raise ValueError. It may have made sense to raise
40Python's ZeroDivisionError in #3, but historically that's only been
41raised for division by zero and mod by zero.
42
43*/
44
45/*
46 In general, on an IEEE-754 platform the aim is to follow the C99
47 standard, including Annex 'F', whenever possible. Where the
48 standard recommends raising the 'divide-by-zero' or 'invalid'
49 floating-point exceptions, Python should raise a ValueError. Where
50 the standard recommends raising 'overflow', Python should raise an
51 OverflowError. In all other circumstances a value should be
52 returned.
53 */
54
Barry Warsaw8b43b191996-12-09 22:32:36 +000055#include "Python.h"
Mark Dickinson664b5112009-12-16 20:23:42 +000056#include "_math.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000057
Serhiy Storchakac9ea9332017-01-19 18:13:09 +020058#include "clinic/mathmodule.c.h"
59
60/*[clinic input]
61module math
62[clinic start generated code]*/
63/*[clinic end generated code: output=da39a3ee5e6b4b0d input=76bc7002685dd942]*/
64
65
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000066/*
67 sin(pi*x), giving accurate results for all finite x (especially x
68 integral or close to an integer). This is here for use in the
69 reflection formula for the gamma function. It conforms to IEEE
70 754-2008 for finite arguments, but not for infinities or nans.
71*/
Tim Petersa40c7932001-09-05 22:36:56 +000072
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000073static const double pi = 3.141592653589793238462643383279502884197;
Mark Dickinson9c91eb82010-07-07 16:17:31 +000074static const double logpi = 1.144729885849400174143427351353058711647;
Louie Lu7a264642017-03-31 01:05:10 +080075#if !defined(HAVE_ERF) || !defined(HAVE_ERFC)
76static const double sqrtpi = 1.772453850905516027298167483341145182798;
77#endif /* !defined(HAVE_ERF) || !defined(HAVE_ERFC) */
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000078
79static double
80sinpi(double x)
81{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000082 double y, r;
83 int n;
84 /* this function should only ever be called for finite arguments */
85 assert(Py_IS_FINITE(x));
86 y = fmod(fabs(x), 2.0);
87 n = (int)round(2.0*y);
88 assert(0 <= n && n <= 4);
89 switch (n) {
90 case 0:
91 r = sin(pi*y);
92 break;
93 case 1:
94 r = cos(pi*(y-0.5));
95 break;
96 case 2:
97 /* N.B. -sin(pi*(y-1.0)) is *not* equivalent: it would give
98 -0.0 instead of 0.0 when y == 1.0. */
99 r = sin(pi*(1.0-y));
100 break;
101 case 3:
102 r = -cos(pi*(y-1.5));
103 break;
104 case 4:
105 r = sin(pi*(y-2.0));
106 break;
107 default:
108 assert(0); /* should never get here */
109 r = -1.23e200; /* silence gcc warning */
110 }
111 return copysign(1.0, x)*r;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000112}
113
114/* Implementation of the real gamma function. In extensive but non-exhaustive
115 random tests, this function proved accurate to within <= 10 ulps across the
116 entire float domain. Note that accuracy may depend on the quality of the
117 system math functions, the pow function in particular. Special cases
118 follow C99 annex F. The parameters and method are tailored to platforms
119 whose double format is the IEEE 754 binary64 format.
120
121 Method: for x > 0.0 we use the Lanczos approximation with parameters N=13
122 and g=6.024680040776729583740234375; these parameters are amongst those
123 used by the Boost library. Following Boost (again), we re-express the
124 Lanczos sum as a rational function, and compute it that way. The
125 coefficients below were computed independently using MPFR, and have been
126 double-checked against the coefficients in the Boost source code.
127
128 For x < 0.0 we use the reflection formula.
129
130 There's one minor tweak that deserves explanation: Lanczos' formula for
131 Gamma(x) involves computing pow(x+g-0.5, x-0.5) / exp(x+g-0.5). For many x
132 values, x+g-0.5 can be represented exactly. However, in cases where it
133 can't be represented exactly the small error in x+g-0.5 can be magnified
134 significantly by the pow and exp calls, especially for large x. A cheap
135 correction is to multiply by (1 + e*g/(x+g-0.5)), where e is the error
136 involved in the computation of x+g-0.5 (that is, e = computed value of
137 x+g-0.5 - exact value of x+g-0.5). Here's the proof:
138
139 Correction factor
140 -----------------
141 Write x+g-0.5 = y-e, where y is exactly representable as an IEEE 754
142 double, and e is tiny. Then:
143
144 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) = pow(y-e, x-0.5)/exp(y-e)
145 = pow(y, x-0.5)/exp(y) * C,
146
147 where the correction_factor C is given by
148
149 C = pow(1-e/y, x-0.5) * exp(e)
150
151 Since e is tiny, pow(1-e/y, x-0.5) ~ 1-(x-0.5)*e/y, and exp(x) ~ 1+e, so:
152
153 C ~ (1-(x-0.5)*e/y) * (1+e) ~ 1 + e*(y-(x-0.5))/y
154
155 But y-(x-0.5) = g+e, and g+e ~ g. So we get C ~ 1 + e*g/y, and
156
157 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) ~ pow(y, x-0.5)/exp(y) * (1 + e*g/y),
158
159 Note that for accuracy, when computing r*C it's better to do
160
161 r + e*g/y*r;
162
163 than
164
165 r * (1 + e*g/y);
166
167 since the addition in the latter throws away most of the bits of
168 information in e*g/y.
169*/
170
171#define LANCZOS_N 13
172static const double lanczos_g = 6.024680040776729583740234375;
173static const double lanczos_g_minus_half = 5.524680040776729583740234375;
174static const double lanczos_num_coeffs[LANCZOS_N] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 23531376880.410759688572007674451636754734846804940,
176 42919803642.649098768957899047001988850926355848959,
177 35711959237.355668049440185451547166705960488635843,
178 17921034426.037209699919755754458931112671403265390,
179 6039542586.3520280050642916443072979210699388420708,
180 1439720407.3117216736632230727949123939715485786772,
181 248874557.86205415651146038641322942321632125127801,
182 31426415.585400194380614231628318205362874684987640,
183 2876370.6289353724412254090516208496135991145378768,
184 186056.26539522349504029498971604569928220784236328,
185 8071.6720023658162106380029022722506138218516325024,
186 210.82427775157934587250973392071336271166969580291,
187 2.5066282746310002701649081771338373386264310793408
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000188};
189
190/* denominator is x*(x+1)*...*(x+LANCZOS_N-2) */
191static const double lanczos_den_coeffs[LANCZOS_N] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 0.0, 39916800.0, 120543840.0, 150917976.0, 105258076.0, 45995730.0,
193 13339535.0, 2637558.0, 357423.0, 32670.0, 1925.0, 66.0, 1.0};
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000194
195/* gamma values for small positive integers, 1 though NGAMMA_INTEGRAL */
196#define NGAMMA_INTEGRAL 23
197static const double gamma_integral[NGAMMA_INTEGRAL] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0,
199 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0,
200 1307674368000.0, 20922789888000.0, 355687428096000.0,
201 6402373705728000.0, 121645100408832000.0, 2432902008176640000.0,
202 51090942171709440000.0, 1124000727777607680000.0,
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000203};
204
205/* Lanczos' sum L_g(x), for positive x */
206
207static double
208lanczos_sum(double x)
209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 double num = 0.0, den = 0.0;
211 int i;
212 assert(x > 0.0);
213 /* evaluate the rational function lanczos_sum(x). For large
214 x, the obvious algorithm risks overflow, so we instead
215 rescale the denominator and numerator of the rational
216 function by x**(1-LANCZOS_N) and treat this as a
217 rational function in 1/x. This also reduces the error for
218 larger x values. The choice of cutoff point (5.0 below) is
219 somewhat arbitrary; in tests, smaller cutoff values than
220 this resulted in lower accuracy. */
221 if (x < 5.0) {
222 for (i = LANCZOS_N; --i >= 0; ) {
223 num = num * x + lanczos_num_coeffs[i];
224 den = den * x + lanczos_den_coeffs[i];
225 }
226 }
227 else {
228 for (i = 0; i < LANCZOS_N; i++) {
229 num = num / x + lanczos_num_coeffs[i];
230 den = den / x + lanczos_den_coeffs[i];
231 }
232 }
233 return num/den;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000234}
235
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +0000236/* Constant for +infinity, generated in the same way as float('inf'). */
237
238static double
239m_inf(void)
240{
241#ifndef PY_NO_SHORT_FLOAT_REPR
242 return _Py_dg_infinity(0);
243#else
244 return Py_HUGE_VAL;
245#endif
246}
247
248/* Constant nan value, generated in the same way as float('nan'). */
249/* We don't currently assume that Py_NAN is defined everywhere. */
250
251#if !defined(PY_NO_SHORT_FLOAT_REPR) || defined(Py_NAN)
252
253static double
254m_nan(void)
255{
256#ifndef PY_NO_SHORT_FLOAT_REPR
257 return _Py_dg_stdnan(0);
258#else
259 return Py_NAN;
260#endif
261}
262
263#endif
264
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000265static double
266m_tgamma(double x)
267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 double absx, r, y, z, sqrtpow;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 /* special cases */
271 if (!Py_IS_FINITE(x)) {
272 if (Py_IS_NAN(x) || x > 0.0)
273 return x; /* tgamma(nan) = nan, tgamma(inf) = inf */
274 else {
275 errno = EDOM;
276 return Py_NAN; /* tgamma(-inf) = nan, invalid */
277 }
278 }
279 if (x == 0.0) {
280 errno = EDOM;
Mark Dickinson50203a62011-09-25 15:26:43 +0100281 /* tgamma(+-0.0) = +-inf, divide-by-zero */
282 return copysign(Py_HUGE_VAL, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 /* integer arguments */
286 if (x == floor(x)) {
287 if (x < 0.0) {
288 errno = EDOM; /* tgamma(n) = nan, invalid for */
289 return Py_NAN; /* negative integers n */
290 }
291 if (x <= NGAMMA_INTEGRAL)
292 return gamma_integral[(int)x - 1];
293 }
294 absx = fabs(x);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 /* tiny arguments: tgamma(x) ~ 1/x for x near 0 */
297 if (absx < 1e-20) {
298 r = 1.0/x;
299 if (Py_IS_INFINITY(r))
300 errno = ERANGE;
301 return r;
302 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 /* large arguments: assuming IEEE 754 doubles, tgamma(x) overflows for
305 x > 200, and underflows to +-0.0 for x < -200, not a negative
306 integer. */
307 if (absx > 200.0) {
308 if (x < 0.0) {
309 return 0.0/sinpi(x);
310 }
311 else {
312 errno = ERANGE;
313 return Py_HUGE_VAL;
314 }
315 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 y = absx + lanczos_g_minus_half;
318 /* compute error in sum */
319 if (absx > lanczos_g_minus_half) {
320 /* note: the correction can be foiled by an optimizing
321 compiler that (incorrectly) thinks that an expression like
322 a + b - a - b can be optimized to 0.0. This shouldn't
323 happen in a standards-conforming compiler. */
324 double q = y - absx;
325 z = q - lanczos_g_minus_half;
326 }
327 else {
328 double q = y - lanczos_g_minus_half;
329 z = q - absx;
330 }
331 z = z * lanczos_g / y;
332 if (x < 0.0) {
333 r = -pi / sinpi(absx) / absx * exp(y) / lanczos_sum(absx);
334 r -= z * r;
335 if (absx < 140.0) {
336 r /= pow(y, absx - 0.5);
337 }
338 else {
339 sqrtpow = pow(y, absx / 2.0 - 0.25);
340 r /= sqrtpow;
341 r /= sqrtpow;
342 }
343 }
344 else {
345 r = lanczos_sum(absx) / exp(y);
346 r += z * r;
347 if (absx < 140.0) {
348 r *= pow(y, absx - 0.5);
349 }
350 else {
351 sqrtpow = pow(y, absx / 2.0 - 0.25);
352 r *= sqrtpow;
353 r *= sqrtpow;
354 }
355 }
356 if (Py_IS_INFINITY(r))
357 errno = ERANGE;
358 return r;
Guido van Rossum8832b621991-12-16 15:44:24 +0000359}
360
Christian Heimes53876d92008-04-19 00:31:39 +0000361/*
Mark Dickinson05d2e082009-12-11 20:17:17 +0000362 lgamma: natural log of the absolute value of the Gamma function.
363 For large arguments, Lanczos' formula works extremely well here.
364*/
365
366static double
367m_lgamma(double x)
368{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200369 double r;
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200370 double absx;
Mark Dickinson05d2e082009-12-11 20:17:17 +0000371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 /* special cases */
373 if (!Py_IS_FINITE(x)) {
374 if (Py_IS_NAN(x))
375 return x; /* lgamma(nan) = nan */
376 else
377 return Py_HUGE_VAL; /* lgamma(+-inf) = +inf */
378 }
Mark Dickinson05d2e082009-12-11 20:17:17 +0000379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 /* integer arguments */
381 if (x == floor(x) && x <= 2.0) {
382 if (x <= 0.0) {
383 errno = EDOM; /* lgamma(n) = inf, divide-by-zero for */
384 return Py_HUGE_VAL; /* integers n <= 0 */
385 }
386 else {
387 return 0.0; /* lgamma(1) = lgamma(2) = 0.0 */
388 }
389 }
Mark Dickinson05d2e082009-12-11 20:17:17 +0000390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 absx = fabs(x);
392 /* tiny arguments: lgamma(x) ~ -log(fabs(x)) for small x */
393 if (absx < 1e-20)
394 return -log(absx);
Mark Dickinson05d2e082009-12-11 20:17:17 +0000395
Mark Dickinson9c91eb82010-07-07 16:17:31 +0000396 /* Lanczos' formula. We could save a fraction of a ulp in accuracy by
397 having a second set of numerator coefficients for lanczos_sum that
398 absorbed the exp(-lanczos_g) term, and throwing out the lanczos_g
399 subtraction below; it's probably not worth it. */
400 r = log(lanczos_sum(absx)) - lanczos_g;
401 r += (absx - 0.5) * (log(absx + lanczos_g - 0.5) - 1);
402 if (x < 0.0)
403 /* Use reflection formula to get value for negative x. */
404 r = logpi - log(fabs(sinpi(absx))) - log(absx) - r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 if (Py_IS_INFINITY(r))
406 errno = ERANGE;
407 return r;
Mark Dickinson05d2e082009-12-11 20:17:17 +0000408}
409
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200410#if !defined(HAVE_ERF) || !defined(HAVE_ERFC)
411
Mark Dickinson45f992a2009-12-19 11:20:49 +0000412/*
413 Implementations of the error function erf(x) and the complementary error
414 function erfc(x).
415
Brett Cannon45adb312016-01-15 09:38:24 -0800416 Method: we use a series approximation for erf for small x, and a continued
417 fraction approximation for erfc(x) for larger x;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000418 combined with the relations erf(-x) = -erf(x) and erfc(x) = 1.0 - erf(x),
419 this gives us erf(x) and erfc(x) for all x.
420
421 The series expansion used is:
422
423 erf(x) = x*exp(-x*x)/sqrt(pi) * [
424 2/1 + 4/3 x**2 + 8/15 x**4 + 16/105 x**6 + ...]
425
426 The coefficient of x**(2k-2) here is 4**k*factorial(k)/factorial(2*k).
427 This series converges well for smallish x, but slowly for larger x.
428
429 The continued fraction expansion used is:
430
431 erfc(x) = x*exp(-x*x)/sqrt(pi) * [1/(0.5 + x**2 -) 0.5/(2.5 + x**2 - )
432 3.0/(4.5 + x**2 - ) 7.5/(6.5 + x**2 - ) ...]
433
434 after the first term, the general term has the form:
435
436 k*(k-0.5)/(2*k+0.5 + x**2 - ...).
437
438 This expansion converges fast for larger x, but convergence becomes
439 infinitely slow as x approaches 0.0. The (somewhat naive) continued
440 fraction evaluation algorithm used below also risks overflow for large x;
441 but for large x, erfc(x) == 0.0 to within machine precision. (For
442 example, erfc(30.0) is approximately 2.56e-393).
443
444 Parameters: use series expansion for abs(x) < ERF_SERIES_CUTOFF and
445 continued fraction expansion for ERF_SERIES_CUTOFF <= abs(x) <
446 ERFC_CONTFRAC_CUTOFF. ERFC_SERIES_TERMS and ERFC_CONTFRAC_TERMS are the
447 numbers of terms to use for the relevant expansions. */
448
449#define ERF_SERIES_CUTOFF 1.5
450#define ERF_SERIES_TERMS 25
451#define ERFC_CONTFRAC_CUTOFF 30.0
452#define ERFC_CONTFRAC_TERMS 50
453
454/*
455 Error function, via power series.
456
457 Given a finite float x, return an approximation to erf(x).
458 Converges reasonably fast for small x.
459*/
460
461static double
462m_erf_series(double x)
463{
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000464 double x2, acc, fk, result;
465 int i, saved_errno;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 x2 = x * x;
468 acc = 0.0;
469 fk = (double)ERF_SERIES_TERMS + 0.5;
470 for (i = 0; i < ERF_SERIES_TERMS; i++) {
471 acc = 2.0 + x2 * acc / fk;
472 fk -= 1.0;
473 }
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000474 /* Make sure the exp call doesn't affect errno;
475 see m_erfc_contfrac for more. */
476 saved_errno = errno;
477 result = acc * x * exp(-x2) / sqrtpi;
478 errno = saved_errno;
479 return result;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000480}
481
482/*
483 Complementary error function, via continued fraction expansion.
484
485 Given a positive float x, return an approximation to erfc(x). Converges
486 reasonably fast for x large (say, x > 2.0), and should be safe from
487 overflow if x and nterms are not too large. On an IEEE 754 machine, with x
488 <= 30.0, we're safe up to nterms = 100. For x >= 30.0, erfc(x) is smaller
489 than the smallest representable nonzero float. */
490
491static double
492m_erfc_contfrac(double x)
493{
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000494 double x2, a, da, p, p_last, q, q_last, b, result;
495 int i, saved_errno;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 if (x >= ERFC_CONTFRAC_CUTOFF)
498 return 0.0;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 x2 = x*x;
501 a = 0.0;
502 da = 0.5;
503 p = 1.0; p_last = 0.0;
504 q = da + x2; q_last = 1.0;
505 for (i = 0; i < ERFC_CONTFRAC_TERMS; i++) {
506 double temp;
507 a += da;
508 da += 2.0;
509 b = da + x2;
510 temp = p; p = b*p - a*p_last; p_last = temp;
511 temp = q; q = b*q - a*q_last; q_last = temp;
512 }
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000513 /* Issue #8986: On some platforms, exp sets errno on underflow to zero;
514 save the current errno value so that we can restore it later. */
515 saved_errno = errno;
516 result = p / q * x * exp(-x2) / sqrtpi;
517 errno = saved_errno;
518 return result;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000519}
520
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200521#endif /* !defined(HAVE_ERF) || !defined(HAVE_ERFC) */
522
Mark Dickinson45f992a2009-12-19 11:20:49 +0000523/* Error function erf(x), for general x */
524
525static double
526m_erf(double x)
527{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200528#ifdef HAVE_ERF
529 return erf(x);
530#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 double absx, cf;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 if (Py_IS_NAN(x))
534 return x;
535 absx = fabs(x);
536 if (absx < ERF_SERIES_CUTOFF)
537 return m_erf_series(x);
538 else {
539 cf = m_erfc_contfrac(absx);
540 return x > 0.0 ? 1.0 - cf : cf - 1.0;
541 }
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200542#endif
Mark Dickinson45f992a2009-12-19 11:20:49 +0000543}
544
545/* Complementary error function erfc(x), for general x. */
546
547static double
548m_erfc(double x)
549{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200550#ifdef HAVE_ERFC
551 return erfc(x);
552#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 double absx, cf;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 if (Py_IS_NAN(x))
556 return x;
557 absx = fabs(x);
558 if (absx < ERF_SERIES_CUTOFF)
559 return 1.0 - m_erf_series(x);
560 else {
561 cf = m_erfc_contfrac(absx);
562 return x > 0.0 ? cf : 2.0 - cf;
563 }
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200564#endif
Mark Dickinson45f992a2009-12-19 11:20:49 +0000565}
Mark Dickinson05d2e082009-12-11 20:17:17 +0000566
567/*
Christian Heimese57950f2008-04-21 13:08:03 +0000568 wrapper for atan2 that deals directly with special cases before
569 delegating to the platform libm for the remaining cases. This
570 is necessary to get consistent behaviour across platforms.
571 Windows, FreeBSD and alpha Tru64 are amongst platforms that don't
572 always follow C99.
573*/
574
575static double
576m_atan2(double y, double x)
577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 if (Py_IS_NAN(x) || Py_IS_NAN(y))
579 return Py_NAN;
580 if (Py_IS_INFINITY(y)) {
581 if (Py_IS_INFINITY(x)) {
582 if (copysign(1., x) == 1.)
583 /* atan2(+-inf, +inf) == +-pi/4 */
584 return copysign(0.25*Py_MATH_PI, y);
585 else
586 /* atan2(+-inf, -inf) == +-pi*3/4 */
587 return copysign(0.75*Py_MATH_PI, y);
588 }
589 /* atan2(+-inf, x) == +-pi/2 for finite x */
590 return copysign(0.5*Py_MATH_PI, y);
591 }
592 if (Py_IS_INFINITY(x) || y == 0.) {
593 if (copysign(1., x) == 1.)
594 /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */
595 return copysign(0., y);
596 else
597 /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */
598 return copysign(Py_MATH_PI, y);
599 }
600 return atan2(y, x);
Christian Heimese57950f2008-04-21 13:08:03 +0000601}
602
603/*
Mark Dickinsone675f082008-12-11 21:56:00 +0000604 Various platforms (Solaris, OpenBSD) do nonstandard things for log(0),
605 log(-ve), log(NaN). Here are wrappers for log and log10 that deal with
606 special values directly, passing positive non-special values through to
607 the system log/log10.
608 */
609
610static double
611m_log(double x)
612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 if (Py_IS_FINITE(x)) {
614 if (x > 0.0)
615 return log(x);
616 errno = EDOM;
617 if (x == 0.0)
618 return -Py_HUGE_VAL; /* log(0) = -inf */
619 else
620 return Py_NAN; /* log(-ve) = nan */
621 }
622 else if (Py_IS_NAN(x))
623 return x; /* log(nan) = nan */
624 else if (x > 0.0)
625 return x; /* log(inf) = inf */
626 else {
627 errno = EDOM;
628 return Py_NAN; /* log(-inf) = nan */
629 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000630}
631
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200632/*
633 log2: log to base 2.
634
635 Uses an algorithm that should:
Mark Dickinson83b8c0b2011-05-09 08:40:20 +0100636
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200637 (a) produce exact results for powers of 2, and
Mark Dickinson83b8c0b2011-05-09 08:40:20 +0100638 (b) give a monotonic log2 (for positive finite floats),
639 assuming that the system log is monotonic.
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200640*/
641
642static double
643m_log2(double x)
644{
645 if (!Py_IS_FINITE(x)) {
646 if (Py_IS_NAN(x))
647 return x; /* log2(nan) = nan */
648 else if (x > 0.0)
649 return x; /* log2(+inf) = +inf */
650 else {
651 errno = EDOM;
652 return Py_NAN; /* log2(-inf) = nan, invalid-operation */
653 }
654 }
655
656 if (x > 0.0) {
Victor Stinner8f9f8d62011-05-09 12:45:41 +0200657#ifdef HAVE_LOG2
658 return log2(x);
659#else
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200660 double m;
661 int e;
662 m = frexp(x, &e);
663 /* We want log2(m * 2**e) == log(m) / log(2) + e. Care is needed when
664 * x is just greater than 1.0: in that case e is 1, log(m) is negative,
665 * and we get significant cancellation error from the addition of
666 * log(m) / log(2) to e. The slight rewrite of the expression below
667 * avoids this problem.
668 */
669 if (x >= 1.0) {
670 return log(2.0 * m) / log(2.0) + (e - 1);
671 }
672 else {
673 return log(m) / log(2.0) + e;
674 }
Victor Stinner8f9f8d62011-05-09 12:45:41 +0200675#endif
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200676 }
677 else if (x == 0.0) {
678 errno = EDOM;
679 return -Py_HUGE_VAL; /* log2(0) = -inf, divide-by-zero */
680 }
681 else {
682 errno = EDOM;
Mark Dickinson23442582011-05-09 08:05:00 +0100683 return Py_NAN; /* log2(-inf) = nan, invalid-operation */
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200684 }
685}
686
Mark Dickinsone675f082008-12-11 21:56:00 +0000687static double
688m_log10(double x)
689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 if (Py_IS_FINITE(x)) {
691 if (x > 0.0)
692 return log10(x);
693 errno = EDOM;
694 if (x == 0.0)
695 return -Py_HUGE_VAL; /* log10(0) = -inf */
696 else
697 return Py_NAN; /* log10(-ve) = nan */
698 }
699 else if (Py_IS_NAN(x))
700 return x; /* log10(nan) = nan */
701 else if (x > 0.0)
702 return x; /* log10(inf) = inf */
703 else {
704 errno = EDOM;
705 return Py_NAN; /* log10(-inf) = nan */
706 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000707}
708
709
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200710/*[clinic input]
711math.gcd
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300712
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200713 x as a: object
714 y as b: object
715 /
716
717greatest common divisor of x and y
718[clinic start generated code]*/
719
720static PyObject *
721math_gcd_impl(PyObject *module, PyObject *a, PyObject *b)
722/*[clinic end generated code: output=7b2e0c151bd7a5d8 input=c2691e57fb2a98fa]*/
723{
724 PyObject *g;
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300725
726 a = PyNumber_Index(a);
727 if (a == NULL)
728 return NULL;
729 b = PyNumber_Index(b);
730 if (b == NULL) {
731 Py_DECREF(a);
732 return NULL;
733 }
734 g = _PyLong_GCD(a, b);
735 Py_DECREF(a);
736 Py_DECREF(b);
737 return g;
738}
739
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300740
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000741/* Call is_error when errno != 0, and where x is the result libm
742 * returned. is_error will usually set up an exception and return
743 * true (1), but may return false (0) without setting up an exception.
744 */
745static int
746is_error(double x)
747{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 int result = 1; /* presumption of guilt */
749 assert(errno); /* non-zero errno is a precondition for calling */
750 if (errno == EDOM)
751 PyErr_SetString(PyExc_ValueError, "math domain error");
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 else if (errno == ERANGE) {
754 /* ANSI C generally requires libm functions to set ERANGE
755 * on overflow, but also generally *allows* them to set
756 * ERANGE on underflow too. There's no consistency about
757 * the latter across platforms.
758 * Alas, C99 never requires that errno be set.
759 * Here we suppress the underflow errors (libm functions
760 * should return a zero on underflow, and +- HUGE_VAL on
761 * overflow, so testing the result for zero suffices to
762 * distinguish the cases).
763 *
764 * On some platforms (Ubuntu/ia64) it seems that errno can be
765 * set to ERANGE for subnormal results that do *not* underflow
766 * to zero. So to be safe, we'll ignore ERANGE whenever the
767 * function result is less than one in absolute value.
768 */
769 if (fabs(x) < 1.0)
770 result = 0;
771 else
772 PyErr_SetString(PyExc_OverflowError,
773 "math range error");
774 }
775 else
776 /* Unexpected math error */
777 PyErr_SetFromErrno(PyExc_ValueError);
778 return result;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000779}
780
Mark Dickinsone675f082008-12-11 21:56:00 +0000781/*
Christian Heimes53876d92008-04-19 00:31:39 +0000782 math_1 is used to wrap a libm function f that takes a double
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200783 argument and returns a double.
Christian Heimes53876d92008-04-19 00:31:39 +0000784
785 The error reporting follows these rules, which are designed to do
786 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
787 platforms.
788
789 - a NaN result from non-NaN inputs causes ValueError to be raised
790 - an infinite result from finite inputs causes OverflowError to be
791 raised if can_overflow is 1, or raises ValueError if can_overflow
792 is 0.
793 - if the result is finite and errno == EDOM then ValueError is
794 raised
795 - if the result is finite and nonzero and errno == ERANGE then
796 OverflowError is raised
797
798 The last rule is used to catch overflow on platforms which follow
799 C89 but for which HUGE_VAL is not an infinity.
800
801 For the majority of one-argument functions these rules are enough
802 to ensure that Python's functions behave as specified in 'Annex F'
803 of the C99 standard, with the 'invalid' and 'divide-by-zero'
804 floating-point exceptions mapping to Python's ValueError and the
805 'overflow' floating-point exception mapping to OverflowError.
806 math_1 only works for functions that don't have singularities *and*
807 the possibility of overflow; fortunately, that covers everything we
808 care about right now.
809*/
810
Barry Warsaw8b43b191996-12-09 22:32:36 +0000811static PyObject *
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000812math_1_to_whatever(PyObject *arg, double (*func) (double),
Christian Heimes53876d92008-04-19 00:31:39 +0000813 PyObject *(*from_double_func) (double),
814 int can_overflow)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000815{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 double x, r;
817 x = PyFloat_AsDouble(arg);
818 if (x == -1.0 && PyErr_Occurred())
819 return NULL;
820 errno = 0;
821 PyFPE_START_PROTECT("in math_1", return 0);
822 r = (*func)(x);
823 PyFPE_END_PROTECT(r);
824 if (Py_IS_NAN(r) && !Py_IS_NAN(x)) {
825 PyErr_SetString(PyExc_ValueError,
826 "math domain error"); /* invalid arg */
827 return NULL;
828 }
829 if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) {
Benjamin Peterson2354a752012-03-13 16:13:09 -0500830 if (can_overflow)
831 PyErr_SetString(PyExc_OverflowError,
832 "math range error"); /* overflow */
833 else
834 PyErr_SetString(PyExc_ValueError,
835 "math domain error"); /* singularity */
836 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 }
838 if (Py_IS_FINITE(r) && errno && is_error(r))
839 /* this branch unnecessary on most platforms */
840 return NULL;
Mark Dickinsonde429622008-05-01 00:19:23 +0000841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 return (*from_double_func)(r);
Christian Heimes53876d92008-04-19 00:31:39 +0000843}
844
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000845/* variant of math_1, to be used when the function being wrapped is known to
846 set errno properly (that is, errno = EDOM for invalid or divide-by-zero,
847 errno = ERANGE for overflow). */
848
849static PyObject *
850math_1a(PyObject *arg, double (*func) (double))
851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 double x, r;
853 x = PyFloat_AsDouble(arg);
854 if (x == -1.0 && PyErr_Occurred())
855 return NULL;
856 errno = 0;
857 PyFPE_START_PROTECT("in math_1a", return 0);
858 r = (*func)(x);
859 PyFPE_END_PROTECT(r);
860 if (errno && is_error(r))
861 return NULL;
862 return PyFloat_FromDouble(r);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000863}
864
Christian Heimes53876d92008-04-19 00:31:39 +0000865/*
866 math_2 is used to wrap a libm function f that takes two double
867 arguments and returns a double.
868
869 The error reporting follows these rules, which are designed to do
870 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
871 platforms.
872
873 - a NaN result from non-NaN inputs causes ValueError to be raised
874 - an infinite result from finite inputs causes OverflowError to be
875 raised.
876 - if the result is finite and errno == EDOM then ValueError is
877 raised
878 - if the result is finite and nonzero and errno == ERANGE then
879 OverflowError is raised
880
881 The last rule is used to catch overflow on platforms which follow
882 C89 but for which HUGE_VAL is not an infinity.
883
884 For most two-argument functions (copysign, fmod, hypot, atan2)
885 these rules are enough to ensure that Python's functions behave as
886 specified in 'Annex F' of the C99 standard, with the 'invalid' and
887 'divide-by-zero' floating-point exceptions mapping to Python's
888 ValueError and the 'overflow' floating-point exception mapping to
889 OverflowError.
890*/
891
892static PyObject *
893math_1(PyObject *arg, double (*func) (double), int can_overflow)
894{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow);
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000896}
897
898static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000899math_1_to_int(PyObject *arg, double (*func) (double), int can_overflow)
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000900{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 return math_1_to_whatever(arg, func, PyLong_FromDouble, can_overflow);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000902}
903
Barry Warsaw8b43b191996-12-09 22:32:36 +0000904static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200905math_2(PyObject *args, double (*func) (double, double), const char *funcname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000906{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 PyObject *ox, *oy;
908 double x, y, r;
909 if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy))
910 return NULL;
911 x = PyFloat_AsDouble(ox);
912 y = PyFloat_AsDouble(oy);
913 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
914 return NULL;
915 errno = 0;
916 PyFPE_START_PROTECT("in math_2", return 0);
917 r = (*func)(x, y);
918 PyFPE_END_PROTECT(r);
919 if (Py_IS_NAN(r)) {
920 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
921 errno = EDOM;
922 else
923 errno = 0;
924 }
925 else if (Py_IS_INFINITY(r)) {
926 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
927 errno = ERANGE;
928 else
929 errno = 0;
930 }
931 if (errno && is_error(r))
932 return NULL;
933 else
934 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000935}
936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937#define FUNC1(funcname, func, can_overflow, docstring) \
938 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
939 return math_1(args, func, can_overflow); \
940 }\
941 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943#define FUNC1A(funcname, func, docstring) \
944 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
945 return math_1a(args, func); \
946 }\
947 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000948
Fred Drake40c48682000-07-03 18:11:56 +0000949#define FUNC2(funcname, func, docstring) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
951 return math_2(args, func, #funcname); \
952 }\
953 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000954
Christian Heimes53876d92008-04-19 00:31:39 +0000955FUNC1(acos, acos, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200956 "acos($module, x, /)\n--\n\n"
957 "Return the arc cosine (measured in radians) of x.")
Mark Dickinsonf3718592009-12-21 15:27:41 +0000958FUNC1(acosh, m_acosh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200959 "acosh($module, x, /)\n--\n\n"
960 "Return the inverse hyperbolic cosine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000961FUNC1(asin, asin, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200962 "asin($module, x, /)\n--\n\n"
963 "Return the arc sine (measured in radians) of x.")
Mark Dickinsonf3718592009-12-21 15:27:41 +0000964FUNC1(asinh, m_asinh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200965 "asinh($module, x, /)\n--\n\n"
966 "Return the inverse hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000967FUNC1(atan, atan, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200968 "atan($module, x, /)\n--\n\n"
969 "Return the arc tangent (measured in radians) of x.")
Christian Heimese57950f2008-04-21 13:08:03 +0000970FUNC2(atan2, m_atan2,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200971 "atan2($module, y, x, /)\n--\n\n"
972 "Return the arc tangent (measured in radians) of y/x.\n\n"
Tim Petersfe71f812001-08-07 22:10:00 +0000973 "Unlike atan(y/x), the signs of both x and y are considered.")
Mark Dickinsonf3718592009-12-21 15:27:41 +0000974FUNC1(atanh, m_atanh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200975 "atanh($module, x, /)\n--\n\n"
976 "Return the inverse hyperbolic tangent of x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +0000977
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200978/*[clinic input]
979math.ceil
980
981 x as number: object
982 /
983
984Return the ceiling of x as an Integral.
985
986This is the smallest integer >= x.
987[clinic start generated code]*/
988
989static PyObject *
990math_ceil(PyObject *module, PyObject *number)
991/*[clinic end generated code: output=6c3b8a78bc201c67 input=2725352806399cab]*/
992{
Benjamin Petersonce798522012-01-22 11:24:29 -0500993 _Py_IDENTIFIER(__ceil__);
Mark Dickinson6d02d9c2010-07-02 16:05:15 +0000994 PyObject *method, *result;
Guido van Rossum13e05de2007-08-23 22:56:55 +0000995
Benjamin Petersonce798522012-01-22 11:24:29 -0500996 method = _PyObject_LookupSpecial(number, &PyId___ceil__);
Benjamin Petersonf751bc92010-07-02 13:46:42 +0000997 if (method == NULL) {
998 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 return math_1_to_int(number, ceil, 0);
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001001 }
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001002 result = _PyObject_CallNoArg(method);
Mark Dickinson6d02d9c2010-07-02 16:05:15 +00001003 Py_DECREF(method);
1004 return result;
Guido van Rossum13e05de2007-08-23 22:56:55 +00001005}
1006
Christian Heimes072c0f12008-01-03 23:01:04 +00001007FUNC2(copysign, copysign,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001008 "copysign($module, x, y, /)\n--\n\n"
1009 "Return a float with the magnitude (absolute value) of x but the sign of y.\n\n"
1010 "On platforms that support signed zeros, copysign(1.0, -0.0)\n"
1011 "returns -1.0.\n")
Christian Heimes53876d92008-04-19 00:31:39 +00001012FUNC1(cos, cos, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001013 "cos($module, x, /)\n--\n\n"
1014 "Return the cosine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001015FUNC1(cosh, cosh, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001016 "cosh($module, x, /)\n--\n\n"
1017 "Return the hyperbolic cosine of x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +00001018FUNC1A(erf, m_erf,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001019 "erf($module, x, /)\n--\n\n"
1020 "Error function at x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +00001021FUNC1A(erfc, m_erfc,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001022 "erfc($module, x, /)\n--\n\n"
1023 "Complementary error function at x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001024FUNC1(exp, exp, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001025 "exp($module, x, /)\n--\n\n"
1026 "Return e raised to the power of x.")
Mark Dickinson664b5112009-12-16 20:23:42 +00001027FUNC1(expm1, m_expm1, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001028 "expm1($module, x, /)\n--\n\n"
1029 "Return exp(x)-1.\n\n"
Mark Dickinson664b5112009-12-16 20:23:42 +00001030 "This function avoids the loss of precision involved in the direct "
1031 "evaluation of exp(x)-1 for small x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001032FUNC1(fabs, fabs, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001033 "fabs($module, x, /)\n--\n\n"
1034 "Return the absolute value of the float x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +00001035
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001036/*[clinic input]
1037math.floor
1038
1039 x as number: object
1040 /
1041
1042Return the floor of x as an Integral.
1043
1044This is the largest integer <= x.
1045[clinic start generated code]*/
1046
1047static PyObject *
1048math_floor(PyObject *module, PyObject *number)
1049/*[clinic end generated code: output=c6a65c4884884b8a input=63af6b5d7ebcc3d6]*/
1050{
Benjamin Petersonce798522012-01-22 11:24:29 -05001051 _Py_IDENTIFIER(__floor__);
Benjamin Petersonb0125892010-07-02 13:35:17 +00001052 PyObject *method, *result;
Guido van Rossum13e05de2007-08-23 22:56:55 +00001053
Benjamin Petersonce798522012-01-22 11:24:29 -05001054 method = _PyObject_LookupSpecial(number, &PyId___floor__);
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001055 if (method == NULL) {
1056 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 return math_1_to_int(number, floor, 0);
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001059 }
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001060 result = _PyObject_CallNoArg(method);
Benjamin Petersonb0125892010-07-02 13:35:17 +00001061 Py_DECREF(method);
1062 return result;
Guido van Rossum13e05de2007-08-23 22:56:55 +00001063}
1064
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001065FUNC1A(gamma, m_tgamma,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001066 "gamma($module, x, /)\n--\n\n"
1067 "Gamma function at x.")
Mark Dickinson05d2e082009-12-11 20:17:17 +00001068FUNC1A(lgamma, m_lgamma,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001069 "lgamma($module, x, /)\n--\n\n"
1070 "Natural logarithm of absolute value of Gamma function at x.")
Mark Dickinsonbe64d952010-07-07 16:21:29 +00001071FUNC1(log1p, m_log1p, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001072 "log1p($module, x, /)\n--\n\n"
1073 "Return the natural logarithm of 1+x (base e).\n\n"
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001074 "The result is computed in a way which is accurate for x near zero.")
Christian Heimes53876d92008-04-19 00:31:39 +00001075FUNC1(sin, sin, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001076 "sin($module, x, /)\n--\n\n"
1077 "Return the sine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001078FUNC1(sinh, sinh, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001079 "sinh($module, x, /)\n--\n\n"
1080 "Return the hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001081FUNC1(sqrt, sqrt, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001082 "sqrt($module, x, /)\n--\n\n"
1083 "Return the square root of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001084FUNC1(tan, tan, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001085 "tan($module, x, /)\n--\n\n"
1086 "Return the tangent of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001087FUNC1(tanh, tanh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001088 "tanh($module, x, /)\n--\n\n"
1089 "Return the hyperbolic tangent of x.")
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001090
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001091/* Precision summation function as msum() by Raymond Hettinger in
1092 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
1093 enhanced with the exact partials sum and roundoff from Mark
1094 Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
1095 See those links for more details, proofs and other references.
1096
1097 Note 1: IEEE 754R floating point semantics are assumed,
1098 but the current implementation does not re-establish special
1099 value semantics across iterations (i.e. handling -Inf + Inf).
1100
1101 Note 2: No provision is made for intermediate overflow handling;
Georg Brandlf78e02b2008-06-10 17:40:04 +00001102 therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001103 sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
1104 overflow of the first partial sum.
1105
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001106 Note 3: The intermediate values lo, yr, and hi are declared volatile so
1107 aggressive compilers won't algebraically reduce lo to always be exactly 0.0.
Georg Brandlf78e02b2008-06-10 17:40:04 +00001108 Also, the volatile declaration forces the values to be stored in memory as
1109 regular doubles instead of extended long precision (80-bit) values. This
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001110 prevents double rounding because any addition or subtraction of two doubles
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 can be resolved exactly into double-sized hi and lo values. As long as the
Georg Brandlf78e02b2008-06-10 17:40:04 +00001112 hi value gets forced into a double before yr and lo are computed, the extra
1113 bits in downstream extended precision operations (x87 for example) will be
1114 exactly zero and therefore can be losslessly stored back into a double,
1115 thereby preventing double rounding.
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001116
1117 Note 4: A similar implementation is in Modules/cmathmodule.c.
1118 Be sure to update both when making changes.
1119
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001120 Note 5: The signature of math.fsum() differs from builtins.sum()
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001121 because the start argument doesn't make sense in the context of
1122 accurate summation. Since the partials table is collapsed before
1123 returning a result, sum(seq2, start=sum(seq1)) may not equal the
1124 accurate result returned by sum(itertools.chain(seq1, seq2)).
1125*/
1126
1127#define NUM_PARTIALS 32 /* initial partials array size, on stack */
1128
1129/* Extend the partials array p[] by doubling its size. */
1130static int /* non-zero on error */
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001131_fsum_realloc(double **p_ptr, Py_ssize_t n,
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001132 double *ps, Py_ssize_t *m_ptr)
1133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 void *v = NULL;
1135 Py_ssize_t m = *m_ptr;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 m += m; /* double */
Victor Stinner049e5092014-08-17 22:20:00 +02001138 if (n < m && (size_t)m < ((size_t)PY_SSIZE_T_MAX / sizeof(double))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 double *p = *p_ptr;
1140 if (p == ps) {
1141 v = PyMem_Malloc(sizeof(double) * m);
1142 if (v != NULL)
1143 memcpy(v, ps, sizeof(double) * n);
1144 }
1145 else
1146 v = PyMem_Realloc(p, sizeof(double) * m);
1147 }
1148 if (v == NULL) { /* size overflow or no memory */
1149 PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
1150 return 1;
1151 }
1152 *p_ptr = (double*) v;
1153 *m_ptr = m;
1154 return 0;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001155}
1156
1157/* Full precision summation of a sequence of floats.
1158
1159 def msum(iterable):
1160 partials = [] # sorted, non-overlapping partial sums
1161 for x in iterable:
Mark Dickinsonfdb0acc2010-06-25 20:22:24 +00001162 i = 0
1163 for y in partials:
1164 if abs(x) < abs(y):
1165 x, y = y, x
1166 hi = x + y
1167 lo = y - (hi - x)
1168 if lo:
1169 partials[i] = lo
1170 i += 1
1171 x = hi
1172 partials[i:] = [x]
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001173 return sum_exact(partials)
1174
1175 Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
1176 are exactly equal to x+y. The inner loop applies hi/lo summation to each
1177 partial so that the list of partial sums remains exact.
1178
1179 Sum_exact() adds the partial sums exactly and correctly rounds the final
1180 result (using the round-half-to-even rule). The items in partials remain
1181 non-zero, non-special, non-overlapping and strictly increasing in
1182 magnitude, but possibly not all having the same sign.
1183
1184 Depends on IEEE 754 arithmetic guarantees and half-even rounding.
1185*/
1186
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001187/*[clinic input]
1188math.fsum
1189
1190 seq: object
1191 /
1192
1193Return an accurate floating point sum of values in the iterable seq.
1194
1195Assumes IEEE-754 floating point arithmetic.
1196[clinic start generated code]*/
1197
1198static PyObject *
1199math_fsum(PyObject *module, PyObject *seq)
1200/*[clinic end generated code: output=ba5c672b87fe34fc input=c51b7d8caf6f6e82]*/
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 PyObject *item, *iter, *sum = NULL;
1203 Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
1204 double x, y, t, ps[NUM_PARTIALS], *p = ps;
1205 double xsave, special_sum = 0.0, inf_sum = 0.0;
1206 volatile double hi, yr, lo;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 iter = PyObject_GetIter(seq);
1209 if (iter == NULL)
1210 return NULL;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 for(;;) { /* for x in iterable */
1215 assert(0 <= n && n <= m);
1216 assert((m == NUM_PARTIALS && p == ps) ||
1217 (m > NUM_PARTIALS && p != NULL));
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 item = PyIter_Next(iter);
1220 if (item == NULL) {
1221 if (PyErr_Occurred())
1222 goto _fsum_error;
1223 break;
1224 }
1225 x = PyFloat_AsDouble(item);
1226 Py_DECREF(item);
1227 if (PyErr_Occurred())
1228 goto _fsum_error;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 xsave = x;
1231 for (i = j = 0; j < n; j++) { /* for y in partials */
1232 y = p[j];
1233 if (fabs(x) < fabs(y)) {
1234 t = x; x = y; y = t;
1235 }
1236 hi = x + y;
1237 yr = hi - x;
1238 lo = y - yr;
1239 if (lo != 0.0)
1240 p[i++] = lo;
1241 x = hi;
1242 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 n = i; /* ps[i:] = [x] */
1245 if (x != 0.0) {
1246 if (! Py_IS_FINITE(x)) {
1247 /* a nonfinite x could arise either as
1248 a result of intermediate overflow, or
1249 as a result of a nan or inf in the
1250 summands */
1251 if (Py_IS_FINITE(xsave)) {
1252 PyErr_SetString(PyExc_OverflowError,
1253 "intermediate overflow in fsum");
1254 goto _fsum_error;
1255 }
1256 if (Py_IS_INFINITY(xsave))
1257 inf_sum += xsave;
1258 special_sum += xsave;
1259 /* reset partials */
1260 n = 0;
1261 }
1262 else if (n >= m && _fsum_realloc(&p, n, ps, &m))
1263 goto _fsum_error;
1264 else
1265 p[n++] = x;
1266 }
1267 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 if (special_sum != 0.0) {
1270 if (Py_IS_NAN(inf_sum))
1271 PyErr_SetString(PyExc_ValueError,
1272 "-inf + inf in fsum");
1273 else
1274 sum = PyFloat_FromDouble(special_sum);
1275 goto _fsum_error;
1276 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 hi = 0.0;
1279 if (n > 0) {
1280 hi = p[--n];
1281 /* sum_exact(ps, hi) from the top, stop when the sum becomes
1282 inexact. */
1283 while (n > 0) {
1284 x = hi;
1285 y = p[--n];
1286 assert(fabs(y) < fabs(x));
1287 hi = x + y;
1288 yr = hi - x;
1289 lo = y - yr;
1290 if (lo != 0.0)
1291 break;
1292 }
1293 /* Make half-even rounding work across multiple partials.
1294 Needed so that sum([1e-16, 1, 1e16]) will round-up the last
1295 digit to two instead of down to zero (the 1e-16 makes the 1
1296 slightly closer to two). With a potential 1 ULP rounding
1297 error fixed-up, math.fsum() can guarantee commutativity. */
1298 if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
1299 (lo > 0.0 && p[n-1] > 0.0))) {
1300 y = lo * 2.0;
1301 x = hi + y;
1302 yr = x - hi;
1303 if (y == yr)
1304 hi = x;
1305 }
1306 }
1307 sum = PyFloat_FromDouble(hi);
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001308
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001309_fsum_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 PyFPE_END_PROTECT(hi)
1311 Py_DECREF(iter);
1312 if (p != ps)
1313 PyMem_Free(p);
1314 return sum;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001315}
1316
1317#undef NUM_PARTIALS
1318
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001319
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001320/* Return the smallest integer k such that n < 2**k, or 0 if n == 0.
1321 * Equivalent to floor(lg(x))+1. Also equivalent to: bitwidth_of_type -
1322 * count_leading_zero_bits(x)
1323 */
1324
1325/* XXX: This routine does more or less the same thing as
1326 * bits_in_digit() in Objects/longobject.c. Someday it would be nice to
1327 * consolidate them. On BSD, there's a library function called fls()
1328 * that we could use, and GCC provides __builtin_clz().
1329 */
1330
1331static unsigned long
1332bit_length(unsigned long n)
1333{
1334 unsigned long len = 0;
1335 while (n != 0) {
1336 ++len;
1337 n >>= 1;
1338 }
1339 return len;
1340}
1341
1342static unsigned long
1343count_set_bits(unsigned long n)
1344{
1345 unsigned long count = 0;
1346 while (n != 0) {
1347 ++count;
1348 n &= n - 1; /* clear least significant bit */
1349 }
1350 return count;
1351}
1352
1353/* Divide-and-conquer factorial algorithm
1354 *
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07001355 * Based on the formula and pseudo-code provided at:
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001356 * http://www.luschny.de/math/factorial/binarysplitfact.html
1357 *
1358 * Faster algorithms exist, but they're more complicated and depend on
Ezio Melotti9527afd2010-07-08 15:03:02 +00001359 * a fast prime factorization algorithm.
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001360 *
1361 * Notes on the algorithm
1362 * ----------------------
1363 *
1364 * factorial(n) is written in the form 2**k * m, with m odd. k and m are
1365 * computed separately, and then combined using a left shift.
1366 *
1367 * The function factorial_odd_part computes the odd part m (i.e., the greatest
1368 * odd divisor) of factorial(n), using the formula:
1369 *
1370 * factorial_odd_part(n) =
1371 *
1372 * product_{i >= 0} product_{0 < j <= n / 2**i, j odd} j
1373 *
1374 * Example: factorial_odd_part(20) =
1375 *
1376 * (1) *
1377 * (1) *
1378 * (1 * 3 * 5) *
1379 * (1 * 3 * 5 * 7 * 9)
1380 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1381 *
1382 * Here i goes from large to small: the first term corresponds to i=4 (any
1383 * larger i gives an empty product), and the last term corresponds to i=0.
1384 * Each term can be computed from the last by multiplying by the extra odd
1385 * numbers required: e.g., to get from the penultimate term to the last one,
1386 * we multiply by (11 * 13 * 15 * 17 * 19).
1387 *
1388 * To see a hint of why this formula works, here are the same numbers as above
1389 * but with the even parts (i.e., the appropriate powers of 2) included. For
1390 * each subterm in the product for i, we multiply that subterm by 2**i:
1391 *
1392 * factorial(20) =
1393 *
1394 * (16) *
1395 * (8) *
1396 * (4 * 12 * 20) *
1397 * (2 * 6 * 10 * 14 * 18) *
1398 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1399 *
1400 * The factorial_partial_product function computes the product of all odd j in
1401 * range(start, stop) for given start and stop. It's used to compute the
1402 * partial products like (11 * 13 * 15 * 17 * 19) in the example above. It
1403 * operates recursively, repeatedly splitting the range into two roughly equal
1404 * pieces until the subranges are small enough to be computed using only C
1405 * integer arithmetic.
1406 *
1407 * The two-valuation k (i.e., the exponent of the largest power of 2 dividing
1408 * the factorial) is computed independently in the main math_factorial
1409 * function. By standard results, its value is:
1410 *
1411 * two_valuation = n//2 + n//4 + n//8 + ....
1412 *
1413 * It can be shown (e.g., by complete induction on n) that two_valuation is
1414 * equal to n - count_set_bits(n), where count_set_bits(n) gives the number of
1415 * '1'-bits in the binary expansion of n.
1416 */
1417
1418/* factorial_partial_product: Compute product(range(start, stop, 2)) using
1419 * divide and conquer. Assumes start and stop are odd and stop > start.
1420 * max_bits must be >= bit_length(stop - 2). */
1421
1422static PyObject *
1423factorial_partial_product(unsigned long start, unsigned long stop,
1424 unsigned long max_bits)
1425{
1426 unsigned long midpoint, num_operands;
1427 PyObject *left = NULL, *right = NULL, *result = NULL;
1428
1429 /* If the return value will fit an unsigned long, then we can
1430 * multiply in a tight, fast loop where each multiply is O(1).
1431 * Compute an upper bound on the number of bits required to store
1432 * the answer.
1433 *
1434 * Storing some integer z requires floor(lg(z))+1 bits, which is
1435 * conveniently the value returned by bit_length(z). The
1436 * product x*y will require at most
1437 * bit_length(x) + bit_length(y) bits to store, based
1438 * on the idea that lg product = lg x + lg y.
1439 *
1440 * We know that stop - 2 is the largest number to be multiplied. From
1441 * there, we have: bit_length(answer) <= num_operands *
1442 * bit_length(stop - 2)
1443 */
1444
1445 num_operands = (stop - start) / 2;
1446 /* The "num_operands <= 8 * SIZEOF_LONG" check guards against the
1447 * unlikely case of an overflow in num_operands * max_bits. */
1448 if (num_operands <= 8 * SIZEOF_LONG &&
1449 num_operands * max_bits <= 8 * SIZEOF_LONG) {
1450 unsigned long j, total;
1451 for (total = start, j = start + 2; j < stop; j += 2)
1452 total *= j;
1453 return PyLong_FromUnsignedLong(total);
1454 }
1455
1456 /* find midpoint of range(start, stop), rounded up to next odd number. */
1457 midpoint = (start + num_operands) | 1;
1458 left = factorial_partial_product(start, midpoint,
1459 bit_length(midpoint - 2));
1460 if (left == NULL)
1461 goto error;
1462 right = factorial_partial_product(midpoint, stop, max_bits);
1463 if (right == NULL)
1464 goto error;
1465 result = PyNumber_Multiply(left, right);
1466
1467 error:
1468 Py_XDECREF(left);
1469 Py_XDECREF(right);
1470 return result;
1471}
1472
1473/* factorial_odd_part: compute the odd part of factorial(n). */
1474
1475static PyObject *
1476factorial_odd_part(unsigned long n)
1477{
1478 long i;
1479 unsigned long v, lower, upper;
1480 PyObject *partial, *tmp, *inner, *outer;
1481
1482 inner = PyLong_FromLong(1);
1483 if (inner == NULL)
1484 return NULL;
1485 outer = inner;
1486 Py_INCREF(outer);
1487
1488 upper = 3;
1489 for (i = bit_length(n) - 2; i >= 0; i--) {
1490 v = n >> i;
1491 if (v <= 2)
1492 continue;
1493 lower = upper;
1494 /* (v + 1) | 1 = least odd integer strictly larger than n / 2**i */
1495 upper = (v + 1) | 1;
1496 /* Here inner is the product of all odd integers j in the range (0,
1497 n/2**(i+1)]. The factorial_partial_product call below gives the
1498 product of all odd integers j in the range (n/2**(i+1), n/2**i]. */
1499 partial = factorial_partial_product(lower, upper, bit_length(upper-2));
1500 /* inner *= partial */
1501 if (partial == NULL)
1502 goto error;
1503 tmp = PyNumber_Multiply(inner, partial);
1504 Py_DECREF(partial);
1505 if (tmp == NULL)
1506 goto error;
1507 Py_DECREF(inner);
1508 inner = tmp;
1509 /* Now inner is the product of all odd integers j in the range (0,
1510 n/2**i], giving the inner product in the formula above. */
1511
1512 /* outer *= inner; */
1513 tmp = PyNumber_Multiply(outer, inner);
1514 if (tmp == NULL)
1515 goto error;
1516 Py_DECREF(outer);
1517 outer = tmp;
1518 }
Mark Dickinson76464492012-10-25 10:46:28 +01001519 Py_DECREF(inner);
1520 return outer;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001521
1522 error:
1523 Py_DECREF(outer);
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001524 Py_DECREF(inner);
Mark Dickinson76464492012-10-25 10:46:28 +01001525 return NULL;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001526}
1527
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001528
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001529/* Lookup table for small factorial values */
1530
1531static const unsigned long SmallFactorials[] = {
1532 1, 1, 2, 6, 24, 120, 720, 5040, 40320,
1533 362880, 3628800, 39916800, 479001600,
1534#if SIZEOF_LONG >= 8
1535 6227020800, 87178291200, 1307674368000,
1536 20922789888000, 355687428096000, 6402373705728000,
1537 121645100408832000, 2432902008176640000
1538#endif
1539};
1540
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001541/*[clinic input]
1542math.factorial
1543
1544 x as arg: object
1545 /
1546
1547Find x!.
1548
1549Raise a ValueError if x is negative or non-integral.
1550[clinic start generated code]*/
1551
Barry Warsaw8b43b191996-12-09 22:32:36 +00001552static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001553math_factorial(PyObject *module, PyObject *arg)
1554/*[clinic end generated code: output=6686f26fae00e9ca input=6d1c8105c0d91fb4]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001555{
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001556 long x;
Mark Dickinson5990d282014-04-10 09:29:39 -04001557 int overflow;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001558 PyObject *result, *odd_part, *two_valuation;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 if (PyFloat_Check(arg)) {
1561 PyObject *lx;
1562 double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
1563 if (!(Py_IS_FINITE(dx) && dx == floor(dx))) {
1564 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001565 "factorial() only accepts integral values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 return NULL;
1567 }
1568 lx = PyLong_FromDouble(dx);
1569 if (lx == NULL)
1570 return NULL;
Mark Dickinson5990d282014-04-10 09:29:39 -04001571 x = PyLong_AsLongAndOverflow(lx, &overflow);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 Py_DECREF(lx);
1573 }
1574 else
Mark Dickinson5990d282014-04-10 09:29:39 -04001575 x = PyLong_AsLongAndOverflow(arg, &overflow);
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001576
Mark Dickinson5990d282014-04-10 09:29:39 -04001577 if (x == -1 && PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 return NULL;
Mark Dickinson5990d282014-04-10 09:29:39 -04001579 }
1580 else if (overflow == 1) {
1581 PyErr_Format(PyExc_OverflowError,
1582 "factorial() argument should not exceed %ld",
1583 LONG_MAX);
1584 return NULL;
1585 }
1586 else if (overflow == -1 || x < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001588 "factorial() not defined for negative values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 return NULL;
1590 }
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001591
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001592 /* use lookup table if x is small */
Victor Stinner63941882011-09-29 00:42:28 +02001593 if (x < (long)Py_ARRAY_LENGTH(SmallFactorials))
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001594 return PyLong_FromUnsignedLong(SmallFactorials[x]);
1595
1596 /* else express in the form odd_part * 2**two_valuation, and compute as
1597 odd_part << two_valuation. */
1598 odd_part = factorial_odd_part(x);
1599 if (odd_part == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 return NULL;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001601 two_valuation = PyLong_FromLong(x - count_set_bits(x));
1602 if (two_valuation == NULL) {
1603 Py_DECREF(odd_part);
1604 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 }
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001606 result = PyNumber_Lshift(odd_part, two_valuation);
1607 Py_DECREF(two_valuation);
1608 Py_DECREF(odd_part);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 return result;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001610}
1611
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001612
1613/*[clinic input]
1614math.trunc
1615
1616 x: object
1617 /
1618
1619Truncates the Real x to the nearest Integral toward 0.
1620
1621Uses the __trunc__ magic method.
1622[clinic start generated code]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001623
1624static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001625math_trunc(PyObject *module, PyObject *x)
1626/*[clinic end generated code: output=34b9697b707e1031 input=2168b34e0a09134d]*/
Christian Heimes400adb02008-02-01 08:12:03 +00001627{
Benjamin Petersonce798522012-01-22 11:24:29 -05001628 _Py_IDENTIFIER(__trunc__);
Benjamin Petersonb0125892010-07-02 13:35:17 +00001629 PyObject *trunc, *result;
Christian Heimes400adb02008-02-01 08:12:03 +00001630
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001631 if (Py_TYPE(x)->tp_dict == NULL) {
1632 if (PyType_Ready(Py_TYPE(x)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 return NULL;
1634 }
Christian Heimes400adb02008-02-01 08:12:03 +00001635
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001636 trunc = _PyObject_LookupSpecial(x, &PyId___trunc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 if (trunc == NULL) {
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001638 if (!PyErr_Occurred())
1639 PyErr_Format(PyExc_TypeError,
1640 "type %.100s doesn't define __trunc__ method",
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001641 Py_TYPE(x)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 return NULL;
1643 }
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001644 result = _PyObject_CallNoArg(trunc);
Benjamin Petersonb0125892010-07-02 13:35:17 +00001645 Py_DECREF(trunc);
1646 return result;
Christian Heimes400adb02008-02-01 08:12:03 +00001647}
1648
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001649
1650/*[clinic input]
1651math.frexp
1652
1653 x: double
1654 /
1655
1656Return the mantissa and exponent of x, as pair (m, e).
1657
1658m is a float and e is an int, such that x = m * 2.**e.
1659If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.
1660[clinic start generated code]*/
Christian Heimes400adb02008-02-01 08:12:03 +00001661
1662static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001663math_frexp_impl(PyObject *module, double x)
1664/*[clinic end generated code: output=03e30d252a15ad4a input=96251c9e208bc6e9]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00001665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 /* deal with special cases directly, to sidestep platform
1668 differences */
1669 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
1670 i = 0;
1671 }
1672 else {
1673 PyFPE_START_PROTECT("in math_frexp", return 0);
1674 x = frexp(x, &i);
1675 PyFPE_END_PROTECT(x);
1676 }
1677 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001678}
1679
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001680
1681/*[clinic input]
1682math.ldexp
1683
1684 x: double
1685 i: object
1686 /
1687
1688Return x * (2**i).
1689
1690This is essentially the inverse of frexp().
1691[clinic start generated code]*/
Guido van Rossumc6e22901998-12-04 19:26:43 +00001692
Barry Warsaw8b43b191996-12-09 22:32:36 +00001693static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001694math_ldexp_impl(PyObject *module, double x, PyObject *i)
1695/*[clinic end generated code: output=b6892f3c2df9cc6a input=17d5970c1a40a8c1]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00001696{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001697 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 long exp;
1699 int overflow;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001700
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001701 if (PyLong_Check(i)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 /* on overflow, replace exponent with either LONG_MAX
1703 or LONG_MIN, depending on the sign. */
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001704 exp = PyLong_AsLongAndOverflow(i, &overflow);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 if (exp == -1 && PyErr_Occurred())
1706 return NULL;
1707 if (overflow)
1708 exp = overflow < 0 ? LONG_MIN : LONG_MAX;
1709 }
1710 else {
1711 PyErr_SetString(PyExc_TypeError,
Serhiy Storchaka95949422013-08-27 19:40:23 +03001712 "Expected an int as second argument to ldexp.");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 return NULL;
1714 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 if (x == 0. || !Py_IS_FINITE(x)) {
1717 /* NaNs, zeros and infinities are returned unchanged */
1718 r = x;
1719 errno = 0;
1720 } else if (exp > INT_MAX) {
1721 /* overflow */
1722 r = copysign(Py_HUGE_VAL, x);
1723 errno = ERANGE;
1724 } else if (exp < INT_MIN) {
1725 /* underflow to +-0 */
1726 r = copysign(0., x);
1727 errno = 0;
1728 } else {
1729 errno = 0;
1730 PyFPE_START_PROTECT("in math_ldexp", return 0);
1731 r = ldexp(x, (int)exp);
1732 PyFPE_END_PROTECT(r);
1733 if (Py_IS_INFINITY(r))
1734 errno = ERANGE;
1735 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 if (errno && is_error(r))
1738 return NULL;
1739 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001740}
1741
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001742
1743/*[clinic input]
1744math.modf
1745
1746 x: double
1747 /
1748
1749Return the fractional and integer parts of x.
1750
1751Both results carry the sign of x and are floats.
1752[clinic start generated code]*/
Guido van Rossumc6e22901998-12-04 19:26:43 +00001753
Barry Warsaw8b43b191996-12-09 22:32:36 +00001754static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001755math_modf_impl(PyObject *module, double x)
1756/*[clinic end generated code: output=90cee0260014c3c0 input=b4cfb6786afd9035]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00001757{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001758 double y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 /* some platforms don't do the right thing for NaNs and
1760 infinities, so we take care of special cases directly. */
1761 if (!Py_IS_FINITE(x)) {
1762 if (Py_IS_INFINITY(x))
1763 return Py_BuildValue("(dd)", copysign(0., x), x);
1764 else if (Py_IS_NAN(x))
1765 return Py_BuildValue("(dd)", x, x);
1766 }
Christian Heimesa342c012008-04-20 21:01:16 +00001767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 errno = 0;
1769 PyFPE_START_PROTECT("in math_modf", return 0);
1770 x = modf(x, &y);
1771 PyFPE_END_PROTECT(x);
1772 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001773}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001774
Guido van Rossumc6e22901998-12-04 19:26:43 +00001775
Serhiy Storchaka95949422013-08-27 19:40:23 +03001776/* A decent logarithm is easy to compute even for huge ints, but libm can't
Tim Peters78526162001-09-05 00:53:45 +00001777 do that by itself -- loghelper can. func is log or log10, and name is
Serhiy Storchaka95949422013-08-27 19:40:23 +03001778 "log" or "log10". Note that overflow of the result isn't possible: an int
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00001779 can contain no more than INT_MAX * SHIFT bits, so has value certainly less
1780 than 2**(2**64 * 2**16) == 2**2**80, and log2 of that is 2**80, which is
Tim Peters78526162001-09-05 00:53:45 +00001781 small enough to fit in an IEEE single. log and log10 are even smaller.
Serhiy Storchaka95949422013-08-27 19:40:23 +03001782 However, intermediate overflow is possible for an int if the number of bits
1783 in that int is larger than PY_SSIZE_T_MAX. */
Tim Peters78526162001-09-05 00:53:45 +00001784
1785static PyObject*
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001786loghelper(PyObject* arg, double (*func)(double), const char *funcname)
Tim Peters78526162001-09-05 00:53:45 +00001787{
Serhiy Storchaka95949422013-08-27 19:40:23 +03001788 /* If it is int, do it ourselves. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 if (PyLong_Check(arg)) {
Mark Dickinsonc6037172010-09-29 19:06:36 +00001790 double x, result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 Py_ssize_t e;
Mark Dickinsonc6037172010-09-29 19:06:36 +00001792
1793 /* Negative or zero inputs give a ValueError. */
1794 if (Py_SIZE(arg) <= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 PyErr_SetString(PyExc_ValueError,
1796 "math domain error");
1797 return NULL;
1798 }
Mark Dickinsonfa41e602010-09-28 07:22:27 +00001799
Mark Dickinsonc6037172010-09-29 19:06:36 +00001800 x = PyLong_AsDouble(arg);
1801 if (x == -1.0 && PyErr_Occurred()) {
1802 if (!PyErr_ExceptionMatches(PyExc_OverflowError))
1803 return NULL;
1804 /* Here the conversion to double overflowed, but it's possible
1805 to compute the log anyway. Clear the exception and continue. */
1806 PyErr_Clear();
1807 x = _PyLong_Frexp((PyLongObject *)arg, &e);
1808 if (x == -1.0 && PyErr_Occurred())
1809 return NULL;
1810 /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */
1811 result = func(x) + func(2.0) * e;
1812 }
1813 else
1814 /* Successfully converted x to a double. */
1815 result = func(x);
1816 return PyFloat_FromDouble(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 }
Tim Peters78526162001-09-05 00:53:45 +00001818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 /* Else let libm handle it by itself. */
1820 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +00001821}
1822
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001823
1824/*[clinic input]
1825math.log
1826
1827 x: object
1828 [
1829 base: object(c_default="NULL") = math.e
1830 ]
1831 /
1832
1833Return the logarithm of x to the given base.
1834
1835If the base not specified, returns the natural logarithm (base e) of x.
1836[clinic start generated code]*/
1837
Tim Peters78526162001-09-05 00:53:45 +00001838static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001839math_log_impl(PyObject *module, PyObject *x, int group_right_1,
1840 PyObject *base)
1841/*[clinic end generated code: output=7b5a39e526b73fc9 input=0f62d5726cbfebbd]*/
Tim Peters78526162001-09-05 00:53:45 +00001842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 PyObject *num, *den;
1844 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001845
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001846 num = loghelper(x, m_log, "log");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 if (num == NULL || base == NULL)
1848 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 den = loghelper(base, m_log, "log");
1851 if (den == NULL) {
1852 Py_DECREF(num);
1853 return NULL;
1854 }
Raymond Hettinger866964c2002-12-14 19:51:34 +00001855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 ans = PyNumber_TrueDivide(num, den);
1857 Py_DECREF(num);
1858 Py_DECREF(den);
1859 return ans;
Tim Peters78526162001-09-05 00:53:45 +00001860}
1861
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001862
1863/*[clinic input]
1864math.log2
1865
1866 x: object
1867 /
1868
1869Return the base 2 logarithm of x.
1870[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00001871
1872static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001873math_log2(PyObject *module, PyObject *x)
1874/*[clinic end generated code: output=5425899a4d5d6acb input=08321262bae4f39b]*/
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001875{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001876 return loghelper(x, m_log2, "log2");
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001877}
1878
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001879
1880/*[clinic input]
1881math.log10
1882
1883 x: object
1884 /
1885
1886Return the base 10 logarithm of x.
1887[clinic start generated code]*/
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001888
1889static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001890math_log10(PyObject *module, PyObject *x)
1891/*[clinic end generated code: output=be72a64617df9c6f input=b2469d02c6469e53]*/
Tim Peters78526162001-09-05 00:53:45 +00001892{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001893 return loghelper(x, m_log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +00001894}
1895
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001896
1897/*[clinic input]
1898math.fmod
1899
1900 x: double
1901 y: double
1902 /
1903
1904Return fmod(x, y), according to platform C.
1905
1906x % y may differ.
1907[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00001908
Christian Heimes53876d92008-04-19 00:31:39 +00001909static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001910math_fmod_impl(PyObject *module, double x, double y)
1911/*[clinic end generated code: output=7559d794343a27b5 input=4f84caa8cfc26a03]*/
Christian Heimes53876d92008-04-19 00:31:39 +00001912{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001913 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 /* fmod(x, +/-Inf) returns x for finite x. */
1915 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
1916 return PyFloat_FromDouble(x);
1917 errno = 0;
1918 PyFPE_START_PROTECT("in math_fmod", return 0);
1919 r = fmod(x, y);
1920 PyFPE_END_PROTECT(r);
1921 if (Py_IS_NAN(r)) {
1922 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1923 errno = EDOM;
1924 else
1925 errno = 0;
1926 }
1927 if (errno && is_error(r))
1928 return NULL;
1929 else
1930 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00001931}
1932
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001933
1934/*[clinic input]
1935math.hypot
1936
1937 x: double
1938 y: double
1939 /
1940
1941Return the Euclidean distance, sqrt(x*x + y*y).
1942[clinic start generated code]*/
Christian Heimes53876d92008-04-19 00:31:39 +00001943
1944static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001945math_hypot_impl(PyObject *module, double x, double y)
1946/*[clinic end generated code: output=b7686e5be468ef87 input=7f8eea70406474aa]*/
Christian Heimes53876d92008-04-19 00:31:39 +00001947{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001948 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */
1950 if (Py_IS_INFINITY(x))
1951 return PyFloat_FromDouble(fabs(x));
1952 if (Py_IS_INFINITY(y))
1953 return PyFloat_FromDouble(fabs(y));
1954 errno = 0;
1955 PyFPE_START_PROTECT("in math_hypot", return 0);
1956 r = hypot(x, y);
1957 PyFPE_END_PROTECT(r);
1958 if (Py_IS_NAN(r)) {
1959 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1960 errno = EDOM;
1961 else
1962 errno = 0;
1963 }
1964 else if (Py_IS_INFINITY(r)) {
1965 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
1966 errno = ERANGE;
1967 else
1968 errno = 0;
1969 }
1970 if (errno && is_error(r))
1971 return NULL;
1972 else
1973 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00001974}
1975
Christian Heimes53876d92008-04-19 00:31:39 +00001976
1977/* pow can't use math_2, but needs its own wrapper: the problem is
1978 that an infinite result can arise either as a result of overflow
1979 (in which case OverflowError should be raised) or as a result of
1980 e.g. 0.**-5. (for which ValueError needs to be raised.)
1981*/
1982
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001983/*[clinic input]
1984math.pow
Christian Heimes53876d92008-04-19 00:31:39 +00001985
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001986 x: double
1987 y: double
1988 /
1989
1990Return x**y (x to the power of y).
1991[clinic start generated code]*/
1992
1993static PyObject *
1994math_pow_impl(PyObject *module, double x, double y)
1995/*[clinic end generated code: output=fff93e65abccd6b0 input=c26f1f6075088bfd]*/
1996{
1997 double r;
1998 int odd_y;
Christian Heimesa342c012008-04-20 21:01:16 +00001999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 /* deal directly with IEEE specials, to cope with problems on various
2001 platforms whose semantics don't exactly match C99 */
2002 r = 0.; /* silence compiler warning */
2003 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
2004 errno = 0;
2005 if (Py_IS_NAN(x))
2006 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
2007 else if (Py_IS_NAN(y))
2008 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
2009 else if (Py_IS_INFINITY(x)) {
2010 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
2011 if (y > 0.)
2012 r = odd_y ? x : fabs(x);
2013 else if (y == 0.)
2014 r = 1.;
2015 else /* y < 0. */
2016 r = odd_y ? copysign(0., x) : 0.;
2017 }
2018 else if (Py_IS_INFINITY(y)) {
2019 if (fabs(x) == 1.0)
2020 r = 1.;
2021 else if (y > 0. && fabs(x) > 1.0)
2022 r = y;
2023 else if (y < 0. && fabs(x) < 1.0) {
2024 r = -y; /* result is +inf */
2025 if (x == 0.) /* 0**-inf: divide-by-zero */
2026 errno = EDOM;
2027 }
2028 else
2029 r = 0.;
2030 }
2031 }
2032 else {
2033 /* let libm handle finite**finite */
2034 errno = 0;
2035 PyFPE_START_PROTECT("in math_pow", return 0);
2036 r = pow(x, y);
2037 PyFPE_END_PROTECT(r);
2038 /* a NaN result should arise only from (-ve)**(finite
2039 non-integer); in this case we want to raise ValueError. */
2040 if (!Py_IS_FINITE(r)) {
2041 if (Py_IS_NAN(r)) {
2042 errno = EDOM;
2043 }
2044 /*
2045 an infinite result here arises either from:
2046 (A) (+/-0.)**negative (-> divide-by-zero)
2047 (B) overflow of x**y with x and y finite
2048 */
2049 else if (Py_IS_INFINITY(r)) {
2050 if (x == 0.)
2051 errno = EDOM;
2052 else
2053 errno = ERANGE;
2054 }
2055 }
2056 }
Christian Heimes53876d92008-04-19 00:31:39 +00002057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 if (errno && is_error(r))
2059 return NULL;
2060 else
2061 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00002062}
2063
Christian Heimes53876d92008-04-19 00:31:39 +00002064
Christian Heimes072c0f12008-01-03 23:01:04 +00002065static const double degToRad = Py_MATH_PI / 180.0;
2066static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002067
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002068/*[clinic input]
2069math.degrees
2070
2071 x: double
2072 /
2073
2074Convert angle x from radians to degrees.
2075[clinic start generated code]*/
2076
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002077static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002078math_degrees_impl(PyObject *module, double x)
2079/*[clinic end generated code: output=7fea78b294acd12f input=81e016555d6e3660]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002080{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002082}
2083
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002084
2085/*[clinic input]
2086math.radians
2087
2088 x: double
2089 /
2090
2091Convert angle x from degrees to radians.
2092[clinic start generated code]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002093
2094static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002095math_radians_impl(PyObject *module, double x)
2096/*[clinic end generated code: output=34daa47caf9b1590 input=91626fc489fe3d63]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 return PyFloat_FromDouble(x * degToRad);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002099}
2100
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002101
2102/*[clinic input]
2103math.isfinite
2104
2105 x: double
2106 /
2107
2108Return True if x is neither an infinity nor a NaN, and False otherwise.
2109[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002110
Christian Heimes072c0f12008-01-03 23:01:04 +00002111static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002112math_isfinite_impl(PyObject *module, double x)
2113/*[clinic end generated code: output=8ba1f396440c9901 input=46967d254812e54a]*/
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002114{
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002115 return PyBool_FromLong((long)Py_IS_FINITE(x));
2116}
2117
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002118
2119/*[clinic input]
2120math.isnan
2121
2122 x: double
2123 /
2124
2125Return True if x is a NaN (not a number), and False otherwise.
2126[clinic start generated code]*/
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002127
2128static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002129math_isnan_impl(PyObject *module, double x)
2130/*[clinic end generated code: output=f537b4d6df878c3e input=935891e66083f46a]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00002133}
2134
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002135
2136/*[clinic input]
2137math.isinf
2138
2139 x: double
2140 /
2141
2142Return True if x is a positive or negative infinity, and False otherwise.
2143[clinic start generated code]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002144
2145static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002146math_isinf_impl(PyObject *module, double x)
2147/*[clinic end generated code: output=9f00cbec4de7b06b input=32630e4212cf961f]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00002150}
2151
Christian Heimes072c0f12008-01-03 23:01:04 +00002152
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002153/*[clinic input]
2154math.isclose -> bool
2155
2156 a: double
2157 b: double
2158 *
2159 rel_tol: double = 1e-09
2160 maximum difference for being considered "close", relative to the
2161 magnitude of the input values
2162 abs_tol: double = 0.0
2163 maximum difference for being considered "close", regardless of the
2164 magnitude of the input values
2165
2166Determine whether two floating point numbers are close in value.
2167
2168Return True if a is close in value to b, and False otherwise.
2169
2170For the values to be considered close, the difference between them
2171must be smaller than at least one of the tolerances.
2172
2173-inf, inf and NaN behave similarly to the IEEE 754 Standard. That
2174is, NaN is not close to anything, even itself. inf and -inf are
2175only close to themselves.
2176[clinic start generated code]*/
2177
2178static int
2179math_isclose_impl(PyObject *module, double a, double b, double rel_tol,
2180 double abs_tol)
2181/*[clinic end generated code: output=b73070207511952d input=f28671871ea5bfba]*/
Tal Einatd5519ed2015-05-31 22:05:00 +03002182{
Tal Einatd5519ed2015-05-31 22:05:00 +03002183 double diff = 0.0;
Tal Einatd5519ed2015-05-31 22:05:00 +03002184
2185 /* sanity check on the inputs */
2186 if (rel_tol < 0.0 || abs_tol < 0.0 ) {
2187 PyErr_SetString(PyExc_ValueError,
2188 "tolerances must be non-negative");
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002189 return -1;
Tal Einatd5519ed2015-05-31 22:05:00 +03002190 }
2191
2192 if ( a == b ) {
2193 /* short circuit exact equality -- needed to catch two infinities of
2194 the same sign. And perhaps speeds things up a bit sometimes.
2195 */
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002196 return 1;
Tal Einatd5519ed2015-05-31 22:05:00 +03002197 }
2198
2199 /* This catches the case of two infinities of opposite sign, or
2200 one infinity and one finite number. Two infinities of opposite
2201 sign would otherwise have an infinite relative tolerance.
2202 Two infinities of the same sign are caught by the equality check
2203 above.
2204 */
2205
2206 if (Py_IS_INFINITY(a) || Py_IS_INFINITY(b)) {
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002207 return 0;
Tal Einatd5519ed2015-05-31 22:05:00 +03002208 }
2209
2210 /* now do the regular computation
2211 this is essentially the "weak" test from the Boost library
2212 */
2213
2214 diff = fabs(b - a);
2215
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002216 return (((diff <= fabs(rel_tol * b)) ||
2217 (diff <= fabs(rel_tol * a))) ||
2218 (diff <= abs_tol));
Tal Einatd5519ed2015-05-31 22:05:00 +03002219}
2220
Tal Einatd5519ed2015-05-31 22:05:00 +03002221
Barry Warsaw8b43b191996-12-09 22:32:36 +00002222static PyMethodDef math_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 {"acos", math_acos, METH_O, math_acos_doc},
2224 {"acosh", math_acosh, METH_O, math_acosh_doc},
2225 {"asin", math_asin, METH_O, math_asin_doc},
2226 {"asinh", math_asinh, METH_O, math_asinh_doc},
2227 {"atan", math_atan, METH_O, math_atan_doc},
2228 {"atan2", math_atan2, METH_VARARGS, math_atan2_doc},
2229 {"atanh", math_atanh, METH_O, math_atanh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002230 MATH_CEIL_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 {"copysign", math_copysign, METH_VARARGS, math_copysign_doc},
2232 {"cos", math_cos, METH_O, math_cos_doc},
2233 {"cosh", math_cosh, METH_O, math_cosh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002234 MATH_DEGREES_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 {"erf", math_erf, METH_O, math_erf_doc},
2236 {"erfc", math_erfc, METH_O, math_erfc_doc},
2237 {"exp", math_exp, METH_O, math_exp_doc},
2238 {"expm1", math_expm1, METH_O, math_expm1_doc},
2239 {"fabs", math_fabs, METH_O, math_fabs_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002240 MATH_FACTORIAL_METHODDEF
2241 MATH_FLOOR_METHODDEF
2242 MATH_FMOD_METHODDEF
2243 MATH_FREXP_METHODDEF
2244 MATH_FSUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 {"gamma", math_gamma, METH_O, math_gamma_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002246 MATH_GCD_METHODDEF
2247 MATH_HYPOT_METHODDEF
2248 MATH_ISCLOSE_METHODDEF
2249 MATH_ISFINITE_METHODDEF
2250 MATH_ISINF_METHODDEF
2251 MATH_ISNAN_METHODDEF
2252 MATH_LDEXP_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002254 MATH_LOG_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 {"log1p", math_log1p, METH_O, math_log1p_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002256 MATH_LOG10_METHODDEF
2257 MATH_LOG2_METHODDEF
2258 MATH_MODF_METHODDEF
2259 MATH_POW_METHODDEF
2260 MATH_RADIANS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 {"sin", math_sin, METH_O, math_sin_doc},
2262 {"sinh", math_sinh, METH_O, math_sinh_doc},
2263 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
2264 {"tan", math_tan, METH_O, math_tan_doc},
2265 {"tanh", math_tanh, METH_O, math_tanh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002266 MATH_TRUNC_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002268};
2269
Guido van Rossumc6e22901998-12-04 19:26:43 +00002270
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002271PyDoc_STRVAR(module_doc,
Tim Peters63c94532001-09-04 23:17:42 +00002272"This module is always available. It provides access to the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002273"mathematical functions defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00002274
Martin v. Löwis1a214512008-06-11 05:26:20 +00002275
2276static struct PyModuleDef mathmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 PyModuleDef_HEAD_INIT,
2278 "math",
2279 module_doc,
2280 -1,
2281 math_methods,
2282 NULL,
2283 NULL,
2284 NULL,
2285 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002286};
2287
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002288PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002289PyInit_math(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 PyObject *m;
Tim Petersfe71f812001-08-07 22:10:00 +00002292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 m = PyModule_Create(&mathmodule);
2294 if (m == NULL)
2295 goto finally;
Barry Warsawfc93f751996-12-17 00:47:03 +00002296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
2298 PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
Guido van Rossum0a891d72016-08-15 09:12:52 -07002299 PyModule_AddObject(m, "tau", PyFloat_FromDouble(Py_MATH_TAU)); /* 2pi */
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +00002300 PyModule_AddObject(m, "inf", PyFloat_FromDouble(m_inf()));
2301#if !defined(PY_NO_SHORT_FLOAT_REPR) || defined(Py_NAN)
2302 PyModule_AddObject(m, "nan", PyFloat_FromDouble(m_nan()));
2303#endif
Barry Warsawfc93f751996-12-17 00:47:03 +00002304
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +00002305 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002307}