blob: 95ea4f7fef83aa9a9e66165f53304414dfe3ae36 [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
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000058/*
59 sin(pi*x), giving accurate results for all finite x (especially x
60 integral or close to an integer). This is here for use in the
61 reflection formula for the gamma function. It conforms to IEEE
62 754-2008 for finite arguments, but not for infinities or nans.
63*/
Tim Petersa40c7932001-09-05 22:36:56 +000064
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000065static const double pi = 3.141592653589793238462643383279502884197;
Mark Dickinson45f992a2009-12-19 11:20:49 +000066static const double sqrtpi = 1.772453850905516027298167483341145182798;
Mark Dickinson9c91eb82010-07-07 16:17:31 +000067static const double logpi = 1.144729885849400174143427351353058711647;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000068
69static double
70sinpi(double x)
71{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000072 double y, r;
73 int n;
74 /* this function should only ever be called for finite arguments */
75 assert(Py_IS_FINITE(x));
76 y = fmod(fabs(x), 2.0);
77 n = (int)round(2.0*y);
78 assert(0 <= n && n <= 4);
79 switch (n) {
80 case 0:
81 r = sin(pi*y);
82 break;
83 case 1:
84 r = cos(pi*(y-0.5));
85 break;
86 case 2:
87 /* N.B. -sin(pi*(y-1.0)) is *not* equivalent: it would give
88 -0.0 instead of 0.0 when y == 1.0. */
89 r = sin(pi*(1.0-y));
90 break;
91 case 3:
92 r = -cos(pi*(y-1.5));
93 break;
94 case 4:
95 r = sin(pi*(y-2.0));
96 break;
97 default:
98 assert(0); /* should never get here */
99 r = -1.23e200; /* silence gcc warning */
100 }
101 return copysign(1.0, x)*r;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000102}
103
104/* Implementation of the real gamma function. In extensive but non-exhaustive
105 random tests, this function proved accurate to within <= 10 ulps across the
106 entire float domain. Note that accuracy may depend on the quality of the
107 system math functions, the pow function in particular. Special cases
108 follow C99 annex F. The parameters and method are tailored to platforms
109 whose double format is the IEEE 754 binary64 format.
110
111 Method: for x > 0.0 we use the Lanczos approximation with parameters N=13
112 and g=6.024680040776729583740234375; these parameters are amongst those
113 used by the Boost library. Following Boost (again), we re-express the
114 Lanczos sum as a rational function, and compute it that way. The
115 coefficients below were computed independently using MPFR, and have been
116 double-checked against the coefficients in the Boost source code.
117
118 For x < 0.0 we use the reflection formula.
119
120 There's one minor tweak that deserves explanation: Lanczos' formula for
121 Gamma(x) involves computing pow(x+g-0.5, x-0.5) / exp(x+g-0.5). For many x
122 values, x+g-0.5 can be represented exactly. However, in cases where it
123 can't be represented exactly the small error in x+g-0.5 can be magnified
124 significantly by the pow and exp calls, especially for large x. A cheap
125 correction is to multiply by (1 + e*g/(x+g-0.5)), where e is the error
126 involved in the computation of x+g-0.5 (that is, e = computed value of
127 x+g-0.5 - exact value of x+g-0.5). Here's the proof:
128
129 Correction factor
130 -----------------
131 Write x+g-0.5 = y-e, where y is exactly representable as an IEEE 754
132 double, and e is tiny. Then:
133
134 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) = pow(y-e, x-0.5)/exp(y-e)
135 = pow(y, x-0.5)/exp(y) * C,
136
137 where the correction_factor C is given by
138
139 C = pow(1-e/y, x-0.5) * exp(e)
140
141 Since e is tiny, pow(1-e/y, x-0.5) ~ 1-(x-0.5)*e/y, and exp(x) ~ 1+e, so:
142
143 C ~ (1-(x-0.5)*e/y) * (1+e) ~ 1 + e*(y-(x-0.5))/y
144
145 But y-(x-0.5) = g+e, and g+e ~ g. So we get C ~ 1 + e*g/y, and
146
147 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) ~ pow(y, x-0.5)/exp(y) * (1 + e*g/y),
148
149 Note that for accuracy, when computing r*C it's better to do
150
151 r + e*g/y*r;
152
153 than
154
155 r * (1 + e*g/y);
156
157 since the addition in the latter throws away most of the bits of
158 information in e*g/y.
159*/
160
161#define LANCZOS_N 13
162static const double lanczos_g = 6.024680040776729583740234375;
163static const double lanczos_g_minus_half = 5.524680040776729583740234375;
164static const double lanczos_num_coeffs[LANCZOS_N] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 23531376880.410759688572007674451636754734846804940,
166 42919803642.649098768957899047001988850926355848959,
167 35711959237.355668049440185451547166705960488635843,
168 17921034426.037209699919755754458931112671403265390,
169 6039542586.3520280050642916443072979210699388420708,
170 1439720407.3117216736632230727949123939715485786772,
171 248874557.86205415651146038641322942321632125127801,
172 31426415.585400194380614231628318205362874684987640,
173 2876370.6289353724412254090516208496135991145378768,
174 186056.26539522349504029498971604569928220784236328,
175 8071.6720023658162106380029022722506138218516325024,
176 210.82427775157934587250973392071336271166969580291,
177 2.5066282746310002701649081771338373386264310793408
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000178};
179
180/* denominator is x*(x+1)*...*(x+LANCZOS_N-2) */
181static const double lanczos_den_coeffs[LANCZOS_N] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 0.0, 39916800.0, 120543840.0, 150917976.0, 105258076.0, 45995730.0,
183 13339535.0, 2637558.0, 357423.0, 32670.0, 1925.0, 66.0, 1.0};
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000184
185/* gamma values for small positive integers, 1 though NGAMMA_INTEGRAL */
186#define NGAMMA_INTEGRAL 23
187static const double gamma_integral[NGAMMA_INTEGRAL] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0,
189 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0,
190 1307674368000.0, 20922789888000.0, 355687428096000.0,
191 6402373705728000.0, 121645100408832000.0, 2432902008176640000.0,
192 51090942171709440000.0, 1124000727777607680000.0,
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000193};
194
195/* Lanczos' sum L_g(x), for positive x */
196
197static double
198lanczos_sum(double x)
199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 double num = 0.0, den = 0.0;
201 int i;
202 assert(x > 0.0);
203 /* evaluate the rational function lanczos_sum(x). For large
204 x, the obvious algorithm risks overflow, so we instead
205 rescale the denominator and numerator of the rational
206 function by x**(1-LANCZOS_N) and treat this as a
207 rational function in 1/x. This also reduces the error for
208 larger x values. The choice of cutoff point (5.0 below) is
209 somewhat arbitrary; in tests, smaller cutoff values than
210 this resulted in lower accuracy. */
211 if (x < 5.0) {
212 for (i = LANCZOS_N; --i >= 0; ) {
213 num = num * x + lanczos_num_coeffs[i];
214 den = den * x + lanczos_den_coeffs[i];
215 }
216 }
217 else {
218 for (i = 0; i < LANCZOS_N; i++) {
219 num = num / x + lanczos_num_coeffs[i];
220 den = den / x + lanczos_den_coeffs[i];
221 }
222 }
223 return num/den;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000224}
225
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +0000226/* Constant for +infinity, generated in the same way as float('inf'). */
227
228static double
229m_inf(void)
230{
231#ifndef PY_NO_SHORT_FLOAT_REPR
232 return _Py_dg_infinity(0);
233#else
234 return Py_HUGE_VAL;
235#endif
236}
237
238/* Constant nan value, generated in the same way as float('nan'). */
239/* We don't currently assume that Py_NAN is defined everywhere. */
240
241#if !defined(PY_NO_SHORT_FLOAT_REPR) || defined(Py_NAN)
242
243static double
244m_nan(void)
245{
246#ifndef PY_NO_SHORT_FLOAT_REPR
247 return _Py_dg_stdnan(0);
248#else
249 return Py_NAN;
250#endif
251}
252
253#endif
254
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000255static double
256m_tgamma(double x)
257{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 double absx, r, y, z, sqrtpow;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 /* special cases */
261 if (!Py_IS_FINITE(x)) {
262 if (Py_IS_NAN(x) || x > 0.0)
263 return x; /* tgamma(nan) = nan, tgamma(inf) = inf */
264 else {
265 errno = EDOM;
266 return Py_NAN; /* tgamma(-inf) = nan, invalid */
267 }
268 }
269 if (x == 0.0) {
270 errno = EDOM;
Mark Dickinson50203a62011-09-25 15:26:43 +0100271 /* tgamma(+-0.0) = +-inf, divide-by-zero */
272 return copysign(Py_HUGE_VAL, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 /* integer arguments */
276 if (x == floor(x)) {
277 if (x < 0.0) {
278 errno = EDOM; /* tgamma(n) = nan, invalid for */
279 return Py_NAN; /* negative integers n */
280 }
281 if (x <= NGAMMA_INTEGRAL)
282 return gamma_integral[(int)x - 1];
283 }
284 absx = fabs(x);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 /* tiny arguments: tgamma(x) ~ 1/x for x near 0 */
287 if (absx < 1e-20) {
288 r = 1.0/x;
289 if (Py_IS_INFINITY(r))
290 errno = ERANGE;
291 return r;
292 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 /* large arguments: assuming IEEE 754 doubles, tgamma(x) overflows for
295 x > 200, and underflows to +-0.0 for x < -200, not a negative
296 integer. */
297 if (absx > 200.0) {
298 if (x < 0.0) {
299 return 0.0/sinpi(x);
300 }
301 else {
302 errno = ERANGE;
303 return Py_HUGE_VAL;
304 }
305 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 y = absx + lanczos_g_minus_half;
308 /* compute error in sum */
309 if (absx > lanczos_g_minus_half) {
310 /* note: the correction can be foiled by an optimizing
311 compiler that (incorrectly) thinks that an expression like
312 a + b - a - b can be optimized to 0.0. This shouldn't
313 happen in a standards-conforming compiler. */
314 double q = y - absx;
315 z = q - lanczos_g_minus_half;
316 }
317 else {
318 double q = y - lanczos_g_minus_half;
319 z = q - absx;
320 }
321 z = z * lanczos_g / y;
322 if (x < 0.0) {
323 r = -pi / sinpi(absx) / absx * exp(y) / lanczos_sum(absx);
324 r -= z * r;
325 if (absx < 140.0) {
326 r /= pow(y, absx - 0.5);
327 }
328 else {
329 sqrtpow = pow(y, absx / 2.0 - 0.25);
330 r /= sqrtpow;
331 r /= sqrtpow;
332 }
333 }
334 else {
335 r = lanczos_sum(absx) / exp(y);
336 r += z * r;
337 if (absx < 140.0) {
338 r *= pow(y, absx - 0.5);
339 }
340 else {
341 sqrtpow = pow(y, absx / 2.0 - 0.25);
342 r *= sqrtpow;
343 r *= sqrtpow;
344 }
345 }
346 if (Py_IS_INFINITY(r))
347 errno = ERANGE;
348 return r;
Guido van Rossum8832b621991-12-16 15:44:24 +0000349}
350
Christian Heimes53876d92008-04-19 00:31:39 +0000351/*
Mark Dickinson05d2e082009-12-11 20:17:17 +0000352 lgamma: natural log of the absolute value of the Gamma function.
353 For large arguments, Lanczos' formula works extremely well here.
354*/
355
356static double
357m_lgamma(double x)
358{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 double r, absx;
Mark Dickinson05d2e082009-12-11 20:17:17 +0000360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 /* special cases */
362 if (!Py_IS_FINITE(x)) {
363 if (Py_IS_NAN(x))
364 return x; /* lgamma(nan) = nan */
365 else
366 return Py_HUGE_VAL; /* lgamma(+-inf) = +inf */
367 }
Mark Dickinson05d2e082009-12-11 20:17:17 +0000368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 /* integer arguments */
370 if (x == floor(x) && x <= 2.0) {
371 if (x <= 0.0) {
372 errno = EDOM; /* lgamma(n) = inf, divide-by-zero for */
373 return Py_HUGE_VAL; /* integers n <= 0 */
374 }
375 else {
376 return 0.0; /* lgamma(1) = lgamma(2) = 0.0 */
377 }
378 }
Mark Dickinson05d2e082009-12-11 20:17:17 +0000379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 absx = fabs(x);
381 /* tiny arguments: lgamma(x) ~ -log(fabs(x)) for small x */
382 if (absx < 1e-20)
383 return -log(absx);
Mark Dickinson05d2e082009-12-11 20:17:17 +0000384
Mark Dickinson9c91eb82010-07-07 16:17:31 +0000385 /* Lanczos' formula. We could save a fraction of a ulp in accuracy by
386 having a second set of numerator coefficients for lanczos_sum that
387 absorbed the exp(-lanczos_g) term, and throwing out the lanczos_g
388 subtraction below; it's probably not worth it. */
389 r = log(lanczos_sum(absx)) - lanczos_g;
390 r += (absx - 0.5) * (log(absx + lanczos_g - 0.5) - 1);
391 if (x < 0.0)
392 /* Use reflection formula to get value for negative x. */
393 r = logpi - log(fabs(sinpi(absx))) - log(absx) - r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 if (Py_IS_INFINITY(r))
395 errno = ERANGE;
396 return r;
Mark Dickinson05d2e082009-12-11 20:17:17 +0000397}
398
Mark Dickinson45f992a2009-12-19 11:20:49 +0000399/*
400 Implementations of the error function erf(x) and the complementary error
401 function erfc(x).
402
Brett Cannon45adb312016-01-15 09:38:24 -0800403 Method: we use a series approximation for erf for small x, and a continued
404 fraction approximation for erfc(x) for larger x;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000405 combined with the relations erf(-x) = -erf(x) and erfc(x) = 1.0 - erf(x),
406 this gives us erf(x) and erfc(x) for all x.
407
408 The series expansion used is:
409
410 erf(x) = x*exp(-x*x)/sqrt(pi) * [
411 2/1 + 4/3 x**2 + 8/15 x**4 + 16/105 x**6 + ...]
412
413 The coefficient of x**(2k-2) here is 4**k*factorial(k)/factorial(2*k).
414 This series converges well for smallish x, but slowly for larger x.
415
416 The continued fraction expansion used is:
417
418 erfc(x) = x*exp(-x*x)/sqrt(pi) * [1/(0.5 + x**2 -) 0.5/(2.5 + x**2 - )
419 3.0/(4.5 + x**2 - ) 7.5/(6.5 + x**2 - ) ...]
420
421 after the first term, the general term has the form:
422
423 k*(k-0.5)/(2*k+0.5 + x**2 - ...).
424
425 This expansion converges fast for larger x, but convergence becomes
426 infinitely slow as x approaches 0.0. The (somewhat naive) continued
427 fraction evaluation algorithm used below also risks overflow for large x;
428 but for large x, erfc(x) == 0.0 to within machine precision. (For
429 example, erfc(30.0) is approximately 2.56e-393).
430
431 Parameters: use series expansion for abs(x) < ERF_SERIES_CUTOFF and
432 continued fraction expansion for ERF_SERIES_CUTOFF <= abs(x) <
433 ERFC_CONTFRAC_CUTOFF. ERFC_SERIES_TERMS and ERFC_CONTFRAC_TERMS are the
434 numbers of terms to use for the relevant expansions. */
435
436#define ERF_SERIES_CUTOFF 1.5
437#define ERF_SERIES_TERMS 25
438#define ERFC_CONTFRAC_CUTOFF 30.0
439#define ERFC_CONTFRAC_TERMS 50
440
441/*
442 Error function, via power series.
443
444 Given a finite float x, return an approximation to erf(x).
445 Converges reasonably fast for small x.
446*/
447
448static double
449m_erf_series(double x)
450{
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000451 double x2, acc, fk, result;
452 int i, saved_errno;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 x2 = x * x;
455 acc = 0.0;
456 fk = (double)ERF_SERIES_TERMS + 0.5;
457 for (i = 0; i < ERF_SERIES_TERMS; i++) {
458 acc = 2.0 + x2 * acc / fk;
459 fk -= 1.0;
460 }
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000461 /* Make sure the exp call doesn't affect errno;
462 see m_erfc_contfrac for more. */
463 saved_errno = errno;
464 result = acc * x * exp(-x2) / sqrtpi;
465 errno = saved_errno;
466 return result;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000467}
468
469/*
470 Complementary error function, via continued fraction expansion.
471
472 Given a positive float x, return an approximation to erfc(x). Converges
473 reasonably fast for x large (say, x > 2.0), and should be safe from
474 overflow if x and nterms are not too large. On an IEEE 754 machine, with x
475 <= 30.0, we're safe up to nterms = 100. For x >= 30.0, erfc(x) is smaller
476 than the smallest representable nonzero float. */
477
478static double
479m_erfc_contfrac(double x)
480{
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000481 double x2, a, da, p, p_last, q, q_last, b, result;
482 int i, saved_errno;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 if (x >= ERFC_CONTFRAC_CUTOFF)
485 return 0.0;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 x2 = x*x;
488 a = 0.0;
489 da = 0.5;
490 p = 1.0; p_last = 0.0;
491 q = da + x2; q_last = 1.0;
492 for (i = 0; i < ERFC_CONTFRAC_TERMS; i++) {
493 double temp;
494 a += da;
495 da += 2.0;
496 b = da + x2;
497 temp = p; p = b*p - a*p_last; p_last = temp;
498 temp = q; q = b*q - a*q_last; q_last = temp;
499 }
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000500 /* Issue #8986: On some platforms, exp sets errno on underflow to zero;
501 save the current errno value so that we can restore it later. */
502 saved_errno = errno;
503 result = p / q * x * exp(-x2) / sqrtpi;
504 errno = saved_errno;
505 return result;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000506}
507
508/* Error function erf(x), for general x */
509
510static double
511m_erf(double x)
512{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 double absx, cf;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 if (Py_IS_NAN(x))
516 return x;
517 absx = fabs(x);
518 if (absx < ERF_SERIES_CUTOFF)
519 return m_erf_series(x);
520 else {
521 cf = m_erfc_contfrac(absx);
522 return x > 0.0 ? 1.0 - cf : cf - 1.0;
523 }
Mark Dickinson45f992a2009-12-19 11:20:49 +0000524}
525
526/* Complementary error function erfc(x), for general x. */
527
528static double
529m_erfc(double x)
530{
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 1.0 - m_erf_series(x);
538 else {
539 cf = m_erfc_contfrac(absx);
540 return x > 0.0 ? cf : 2.0 - cf;
541 }
Mark Dickinson45f992a2009-12-19 11:20:49 +0000542}
Mark Dickinson05d2e082009-12-11 20:17:17 +0000543
544/*
Christian Heimese57950f2008-04-21 13:08:03 +0000545 wrapper for atan2 that deals directly with special cases before
546 delegating to the platform libm for the remaining cases. This
547 is necessary to get consistent behaviour across platforms.
548 Windows, FreeBSD and alpha Tru64 are amongst platforms that don't
549 always follow C99.
550*/
551
552static double
553m_atan2(double y, double x)
554{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 if (Py_IS_NAN(x) || Py_IS_NAN(y))
556 return Py_NAN;
557 if (Py_IS_INFINITY(y)) {
558 if (Py_IS_INFINITY(x)) {
559 if (copysign(1., x) == 1.)
560 /* atan2(+-inf, +inf) == +-pi/4 */
561 return copysign(0.25*Py_MATH_PI, y);
562 else
563 /* atan2(+-inf, -inf) == +-pi*3/4 */
564 return copysign(0.75*Py_MATH_PI, y);
565 }
566 /* atan2(+-inf, x) == +-pi/2 for finite x */
567 return copysign(0.5*Py_MATH_PI, y);
568 }
569 if (Py_IS_INFINITY(x) || y == 0.) {
570 if (copysign(1., x) == 1.)
571 /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */
572 return copysign(0., y);
573 else
574 /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */
575 return copysign(Py_MATH_PI, y);
576 }
577 return atan2(y, x);
Christian Heimese57950f2008-04-21 13:08:03 +0000578}
579
580/*
Mark Dickinsone675f082008-12-11 21:56:00 +0000581 Various platforms (Solaris, OpenBSD) do nonstandard things for log(0),
582 log(-ve), log(NaN). Here are wrappers for log and log10 that deal with
583 special values directly, passing positive non-special values through to
584 the system log/log10.
585 */
586
587static double
588m_log(double x)
589{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 if (Py_IS_FINITE(x)) {
591 if (x > 0.0)
592 return log(x);
593 errno = EDOM;
594 if (x == 0.0)
595 return -Py_HUGE_VAL; /* log(0) = -inf */
596 else
597 return Py_NAN; /* log(-ve) = nan */
598 }
599 else if (Py_IS_NAN(x))
600 return x; /* log(nan) = nan */
601 else if (x > 0.0)
602 return x; /* log(inf) = inf */
603 else {
604 errno = EDOM;
605 return Py_NAN; /* log(-inf) = nan */
606 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000607}
608
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200609/*
610 log2: log to base 2.
611
612 Uses an algorithm that should:
Mark Dickinson83b8c0b2011-05-09 08:40:20 +0100613
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200614 (a) produce exact results for powers of 2, and
Mark Dickinson83b8c0b2011-05-09 08:40:20 +0100615 (b) give a monotonic log2 (for positive finite floats),
616 assuming that the system log is monotonic.
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200617*/
618
619static double
620m_log2(double x)
621{
622 if (!Py_IS_FINITE(x)) {
623 if (Py_IS_NAN(x))
624 return x; /* log2(nan) = nan */
625 else if (x > 0.0)
626 return x; /* log2(+inf) = +inf */
627 else {
628 errno = EDOM;
629 return Py_NAN; /* log2(-inf) = nan, invalid-operation */
630 }
631 }
632
633 if (x > 0.0) {
Victor Stinner8f9f8d62011-05-09 12:45:41 +0200634#ifdef HAVE_LOG2
635 return log2(x);
636#else
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200637 double m;
638 int e;
639 m = frexp(x, &e);
640 /* We want log2(m * 2**e) == log(m) / log(2) + e. Care is needed when
641 * x is just greater than 1.0: in that case e is 1, log(m) is negative,
642 * and we get significant cancellation error from the addition of
643 * log(m) / log(2) to e. The slight rewrite of the expression below
644 * avoids this problem.
645 */
646 if (x >= 1.0) {
647 return log(2.0 * m) / log(2.0) + (e - 1);
648 }
649 else {
650 return log(m) / log(2.0) + e;
651 }
Victor Stinner8f9f8d62011-05-09 12:45:41 +0200652#endif
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200653 }
654 else if (x == 0.0) {
655 errno = EDOM;
656 return -Py_HUGE_VAL; /* log2(0) = -inf, divide-by-zero */
657 }
658 else {
659 errno = EDOM;
Mark Dickinson23442582011-05-09 08:05:00 +0100660 return Py_NAN; /* log2(-inf) = nan, invalid-operation */
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200661 }
662}
663
Mark Dickinsone675f082008-12-11 21:56:00 +0000664static double
665m_log10(double x)
666{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 if (Py_IS_FINITE(x)) {
668 if (x > 0.0)
669 return log10(x);
670 errno = EDOM;
671 if (x == 0.0)
672 return -Py_HUGE_VAL; /* log10(0) = -inf */
673 else
674 return Py_NAN; /* log10(-ve) = nan */
675 }
676 else if (Py_IS_NAN(x))
677 return x; /* log10(nan) = nan */
678 else if (x > 0.0)
679 return x; /* log10(inf) = inf */
680 else {
681 errno = EDOM;
682 return Py_NAN; /* log10(-inf) = nan */
683 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000684}
685
686
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300687static PyObject *
688math_gcd(PyObject *self, PyObject *args)
689{
690 PyObject *a, *b, *g;
691
692 if (!PyArg_ParseTuple(args, "OO:gcd", &a, &b))
693 return NULL;
694
695 a = PyNumber_Index(a);
696 if (a == NULL)
697 return NULL;
698 b = PyNumber_Index(b);
699 if (b == NULL) {
700 Py_DECREF(a);
701 return NULL;
702 }
703 g = _PyLong_GCD(a, b);
704 Py_DECREF(a);
705 Py_DECREF(b);
706 return g;
707}
708
709PyDoc_STRVAR(math_gcd_doc,
710"gcd(x, y) -> int\n\
711greatest common divisor of x and y");
712
713
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000714/* Call is_error when errno != 0, and where x is the result libm
715 * returned. is_error will usually set up an exception and return
716 * true (1), but may return false (0) without setting up an exception.
717 */
718static int
719is_error(double x)
720{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 int result = 1; /* presumption of guilt */
722 assert(errno); /* non-zero errno is a precondition for calling */
723 if (errno == EDOM)
724 PyErr_SetString(PyExc_ValueError, "math domain error");
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 else if (errno == ERANGE) {
727 /* ANSI C generally requires libm functions to set ERANGE
728 * on overflow, but also generally *allows* them to set
729 * ERANGE on underflow too. There's no consistency about
730 * the latter across platforms.
731 * Alas, C99 never requires that errno be set.
732 * Here we suppress the underflow errors (libm functions
733 * should return a zero on underflow, and +- HUGE_VAL on
734 * overflow, so testing the result for zero suffices to
735 * distinguish the cases).
736 *
737 * On some platforms (Ubuntu/ia64) it seems that errno can be
738 * set to ERANGE for subnormal results that do *not* underflow
739 * to zero. So to be safe, we'll ignore ERANGE whenever the
740 * function result is less than one in absolute value.
741 */
742 if (fabs(x) < 1.0)
743 result = 0;
744 else
745 PyErr_SetString(PyExc_OverflowError,
746 "math range error");
747 }
748 else
749 /* Unexpected math error */
750 PyErr_SetFromErrno(PyExc_ValueError);
751 return result;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000752}
753
Mark Dickinsone675f082008-12-11 21:56:00 +0000754/*
Christian Heimes53876d92008-04-19 00:31:39 +0000755 math_1 is used to wrap a libm function f that takes a double
756 arguments and returns a double.
757
758 The error reporting follows these rules, which are designed to do
759 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
760 platforms.
761
762 - a NaN result from non-NaN inputs causes ValueError to be raised
763 - an infinite result from finite inputs causes OverflowError to be
764 raised if can_overflow is 1, or raises ValueError if can_overflow
765 is 0.
766 - if the result is finite and errno == EDOM then ValueError is
767 raised
768 - if the result is finite and nonzero and errno == ERANGE then
769 OverflowError is raised
770
771 The last rule is used to catch overflow on platforms which follow
772 C89 but for which HUGE_VAL is not an infinity.
773
774 For the majority of one-argument functions these rules are enough
775 to ensure that Python's functions behave as specified in 'Annex F'
776 of the C99 standard, with the 'invalid' and 'divide-by-zero'
777 floating-point exceptions mapping to Python's ValueError and the
778 'overflow' floating-point exception mapping to OverflowError.
779 math_1 only works for functions that don't have singularities *and*
780 the possibility of overflow; fortunately, that covers everything we
781 care about right now.
782*/
783
Barry Warsaw8b43b191996-12-09 22:32:36 +0000784static PyObject *
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000785math_1_to_whatever(PyObject *arg, double (*func) (double),
Christian Heimes53876d92008-04-19 00:31:39 +0000786 PyObject *(*from_double_func) (double),
787 int can_overflow)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000788{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 double x, r;
790 x = PyFloat_AsDouble(arg);
791 if (x == -1.0 && PyErr_Occurred())
792 return NULL;
793 errno = 0;
794 PyFPE_START_PROTECT("in math_1", return 0);
795 r = (*func)(x);
796 PyFPE_END_PROTECT(r);
797 if (Py_IS_NAN(r) && !Py_IS_NAN(x)) {
798 PyErr_SetString(PyExc_ValueError,
799 "math domain error"); /* invalid arg */
800 return NULL;
801 }
802 if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) {
Benjamin Peterson2354a752012-03-13 16:13:09 -0500803 if (can_overflow)
804 PyErr_SetString(PyExc_OverflowError,
805 "math range error"); /* overflow */
806 else
807 PyErr_SetString(PyExc_ValueError,
808 "math domain error"); /* singularity */
809 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 }
811 if (Py_IS_FINITE(r) && errno && is_error(r))
812 /* this branch unnecessary on most platforms */
813 return NULL;
Mark Dickinsonde429622008-05-01 00:19:23 +0000814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 return (*from_double_func)(r);
Christian Heimes53876d92008-04-19 00:31:39 +0000816}
817
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000818/* variant of math_1, to be used when the function being wrapped is known to
819 set errno properly (that is, errno = EDOM for invalid or divide-by-zero,
820 errno = ERANGE for overflow). */
821
822static PyObject *
823math_1a(PyObject *arg, double (*func) (double))
824{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 double x, r;
826 x = PyFloat_AsDouble(arg);
827 if (x == -1.0 && PyErr_Occurred())
828 return NULL;
829 errno = 0;
830 PyFPE_START_PROTECT("in math_1a", return 0);
831 r = (*func)(x);
832 PyFPE_END_PROTECT(r);
833 if (errno && is_error(r))
834 return NULL;
835 return PyFloat_FromDouble(r);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000836}
837
Christian Heimes53876d92008-04-19 00:31:39 +0000838/*
839 math_2 is used to wrap a libm function f that takes two double
840 arguments and returns a double.
841
842 The error reporting follows these rules, which are designed to do
843 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
844 platforms.
845
846 - a NaN result from non-NaN inputs causes ValueError to be raised
847 - an infinite result from finite inputs causes OverflowError to be
848 raised.
849 - if the result is finite and errno == EDOM then ValueError is
850 raised
851 - if the result is finite and nonzero and errno == ERANGE then
852 OverflowError is raised
853
854 The last rule is used to catch overflow on platforms which follow
855 C89 but for which HUGE_VAL is not an infinity.
856
857 For most two-argument functions (copysign, fmod, hypot, atan2)
858 these rules are enough to ensure that Python's functions behave as
859 specified in 'Annex F' of the C99 standard, with the 'invalid' and
860 'divide-by-zero' floating-point exceptions mapping to Python's
861 ValueError and the 'overflow' floating-point exception mapping to
862 OverflowError.
863*/
864
865static PyObject *
866math_1(PyObject *arg, double (*func) (double), int can_overflow)
867{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow);
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000869}
870
871static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000872math_1_to_int(PyObject *arg, double (*func) (double), int can_overflow)
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000873{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 return math_1_to_whatever(arg, func, PyLong_FromDouble, can_overflow);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000875}
876
Barry Warsaw8b43b191996-12-09 22:32:36 +0000877static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200878math_2(PyObject *args, double (*func) (double, double), const char *funcname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 PyObject *ox, *oy;
881 double x, y, r;
882 if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy))
883 return NULL;
884 x = PyFloat_AsDouble(ox);
885 y = PyFloat_AsDouble(oy);
886 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
887 return NULL;
888 errno = 0;
889 PyFPE_START_PROTECT("in math_2", return 0);
890 r = (*func)(x, y);
891 PyFPE_END_PROTECT(r);
892 if (Py_IS_NAN(r)) {
893 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
894 errno = EDOM;
895 else
896 errno = 0;
897 }
898 else if (Py_IS_INFINITY(r)) {
899 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
900 errno = ERANGE;
901 else
902 errno = 0;
903 }
904 if (errno && is_error(r))
905 return NULL;
906 else
907 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000908}
909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910#define FUNC1(funcname, func, can_overflow, docstring) \
911 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
912 return math_1(args, func, can_overflow); \
913 }\
914 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916#define FUNC1A(funcname, func, docstring) \
917 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
918 return math_1a(args, func); \
919 }\
920 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000921
Fred Drake40c48682000-07-03 18:11:56 +0000922#define FUNC2(funcname, func, docstring) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
924 return math_2(args, func, #funcname); \
925 }\
926 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000927
Christian Heimes53876d92008-04-19 00:31:39 +0000928FUNC1(acos, acos, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000929 "acos(x)\n\nReturn the arc cosine (measured in radians) of x.")
Mark Dickinsonf3718592009-12-21 15:27:41 +0000930FUNC1(acosh, m_acosh, 0,
Mark Dickinsondfe0b232015-01-11 13:08:05 +0000931 "acosh(x)\n\nReturn the inverse hyperbolic cosine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000932FUNC1(asin, asin, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000933 "asin(x)\n\nReturn the arc sine (measured in radians) of x.")
Mark Dickinsonf3718592009-12-21 15:27:41 +0000934FUNC1(asinh, m_asinh, 0,
Mark Dickinsondfe0b232015-01-11 13:08:05 +0000935 "asinh(x)\n\nReturn the inverse hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000936FUNC1(atan, atan, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000937 "atan(x)\n\nReturn the arc tangent (measured in radians) of x.")
Christian Heimese57950f2008-04-21 13:08:03 +0000938FUNC2(atan2, m_atan2,
Tim Petersfe71f812001-08-07 22:10:00 +0000939 "atan2(y, x)\n\nReturn the arc tangent (measured in radians) of y/x.\n"
940 "Unlike atan(y/x), the signs of both x and y are considered.")
Mark Dickinsonf3718592009-12-21 15:27:41 +0000941FUNC1(atanh, m_atanh, 0,
Mark Dickinsondfe0b232015-01-11 13:08:05 +0000942 "atanh(x)\n\nReturn the inverse hyperbolic tangent of x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +0000943
944static PyObject * math_ceil(PyObject *self, PyObject *number) {
Benjamin Petersonce798522012-01-22 11:24:29 -0500945 _Py_IDENTIFIER(__ceil__);
Mark Dickinson6d02d9c2010-07-02 16:05:15 +0000946 PyObject *method, *result;
Guido van Rossum13e05de2007-08-23 22:56:55 +0000947
Benjamin Petersonce798522012-01-22 11:24:29 -0500948 method = _PyObject_LookupSpecial(number, &PyId___ceil__);
Benjamin Petersonf751bc92010-07-02 13:46:42 +0000949 if (method == NULL) {
950 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 return math_1_to_int(number, ceil, 0);
Benjamin Petersonf751bc92010-07-02 13:46:42 +0000953 }
Mark Dickinson6d02d9c2010-07-02 16:05:15 +0000954 result = PyObject_CallFunctionObjArgs(method, NULL);
955 Py_DECREF(method);
956 return result;
Guido van Rossum13e05de2007-08-23 22:56:55 +0000957}
958
959PyDoc_STRVAR(math_ceil_doc,
Martin Panter129fe042016-05-08 12:22:37 +0000960 "ceil(x)\n\nReturn the ceiling of x as an Integral.\n"
961 "This is the smallest integer >= x.");
Guido van Rossum13e05de2007-08-23 22:56:55 +0000962
Christian Heimes072c0f12008-01-03 23:01:04 +0000963FUNC2(copysign, copysign,
Andrew Kuchling8cb1ec32014-02-16 11:11:25 -0500964 "copysign(x, y)\n\nReturn a float with the magnitude (absolute value) "
965 "of x but the sign \nof y. On platforms that support signed zeros, "
Andrew Kuchling31378852014-02-16 12:09:35 -0500966 "copysign(1.0, -0.0) \nreturns -1.0.\n")
Christian Heimes53876d92008-04-19 00:31:39 +0000967FUNC1(cos, cos, 0,
968 "cos(x)\n\nReturn the cosine of x (measured in radians).")
969FUNC1(cosh, cosh, 1,
970 "cosh(x)\n\nReturn the hyperbolic cosine of x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +0000971FUNC1A(erf, m_erf,
972 "erf(x)\n\nError function at x.")
973FUNC1A(erfc, m_erfc,
974 "erfc(x)\n\nComplementary error function at x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000975FUNC1(exp, exp, 1,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000976 "exp(x)\n\nReturn e raised to the power of x.")
Mark Dickinson664b5112009-12-16 20:23:42 +0000977FUNC1(expm1, m_expm1, 1,
978 "expm1(x)\n\nReturn exp(x)-1.\n"
979 "This function avoids the loss of precision involved in the direct "
980 "evaluation of exp(x)-1 for small x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000981FUNC1(fabs, fabs, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000982 "fabs(x)\n\nReturn the absolute value of the float x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +0000983
984static PyObject * math_floor(PyObject *self, PyObject *number) {
Benjamin Petersonce798522012-01-22 11:24:29 -0500985 _Py_IDENTIFIER(__floor__);
Benjamin Petersonb0125892010-07-02 13:35:17 +0000986 PyObject *method, *result;
Guido van Rossum13e05de2007-08-23 22:56:55 +0000987
Benjamin Petersonce798522012-01-22 11:24:29 -0500988 method = _PyObject_LookupSpecial(number, &PyId___floor__);
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +0000989 if (method == NULL) {
990 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 return math_1_to_int(number, floor, 0);
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +0000993 }
Benjamin Petersonb0125892010-07-02 13:35:17 +0000994 result = PyObject_CallFunctionObjArgs(method, NULL);
995 Py_DECREF(method);
996 return result;
Guido van Rossum13e05de2007-08-23 22:56:55 +0000997}
998
999PyDoc_STRVAR(math_floor_doc,
Martin Panter129fe042016-05-08 12:22:37 +00001000 "floor(x)\n\nReturn the floor of x as an Integral.\n"
1001 "This is the largest integer <= x.");
Guido van Rossum13e05de2007-08-23 22:56:55 +00001002
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001003FUNC1A(gamma, m_tgamma,
1004 "gamma(x)\n\nGamma function at x.")
Mark Dickinson05d2e082009-12-11 20:17:17 +00001005FUNC1A(lgamma, m_lgamma,
1006 "lgamma(x)\n\nNatural logarithm of absolute value of Gamma function at x.")
Mark Dickinsonbe64d952010-07-07 16:21:29 +00001007FUNC1(log1p, m_log1p, 0,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001008 "log1p(x)\n\nReturn the natural logarithm of 1+x (base e).\n"
1009 "The result is computed in a way which is accurate for x near zero.")
Christian Heimes53876d92008-04-19 00:31:39 +00001010FUNC1(sin, sin, 0,
Tim Petersfe71f812001-08-07 22:10:00 +00001011 "sin(x)\n\nReturn the sine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001012FUNC1(sinh, sinh, 1,
Guido van Rossumc6e22901998-12-04 19:26:43 +00001013 "sinh(x)\n\nReturn the hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001014FUNC1(sqrt, sqrt, 0,
Guido van Rossumc6e22901998-12-04 19:26:43 +00001015 "sqrt(x)\n\nReturn the square root of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001016FUNC1(tan, tan, 0,
Tim Petersfe71f812001-08-07 22:10:00 +00001017 "tan(x)\n\nReturn the tangent of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001018FUNC1(tanh, tanh, 0,
Guido van Rossumc6e22901998-12-04 19:26:43 +00001019 "tanh(x)\n\nReturn the hyperbolic tangent of x.")
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001020
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001021/* Precision summation function as msum() by Raymond Hettinger in
1022 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
1023 enhanced with the exact partials sum and roundoff from Mark
1024 Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
1025 See those links for more details, proofs and other references.
1026
1027 Note 1: IEEE 754R floating point semantics are assumed,
1028 but the current implementation does not re-establish special
1029 value semantics across iterations (i.e. handling -Inf + Inf).
1030
1031 Note 2: No provision is made for intermediate overflow handling;
Georg Brandlf78e02b2008-06-10 17:40:04 +00001032 therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001033 sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
1034 overflow of the first partial sum.
1035
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001036 Note 3: The intermediate values lo, yr, and hi are declared volatile so
1037 aggressive compilers won't algebraically reduce lo to always be exactly 0.0.
Georg Brandlf78e02b2008-06-10 17:40:04 +00001038 Also, the volatile declaration forces the values to be stored in memory as
1039 regular doubles instead of extended long precision (80-bit) values. This
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001040 prevents double rounding because any addition or subtraction of two doubles
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 can be resolved exactly into double-sized hi and lo values. As long as the
Georg Brandlf78e02b2008-06-10 17:40:04 +00001042 hi value gets forced into a double before yr and lo are computed, the extra
1043 bits in downstream extended precision operations (x87 for example) will be
1044 exactly zero and therefore can be losslessly stored back into a double,
1045 thereby preventing double rounding.
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001046
1047 Note 4: A similar implementation is in Modules/cmathmodule.c.
1048 Be sure to update both when making changes.
1049
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001050 Note 5: The signature of math.fsum() differs from builtins.sum()
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001051 because the start argument doesn't make sense in the context of
1052 accurate summation. Since the partials table is collapsed before
1053 returning a result, sum(seq2, start=sum(seq1)) may not equal the
1054 accurate result returned by sum(itertools.chain(seq1, seq2)).
1055*/
1056
1057#define NUM_PARTIALS 32 /* initial partials array size, on stack */
1058
1059/* Extend the partials array p[] by doubling its size. */
1060static int /* non-zero on error */
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001061_fsum_realloc(double **p_ptr, Py_ssize_t n,
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001062 double *ps, Py_ssize_t *m_ptr)
1063{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 void *v = NULL;
1065 Py_ssize_t m = *m_ptr;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 m += m; /* double */
Victor Stinner049e5092014-08-17 22:20:00 +02001068 if (n < m && (size_t)m < ((size_t)PY_SSIZE_T_MAX / sizeof(double))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 double *p = *p_ptr;
1070 if (p == ps) {
1071 v = PyMem_Malloc(sizeof(double) * m);
1072 if (v != NULL)
1073 memcpy(v, ps, sizeof(double) * n);
1074 }
1075 else
1076 v = PyMem_Realloc(p, sizeof(double) * m);
1077 }
1078 if (v == NULL) { /* size overflow or no memory */
1079 PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
1080 return 1;
1081 }
1082 *p_ptr = (double*) v;
1083 *m_ptr = m;
1084 return 0;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001085}
1086
1087/* Full precision summation of a sequence of floats.
1088
1089 def msum(iterable):
1090 partials = [] # sorted, non-overlapping partial sums
1091 for x in iterable:
Mark Dickinsonfdb0acc2010-06-25 20:22:24 +00001092 i = 0
1093 for y in partials:
1094 if abs(x) < abs(y):
1095 x, y = y, x
1096 hi = x + y
1097 lo = y - (hi - x)
1098 if lo:
1099 partials[i] = lo
1100 i += 1
1101 x = hi
1102 partials[i:] = [x]
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001103 return sum_exact(partials)
1104
1105 Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
1106 are exactly equal to x+y. The inner loop applies hi/lo summation to each
1107 partial so that the list of partial sums remains exact.
1108
1109 Sum_exact() adds the partial sums exactly and correctly rounds the final
1110 result (using the round-half-to-even rule). The items in partials remain
1111 non-zero, non-special, non-overlapping and strictly increasing in
1112 magnitude, but possibly not all having the same sign.
1113
1114 Depends on IEEE 754 arithmetic guarantees and half-even rounding.
1115*/
1116
1117static PyObject*
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001118math_fsum(PyObject *self, PyObject *seq)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 PyObject *item, *iter, *sum = NULL;
1121 Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
1122 double x, y, t, ps[NUM_PARTIALS], *p = ps;
1123 double xsave, special_sum = 0.0, inf_sum = 0.0;
1124 volatile double hi, yr, lo;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 iter = PyObject_GetIter(seq);
1127 if (iter == NULL)
1128 return NULL;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 for(;;) { /* for x in iterable */
1133 assert(0 <= n && n <= m);
1134 assert((m == NUM_PARTIALS && p == ps) ||
1135 (m > NUM_PARTIALS && p != NULL));
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 item = PyIter_Next(iter);
1138 if (item == NULL) {
1139 if (PyErr_Occurred())
1140 goto _fsum_error;
1141 break;
1142 }
1143 x = PyFloat_AsDouble(item);
1144 Py_DECREF(item);
1145 if (PyErr_Occurred())
1146 goto _fsum_error;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 xsave = x;
1149 for (i = j = 0; j < n; j++) { /* for y in partials */
1150 y = p[j];
1151 if (fabs(x) < fabs(y)) {
1152 t = x; x = y; y = t;
1153 }
1154 hi = x + y;
1155 yr = hi - x;
1156 lo = y - yr;
1157 if (lo != 0.0)
1158 p[i++] = lo;
1159 x = hi;
1160 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 n = i; /* ps[i:] = [x] */
1163 if (x != 0.0) {
1164 if (! Py_IS_FINITE(x)) {
1165 /* a nonfinite x could arise either as
1166 a result of intermediate overflow, or
1167 as a result of a nan or inf in the
1168 summands */
1169 if (Py_IS_FINITE(xsave)) {
1170 PyErr_SetString(PyExc_OverflowError,
1171 "intermediate overflow in fsum");
1172 goto _fsum_error;
1173 }
1174 if (Py_IS_INFINITY(xsave))
1175 inf_sum += xsave;
1176 special_sum += xsave;
1177 /* reset partials */
1178 n = 0;
1179 }
1180 else if (n >= m && _fsum_realloc(&p, n, ps, &m))
1181 goto _fsum_error;
1182 else
1183 p[n++] = x;
1184 }
1185 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 if (special_sum != 0.0) {
1188 if (Py_IS_NAN(inf_sum))
1189 PyErr_SetString(PyExc_ValueError,
1190 "-inf + inf in fsum");
1191 else
1192 sum = PyFloat_FromDouble(special_sum);
1193 goto _fsum_error;
1194 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 hi = 0.0;
1197 if (n > 0) {
1198 hi = p[--n];
1199 /* sum_exact(ps, hi) from the top, stop when the sum becomes
1200 inexact. */
1201 while (n > 0) {
1202 x = hi;
1203 y = p[--n];
1204 assert(fabs(y) < fabs(x));
1205 hi = x + y;
1206 yr = hi - x;
1207 lo = y - yr;
1208 if (lo != 0.0)
1209 break;
1210 }
1211 /* Make half-even rounding work across multiple partials.
1212 Needed so that sum([1e-16, 1, 1e16]) will round-up the last
1213 digit to two instead of down to zero (the 1e-16 makes the 1
1214 slightly closer to two). With a potential 1 ULP rounding
1215 error fixed-up, math.fsum() can guarantee commutativity. */
1216 if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
1217 (lo > 0.0 && p[n-1] > 0.0))) {
1218 y = lo * 2.0;
1219 x = hi + y;
1220 yr = x - hi;
1221 if (y == yr)
1222 hi = x;
1223 }
1224 }
1225 sum = PyFloat_FromDouble(hi);
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001226
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001227_fsum_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 PyFPE_END_PROTECT(hi)
1229 Py_DECREF(iter);
1230 if (p != ps)
1231 PyMem_Free(p);
1232 return sum;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001233}
1234
1235#undef NUM_PARTIALS
1236
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001237PyDoc_STRVAR(math_fsum_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001238"fsum(iterable)\n\n\
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001239Return an accurate floating point sum of values in the iterable.\n\
1240Assumes IEEE-754 floating point arithmetic.");
1241
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001242/* Return the smallest integer k such that n < 2**k, or 0 if n == 0.
1243 * Equivalent to floor(lg(x))+1. Also equivalent to: bitwidth_of_type -
1244 * count_leading_zero_bits(x)
1245 */
1246
1247/* XXX: This routine does more or less the same thing as
1248 * bits_in_digit() in Objects/longobject.c. Someday it would be nice to
1249 * consolidate them. On BSD, there's a library function called fls()
1250 * that we could use, and GCC provides __builtin_clz().
1251 */
1252
1253static unsigned long
1254bit_length(unsigned long n)
1255{
1256 unsigned long len = 0;
1257 while (n != 0) {
1258 ++len;
1259 n >>= 1;
1260 }
1261 return len;
1262}
1263
1264static unsigned long
1265count_set_bits(unsigned long n)
1266{
1267 unsigned long count = 0;
1268 while (n != 0) {
1269 ++count;
1270 n &= n - 1; /* clear least significant bit */
1271 }
1272 return count;
1273}
1274
1275/* Divide-and-conquer factorial algorithm
1276 *
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07001277 * Based on the formula and pseudo-code provided at:
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001278 * http://www.luschny.de/math/factorial/binarysplitfact.html
1279 *
1280 * Faster algorithms exist, but they're more complicated and depend on
Ezio Melotti9527afd2010-07-08 15:03:02 +00001281 * a fast prime factorization algorithm.
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001282 *
1283 * Notes on the algorithm
1284 * ----------------------
1285 *
1286 * factorial(n) is written in the form 2**k * m, with m odd. k and m are
1287 * computed separately, and then combined using a left shift.
1288 *
1289 * The function factorial_odd_part computes the odd part m (i.e., the greatest
1290 * odd divisor) of factorial(n), using the formula:
1291 *
1292 * factorial_odd_part(n) =
1293 *
1294 * product_{i >= 0} product_{0 < j <= n / 2**i, j odd} j
1295 *
1296 * Example: factorial_odd_part(20) =
1297 *
1298 * (1) *
1299 * (1) *
1300 * (1 * 3 * 5) *
1301 * (1 * 3 * 5 * 7 * 9)
1302 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1303 *
1304 * Here i goes from large to small: the first term corresponds to i=4 (any
1305 * larger i gives an empty product), and the last term corresponds to i=0.
1306 * Each term can be computed from the last by multiplying by the extra odd
1307 * numbers required: e.g., to get from the penultimate term to the last one,
1308 * we multiply by (11 * 13 * 15 * 17 * 19).
1309 *
1310 * To see a hint of why this formula works, here are the same numbers as above
1311 * but with the even parts (i.e., the appropriate powers of 2) included. For
1312 * each subterm in the product for i, we multiply that subterm by 2**i:
1313 *
1314 * factorial(20) =
1315 *
1316 * (16) *
1317 * (8) *
1318 * (4 * 12 * 20) *
1319 * (2 * 6 * 10 * 14 * 18) *
1320 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1321 *
1322 * The factorial_partial_product function computes the product of all odd j in
1323 * range(start, stop) for given start and stop. It's used to compute the
1324 * partial products like (11 * 13 * 15 * 17 * 19) in the example above. It
1325 * operates recursively, repeatedly splitting the range into two roughly equal
1326 * pieces until the subranges are small enough to be computed using only C
1327 * integer arithmetic.
1328 *
1329 * The two-valuation k (i.e., the exponent of the largest power of 2 dividing
1330 * the factorial) is computed independently in the main math_factorial
1331 * function. By standard results, its value is:
1332 *
1333 * two_valuation = n//2 + n//4 + n//8 + ....
1334 *
1335 * It can be shown (e.g., by complete induction on n) that two_valuation is
1336 * equal to n - count_set_bits(n), where count_set_bits(n) gives the number of
1337 * '1'-bits in the binary expansion of n.
1338 */
1339
1340/* factorial_partial_product: Compute product(range(start, stop, 2)) using
1341 * divide and conquer. Assumes start and stop are odd and stop > start.
1342 * max_bits must be >= bit_length(stop - 2). */
1343
1344static PyObject *
1345factorial_partial_product(unsigned long start, unsigned long stop,
1346 unsigned long max_bits)
1347{
1348 unsigned long midpoint, num_operands;
1349 PyObject *left = NULL, *right = NULL, *result = NULL;
1350
1351 /* If the return value will fit an unsigned long, then we can
1352 * multiply in a tight, fast loop where each multiply is O(1).
1353 * Compute an upper bound on the number of bits required to store
1354 * the answer.
1355 *
1356 * Storing some integer z requires floor(lg(z))+1 bits, which is
1357 * conveniently the value returned by bit_length(z). The
1358 * product x*y will require at most
1359 * bit_length(x) + bit_length(y) bits to store, based
1360 * on the idea that lg product = lg x + lg y.
1361 *
1362 * We know that stop - 2 is the largest number to be multiplied. From
1363 * there, we have: bit_length(answer) <= num_operands *
1364 * bit_length(stop - 2)
1365 */
1366
1367 num_operands = (stop - start) / 2;
1368 /* The "num_operands <= 8 * SIZEOF_LONG" check guards against the
1369 * unlikely case of an overflow in num_operands * max_bits. */
1370 if (num_operands <= 8 * SIZEOF_LONG &&
1371 num_operands * max_bits <= 8 * SIZEOF_LONG) {
1372 unsigned long j, total;
1373 for (total = start, j = start + 2; j < stop; j += 2)
1374 total *= j;
1375 return PyLong_FromUnsignedLong(total);
1376 }
1377
1378 /* find midpoint of range(start, stop), rounded up to next odd number. */
1379 midpoint = (start + num_operands) | 1;
1380 left = factorial_partial_product(start, midpoint,
1381 bit_length(midpoint - 2));
1382 if (left == NULL)
1383 goto error;
1384 right = factorial_partial_product(midpoint, stop, max_bits);
1385 if (right == NULL)
1386 goto error;
1387 result = PyNumber_Multiply(left, right);
1388
1389 error:
1390 Py_XDECREF(left);
1391 Py_XDECREF(right);
1392 return result;
1393}
1394
1395/* factorial_odd_part: compute the odd part of factorial(n). */
1396
1397static PyObject *
1398factorial_odd_part(unsigned long n)
1399{
1400 long i;
1401 unsigned long v, lower, upper;
1402 PyObject *partial, *tmp, *inner, *outer;
1403
1404 inner = PyLong_FromLong(1);
1405 if (inner == NULL)
1406 return NULL;
1407 outer = inner;
1408 Py_INCREF(outer);
1409
1410 upper = 3;
1411 for (i = bit_length(n) - 2; i >= 0; i--) {
1412 v = n >> i;
1413 if (v <= 2)
1414 continue;
1415 lower = upper;
1416 /* (v + 1) | 1 = least odd integer strictly larger than n / 2**i */
1417 upper = (v + 1) | 1;
1418 /* Here inner is the product of all odd integers j in the range (0,
1419 n/2**(i+1)]. The factorial_partial_product call below gives the
1420 product of all odd integers j in the range (n/2**(i+1), n/2**i]. */
1421 partial = factorial_partial_product(lower, upper, bit_length(upper-2));
1422 /* inner *= partial */
1423 if (partial == NULL)
1424 goto error;
1425 tmp = PyNumber_Multiply(inner, partial);
1426 Py_DECREF(partial);
1427 if (tmp == NULL)
1428 goto error;
1429 Py_DECREF(inner);
1430 inner = tmp;
1431 /* Now inner is the product of all odd integers j in the range (0,
1432 n/2**i], giving the inner product in the formula above. */
1433
1434 /* outer *= inner; */
1435 tmp = PyNumber_Multiply(outer, inner);
1436 if (tmp == NULL)
1437 goto error;
1438 Py_DECREF(outer);
1439 outer = tmp;
1440 }
Mark Dickinson76464492012-10-25 10:46:28 +01001441 Py_DECREF(inner);
1442 return outer;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001443
1444 error:
1445 Py_DECREF(outer);
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001446 Py_DECREF(inner);
Mark Dickinson76464492012-10-25 10:46:28 +01001447 return NULL;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001448}
1449
1450/* Lookup table for small factorial values */
1451
1452static const unsigned long SmallFactorials[] = {
1453 1, 1, 2, 6, 24, 120, 720, 5040, 40320,
1454 362880, 3628800, 39916800, 479001600,
1455#if SIZEOF_LONG >= 8
1456 6227020800, 87178291200, 1307674368000,
1457 20922789888000, 355687428096000, 6402373705728000,
1458 121645100408832000, 2432902008176640000
1459#endif
1460};
1461
Barry Warsaw8b43b191996-12-09 22:32:36 +00001462static PyObject *
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001463math_factorial(PyObject *self, PyObject *arg)
1464{
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001465 long x;
Mark Dickinson5990d282014-04-10 09:29:39 -04001466 int overflow;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001467 PyObject *result, *odd_part, *two_valuation;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 if (PyFloat_Check(arg)) {
1470 PyObject *lx;
1471 double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
1472 if (!(Py_IS_FINITE(dx) && dx == floor(dx))) {
1473 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001474 "factorial() only accepts integral values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 return NULL;
1476 }
1477 lx = PyLong_FromDouble(dx);
1478 if (lx == NULL)
1479 return NULL;
Mark Dickinson5990d282014-04-10 09:29:39 -04001480 x = PyLong_AsLongAndOverflow(lx, &overflow);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 Py_DECREF(lx);
1482 }
1483 else
Mark Dickinson5990d282014-04-10 09:29:39 -04001484 x = PyLong_AsLongAndOverflow(arg, &overflow);
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001485
Mark Dickinson5990d282014-04-10 09:29:39 -04001486 if (x == -1 && PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 return NULL;
Mark Dickinson5990d282014-04-10 09:29:39 -04001488 }
1489 else if (overflow == 1) {
1490 PyErr_Format(PyExc_OverflowError,
1491 "factorial() argument should not exceed %ld",
1492 LONG_MAX);
1493 return NULL;
1494 }
1495 else if (overflow == -1 || x < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001497 "factorial() not defined for negative values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 return NULL;
1499 }
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001500
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001501 /* use lookup table if x is small */
Victor Stinner63941882011-09-29 00:42:28 +02001502 if (x < (long)Py_ARRAY_LENGTH(SmallFactorials))
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001503 return PyLong_FromUnsignedLong(SmallFactorials[x]);
1504
1505 /* else express in the form odd_part * 2**two_valuation, and compute as
1506 odd_part << two_valuation. */
1507 odd_part = factorial_odd_part(x);
1508 if (odd_part == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 return NULL;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001510 two_valuation = PyLong_FromLong(x - count_set_bits(x));
1511 if (two_valuation == NULL) {
1512 Py_DECREF(odd_part);
1513 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 }
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001515 result = PyNumber_Lshift(odd_part, two_valuation);
1516 Py_DECREF(two_valuation);
1517 Py_DECREF(odd_part);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 return result;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001519}
1520
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001521PyDoc_STRVAR(math_factorial_doc,
1522"factorial(x) -> Integral\n"
1523"\n"
1524"Find x!. Raise a ValueError if x is negative or non-integral.");
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001525
1526static PyObject *
Christian Heimes400adb02008-02-01 08:12:03 +00001527math_trunc(PyObject *self, PyObject *number)
1528{
Benjamin Petersonce798522012-01-22 11:24:29 -05001529 _Py_IDENTIFIER(__trunc__);
Benjamin Petersonb0125892010-07-02 13:35:17 +00001530 PyObject *trunc, *result;
Christian Heimes400adb02008-02-01 08:12:03 +00001531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 if (Py_TYPE(number)->tp_dict == NULL) {
1533 if (PyType_Ready(Py_TYPE(number)) < 0)
1534 return NULL;
1535 }
Christian Heimes400adb02008-02-01 08:12:03 +00001536
Benjamin Petersonce798522012-01-22 11:24:29 -05001537 trunc = _PyObject_LookupSpecial(number, &PyId___trunc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 if (trunc == NULL) {
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001539 if (!PyErr_Occurred())
1540 PyErr_Format(PyExc_TypeError,
1541 "type %.100s doesn't define __trunc__ method",
1542 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 return NULL;
1544 }
Benjamin Petersonb0125892010-07-02 13:35:17 +00001545 result = PyObject_CallFunctionObjArgs(trunc, NULL);
1546 Py_DECREF(trunc);
1547 return result;
Christian Heimes400adb02008-02-01 08:12:03 +00001548}
1549
1550PyDoc_STRVAR(math_trunc_doc,
1551"trunc(x:Real) -> Integral\n"
1552"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001553"Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.");
Christian Heimes400adb02008-02-01 08:12:03 +00001554
1555static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001556math_frexp(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 int i;
1559 double x = PyFloat_AsDouble(arg);
1560 if (x == -1.0 && PyErr_Occurred())
1561 return NULL;
1562 /* deal with special cases directly, to sidestep platform
1563 differences */
1564 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
1565 i = 0;
1566 }
1567 else {
1568 PyFPE_START_PROTECT("in math_frexp", return 0);
1569 x = frexp(x, &i);
1570 PyFPE_END_PROTECT(x);
1571 }
1572 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001573}
1574
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001575PyDoc_STRVAR(math_frexp_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001576"frexp(x)\n"
1577"\n"
1578"Return the mantissa and exponent of x, as pair (m, e).\n"
1579"m is a float and e is an int, such that x = m * 2.**e.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001580"If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001581
Barry Warsaw8b43b191996-12-09 22:32:36 +00001582static PyObject *
Fred Drake40c48682000-07-03 18:11:56 +00001583math_ldexp(PyObject *self, PyObject *args)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001584{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 double x, r;
1586 PyObject *oexp;
1587 long exp;
1588 int overflow;
1589 if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp))
1590 return NULL;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 if (PyLong_Check(oexp)) {
1593 /* on overflow, replace exponent with either LONG_MAX
1594 or LONG_MIN, depending on the sign. */
1595 exp = PyLong_AsLongAndOverflow(oexp, &overflow);
1596 if (exp == -1 && PyErr_Occurred())
1597 return NULL;
1598 if (overflow)
1599 exp = overflow < 0 ? LONG_MIN : LONG_MAX;
1600 }
1601 else {
1602 PyErr_SetString(PyExc_TypeError,
Serhiy Storchaka95949422013-08-27 19:40:23 +03001603 "Expected an int as second argument to ldexp.");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 return NULL;
1605 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 if (x == 0. || !Py_IS_FINITE(x)) {
1608 /* NaNs, zeros and infinities are returned unchanged */
1609 r = x;
1610 errno = 0;
1611 } else if (exp > INT_MAX) {
1612 /* overflow */
1613 r = copysign(Py_HUGE_VAL, x);
1614 errno = ERANGE;
1615 } else if (exp < INT_MIN) {
1616 /* underflow to +-0 */
1617 r = copysign(0., x);
1618 errno = 0;
1619 } else {
1620 errno = 0;
1621 PyFPE_START_PROTECT("in math_ldexp", return 0);
1622 r = ldexp(x, (int)exp);
1623 PyFPE_END_PROTECT(r);
1624 if (Py_IS_INFINITY(r))
1625 errno = ERANGE;
1626 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 if (errno && is_error(r))
1629 return NULL;
1630 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001631}
1632
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001633PyDoc_STRVAR(math_ldexp_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001634"ldexp(x, i)\n\n\
1635Return x * (2**i).");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001636
Barry Warsaw8b43b191996-12-09 22:32:36 +00001637static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001638math_modf(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001639{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 double y, x = PyFloat_AsDouble(arg);
1641 if (x == -1.0 && PyErr_Occurred())
1642 return NULL;
1643 /* some platforms don't do the right thing for NaNs and
1644 infinities, so we take care of special cases directly. */
1645 if (!Py_IS_FINITE(x)) {
1646 if (Py_IS_INFINITY(x))
1647 return Py_BuildValue("(dd)", copysign(0., x), x);
1648 else if (Py_IS_NAN(x))
1649 return Py_BuildValue("(dd)", x, x);
1650 }
Christian Heimesa342c012008-04-20 21:01:16 +00001651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 errno = 0;
1653 PyFPE_START_PROTECT("in math_modf", return 0);
1654 x = modf(x, &y);
1655 PyFPE_END_PROTECT(x);
1656 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001657}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001658
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001659PyDoc_STRVAR(math_modf_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001660"modf(x)\n"
1661"\n"
1662"Return the fractional and integer parts of x. Both results carry the sign\n"
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001663"of x and are floats.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001664
Serhiy Storchaka95949422013-08-27 19:40:23 +03001665/* A decent logarithm is easy to compute even for huge ints, but libm can't
Tim Peters78526162001-09-05 00:53:45 +00001666 do that by itself -- loghelper can. func is log or log10, and name is
Serhiy Storchaka95949422013-08-27 19:40:23 +03001667 "log" or "log10". Note that overflow of the result isn't possible: an int
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00001668 can contain no more than INT_MAX * SHIFT bits, so has value certainly less
1669 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 +00001670 small enough to fit in an IEEE single. log and log10 are even smaller.
Serhiy Storchaka95949422013-08-27 19:40:23 +03001671 However, intermediate overflow is possible for an int if the number of bits
1672 in that int is larger than PY_SSIZE_T_MAX. */
Tim Peters78526162001-09-05 00:53:45 +00001673
1674static PyObject*
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001675loghelper(PyObject* arg, double (*func)(double), const char *funcname)
Tim Peters78526162001-09-05 00:53:45 +00001676{
Serhiy Storchaka95949422013-08-27 19:40:23 +03001677 /* If it is int, do it ourselves. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 if (PyLong_Check(arg)) {
Mark Dickinsonc6037172010-09-29 19:06:36 +00001679 double x, result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 Py_ssize_t e;
Mark Dickinsonc6037172010-09-29 19:06:36 +00001681
1682 /* Negative or zero inputs give a ValueError. */
1683 if (Py_SIZE(arg) <= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 PyErr_SetString(PyExc_ValueError,
1685 "math domain error");
1686 return NULL;
1687 }
Mark Dickinsonfa41e602010-09-28 07:22:27 +00001688
Mark Dickinsonc6037172010-09-29 19:06:36 +00001689 x = PyLong_AsDouble(arg);
1690 if (x == -1.0 && PyErr_Occurred()) {
1691 if (!PyErr_ExceptionMatches(PyExc_OverflowError))
1692 return NULL;
1693 /* Here the conversion to double overflowed, but it's possible
1694 to compute the log anyway. Clear the exception and continue. */
1695 PyErr_Clear();
1696 x = _PyLong_Frexp((PyLongObject *)arg, &e);
1697 if (x == -1.0 && PyErr_Occurred())
1698 return NULL;
1699 /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */
1700 result = func(x) + func(2.0) * e;
1701 }
1702 else
1703 /* Successfully converted x to a double. */
1704 result = func(x);
1705 return PyFloat_FromDouble(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 }
Tim Peters78526162001-09-05 00:53:45 +00001707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 /* Else let libm handle it by itself. */
1709 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +00001710}
1711
1712static PyObject *
1713math_log(PyObject *self, PyObject *args)
1714{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 PyObject *arg;
1716 PyObject *base = NULL;
1717 PyObject *num, *den;
1718 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base))
1721 return NULL;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 num = loghelper(arg, m_log, "log");
1724 if (num == NULL || base == NULL)
1725 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 den = loghelper(base, m_log, "log");
1728 if (den == NULL) {
1729 Py_DECREF(num);
1730 return NULL;
1731 }
Raymond Hettinger866964c2002-12-14 19:51:34 +00001732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 ans = PyNumber_TrueDivide(num, den);
1734 Py_DECREF(num);
1735 Py_DECREF(den);
1736 return ans;
Tim Peters78526162001-09-05 00:53:45 +00001737}
1738
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001739PyDoc_STRVAR(math_log_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001740"log(x[, base])\n\n\
1741Return the logarithm of x to the given base.\n\
Raymond Hettinger866964c2002-12-14 19:51:34 +00001742If the base not specified, returns the natural logarithm (base e) of x.");
Tim Peters78526162001-09-05 00:53:45 +00001743
1744static PyObject *
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001745math_log2(PyObject *self, PyObject *arg)
1746{
1747 return loghelper(arg, m_log2, "log2");
1748}
1749
1750PyDoc_STRVAR(math_log2_doc,
1751"log2(x)\n\nReturn the base 2 logarithm of x.");
1752
1753static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001754math_log10(PyObject *self, PyObject *arg)
Tim Peters78526162001-09-05 00:53:45 +00001755{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 return loghelper(arg, m_log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +00001757}
1758
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001759PyDoc_STRVAR(math_log10_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001760"log10(x)\n\nReturn the base 10 logarithm of x.");
Tim Peters78526162001-09-05 00:53:45 +00001761
Christian Heimes53876d92008-04-19 00:31:39 +00001762static PyObject *
1763math_fmod(PyObject *self, PyObject *args)
1764{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 PyObject *ox, *oy;
1766 double r, x, y;
1767 if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy))
1768 return NULL;
1769 x = PyFloat_AsDouble(ox);
1770 y = PyFloat_AsDouble(oy);
1771 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1772 return NULL;
1773 /* fmod(x, +/-Inf) returns x for finite x. */
1774 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
1775 return PyFloat_FromDouble(x);
1776 errno = 0;
1777 PyFPE_START_PROTECT("in math_fmod", return 0);
1778 r = fmod(x, y);
1779 PyFPE_END_PROTECT(r);
1780 if (Py_IS_NAN(r)) {
1781 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1782 errno = EDOM;
1783 else
1784 errno = 0;
1785 }
1786 if (errno && is_error(r))
1787 return NULL;
1788 else
1789 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00001790}
1791
1792PyDoc_STRVAR(math_fmod_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001793"fmod(x, y)\n\nReturn fmod(x, y), according to platform C."
Christian Heimes53876d92008-04-19 00:31:39 +00001794" x % y may differ.");
1795
1796static PyObject *
1797math_hypot(PyObject *self, PyObject *args)
1798{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 PyObject *ox, *oy;
1800 double r, x, y;
1801 if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy))
1802 return NULL;
1803 x = PyFloat_AsDouble(ox);
1804 y = PyFloat_AsDouble(oy);
1805 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1806 return NULL;
1807 /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */
1808 if (Py_IS_INFINITY(x))
1809 return PyFloat_FromDouble(fabs(x));
1810 if (Py_IS_INFINITY(y))
1811 return PyFloat_FromDouble(fabs(y));
1812 errno = 0;
1813 PyFPE_START_PROTECT("in math_hypot", return 0);
1814 r = hypot(x, y);
1815 PyFPE_END_PROTECT(r);
1816 if (Py_IS_NAN(r)) {
1817 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1818 errno = EDOM;
1819 else
1820 errno = 0;
1821 }
1822 else if (Py_IS_INFINITY(r)) {
1823 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
1824 errno = ERANGE;
1825 else
1826 errno = 0;
1827 }
1828 if (errno && is_error(r))
1829 return NULL;
1830 else
1831 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00001832}
1833
1834PyDoc_STRVAR(math_hypot_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001835"hypot(x, y)\n\nReturn the Euclidean distance, sqrt(x*x + y*y).");
Christian Heimes53876d92008-04-19 00:31:39 +00001836
1837/* pow can't use math_2, but needs its own wrapper: the problem is
1838 that an infinite result can arise either as a result of overflow
1839 (in which case OverflowError should be raised) or as a result of
1840 e.g. 0.**-5. (for which ValueError needs to be raised.)
1841*/
1842
1843static PyObject *
1844math_pow(PyObject *self, PyObject *args)
1845{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 PyObject *ox, *oy;
1847 double r, x, y;
1848 int odd_y;
Christian Heimes53876d92008-04-19 00:31:39 +00001849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy))
1851 return NULL;
1852 x = PyFloat_AsDouble(ox);
1853 y = PyFloat_AsDouble(oy);
1854 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1855 return NULL;
Christian Heimesa342c012008-04-20 21:01:16 +00001856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 /* deal directly with IEEE specials, to cope with problems on various
1858 platforms whose semantics don't exactly match C99 */
1859 r = 0.; /* silence compiler warning */
1860 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
1861 errno = 0;
1862 if (Py_IS_NAN(x))
1863 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
1864 else if (Py_IS_NAN(y))
1865 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
1866 else if (Py_IS_INFINITY(x)) {
1867 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
1868 if (y > 0.)
1869 r = odd_y ? x : fabs(x);
1870 else if (y == 0.)
1871 r = 1.;
1872 else /* y < 0. */
1873 r = odd_y ? copysign(0., x) : 0.;
1874 }
1875 else if (Py_IS_INFINITY(y)) {
1876 if (fabs(x) == 1.0)
1877 r = 1.;
1878 else if (y > 0. && fabs(x) > 1.0)
1879 r = y;
1880 else if (y < 0. && fabs(x) < 1.0) {
1881 r = -y; /* result is +inf */
1882 if (x == 0.) /* 0**-inf: divide-by-zero */
1883 errno = EDOM;
1884 }
1885 else
1886 r = 0.;
1887 }
1888 }
1889 else {
1890 /* let libm handle finite**finite */
1891 errno = 0;
1892 PyFPE_START_PROTECT("in math_pow", return 0);
1893 r = pow(x, y);
1894 PyFPE_END_PROTECT(r);
1895 /* a NaN result should arise only from (-ve)**(finite
1896 non-integer); in this case we want to raise ValueError. */
1897 if (!Py_IS_FINITE(r)) {
1898 if (Py_IS_NAN(r)) {
1899 errno = EDOM;
1900 }
1901 /*
1902 an infinite result here arises either from:
1903 (A) (+/-0.)**negative (-> divide-by-zero)
1904 (B) overflow of x**y with x and y finite
1905 */
1906 else if (Py_IS_INFINITY(r)) {
1907 if (x == 0.)
1908 errno = EDOM;
1909 else
1910 errno = ERANGE;
1911 }
1912 }
1913 }
Christian Heimes53876d92008-04-19 00:31:39 +00001914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 if (errno && is_error(r))
1916 return NULL;
1917 else
1918 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00001919}
1920
1921PyDoc_STRVAR(math_pow_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001922"pow(x, y)\n\nReturn x**y (x to the power of y).");
Christian Heimes53876d92008-04-19 00:31:39 +00001923
Christian Heimes072c0f12008-01-03 23:01:04 +00001924static const double degToRad = Py_MATH_PI / 180.0;
1925static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001926
1927static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001928math_degrees(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001929{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 double x = PyFloat_AsDouble(arg);
1931 if (x == -1.0 && PyErr_Occurred())
1932 return NULL;
1933 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001934}
1935
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001936PyDoc_STRVAR(math_degrees_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001937"degrees(x)\n\n\
1938Convert angle x from radians to degrees.");
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001939
1940static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001941math_radians(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001942{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 double x = PyFloat_AsDouble(arg);
1944 if (x == -1.0 && PyErr_Occurred())
1945 return NULL;
1946 return PyFloat_FromDouble(x * degToRad);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001947}
1948
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001949PyDoc_STRVAR(math_radians_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001950"radians(x)\n\n\
1951Convert angle x from degrees to radians.");
Tim Peters78526162001-09-05 00:53:45 +00001952
Christian Heimes072c0f12008-01-03 23:01:04 +00001953static PyObject *
Mark Dickinson8e0c9962010-07-11 17:38:24 +00001954math_isfinite(PyObject *self, PyObject *arg)
1955{
1956 double x = PyFloat_AsDouble(arg);
1957 if (x == -1.0 && PyErr_Occurred())
1958 return NULL;
1959 return PyBool_FromLong((long)Py_IS_FINITE(x));
1960}
1961
1962PyDoc_STRVAR(math_isfinite_doc,
1963"isfinite(x) -> bool\n\n\
Mark Dickinson226f5442010-07-11 18:13:41 +00001964Return True if x is neither an infinity nor a NaN, and False otherwise.");
Mark Dickinson8e0c9962010-07-11 17:38:24 +00001965
1966static PyObject *
Christian Heimes072c0f12008-01-03 23:01:04 +00001967math_isnan(PyObject *self, PyObject *arg)
1968{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 double x = PyFloat_AsDouble(arg);
1970 if (x == -1.0 && PyErr_Occurred())
1971 return NULL;
1972 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00001973}
1974
1975PyDoc_STRVAR(math_isnan_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001976"isnan(x) -> bool\n\n\
Mark Dickinson226f5442010-07-11 18:13:41 +00001977Return True if x is a NaN (not a number), and False otherwise.");
Christian Heimes072c0f12008-01-03 23:01:04 +00001978
1979static PyObject *
1980math_isinf(PyObject *self, PyObject *arg)
1981{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 double x = PyFloat_AsDouble(arg);
1983 if (x == -1.0 && PyErr_Occurred())
1984 return NULL;
1985 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00001986}
1987
1988PyDoc_STRVAR(math_isinf_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001989"isinf(x) -> bool\n\n\
Mark Dickinson226f5442010-07-11 18:13:41 +00001990Return True if x is a positive or negative infinity, and False otherwise.");
Christian Heimes072c0f12008-01-03 23:01:04 +00001991
Tal Einatd5519ed2015-05-31 22:05:00 +03001992static PyObject *
1993math_isclose(PyObject *self, PyObject *args, PyObject *kwargs)
1994{
1995 double a, b;
1996 double rel_tol = 1e-9;
1997 double abs_tol = 0.0;
1998 double diff = 0.0;
1999 long result = 0;
2000
2001 static char *keywords[] = {"a", "b", "rel_tol", "abs_tol", NULL};
2002
2003
2004 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "dd|$dd:isclose",
2005 keywords,
2006 &a, &b, &rel_tol, &abs_tol
2007 ))
2008 return NULL;
2009
2010 /* sanity check on the inputs */
2011 if (rel_tol < 0.0 || abs_tol < 0.0 ) {
2012 PyErr_SetString(PyExc_ValueError,
2013 "tolerances must be non-negative");
2014 return NULL;
2015 }
2016
2017 if ( a == b ) {
2018 /* short circuit exact equality -- needed to catch two infinities of
2019 the same sign. And perhaps speeds things up a bit sometimes.
2020 */
2021 Py_RETURN_TRUE;
2022 }
2023
2024 /* This catches the case of two infinities of opposite sign, or
2025 one infinity and one finite number. Two infinities of opposite
2026 sign would otherwise have an infinite relative tolerance.
2027 Two infinities of the same sign are caught by the equality check
2028 above.
2029 */
2030
2031 if (Py_IS_INFINITY(a) || Py_IS_INFINITY(b)) {
2032 Py_RETURN_FALSE;
2033 }
2034
2035 /* now do the regular computation
2036 this is essentially the "weak" test from the Boost library
2037 */
2038
2039 diff = fabs(b - a);
2040
2041 result = (((diff <= fabs(rel_tol * b)) ||
2042 (diff <= fabs(rel_tol * a))) ||
2043 (diff <= abs_tol));
2044
2045 return PyBool_FromLong(result);
2046}
2047
2048PyDoc_STRVAR(math_isclose_doc,
Berker Peksagd6e6f8b2016-05-01 11:27:37 +03002049"isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0) -> bool\n"
Tal Einatd5519ed2015-05-31 22:05:00 +03002050"\n"
2051"Determine whether two floating point numbers are close in value.\n"
2052"\n"
2053" rel_tol\n"
2054" maximum difference for being considered \"close\", relative to the\n"
2055" magnitude of the input values\n"
2056" abs_tol\n"
2057" maximum difference for being considered \"close\", regardless of the\n"
2058" magnitude of the input values\n"
2059"\n"
2060"Return True if a is close in value to b, and False otherwise.\n"
2061"\n"
2062"For the values to be considered close, the difference between them\n"
2063"must be smaller than at least one of the tolerances.\n"
2064"\n"
2065"-inf, inf and NaN behave similarly to the IEEE 754 Standard. That\n"
2066"is, NaN is not close to anything, even itself. inf and -inf are\n"
2067"only close to themselves.");
2068
Barry Warsaw8b43b191996-12-09 22:32:36 +00002069static PyMethodDef math_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 {"acos", math_acos, METH_O, math_acos_doc},
2071 {"acosh", math_acosh, METH_O, math_acosh_doc},
2072 {"asin", math_asin, METH_O, math_asin_doc},
2073 {"asinh", math_asinh, METH_O, math_asinh_doc},
2074 {"atan", math_atan, METH_O, math_atan_doc},
2075 {"atan2", math_atan2, METH_VARARGS, math_atan2_doc},
2076 {"atanh", math_atanh, METH_O, math_atanh_doc},
2077 {"ceil", math_ceil, METH_O, math_ceil_doc},
2078 {"copysign", math_copysign, METH_VARARGS, math_copysign_doc},
2079 {"cos", math_cos, METH_O, math_cos_doc},
2080 {"cosh", math_cosh, METH_O, math_cosh_doc},
2081 {"degrees", math_degrees, METH_O, math_degrees_doc},
2082 {"erf", math_erf, METH_O, math_erf_doc},
2083 {"erfc", math_erfc, METH_O, math_erfc_doc},
2084 {"exp", math_exp, METH_O, math_exp_doc},
2085 {"expm1", math_expm1, METH_O, math_expm1_doc},
2086 {"fabs", math_fabs, METH_O, math_fabs_doc},
2087 {"factorial", math_factorial, METH_O, math_factorial_doc},
2088 {"floor", math_floor, METH_O, math_floor_doc},
2089 {"fmod", math_fmod, METH_VARARGS, math_fmod_doc},
2090 {"frexp", math_frexp, METH_O, math_frexp_doc},
2091 {"fsum", math_fsum, METH_O, math_fsum_doc},
2092 {"gamma", math_gamma, METH_O, math_gamma_doc},
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03002093 {"gcd", math_gcd, METH_VARARGS, math_gcd_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 {"hypot", math_hypot, METH_VARARGS, math_hypot_doc},
Tal Einatd5519ed2015-05-31 22:05:00 +03002095 {"isclose", (PyCFunction) math_isclose, METH_VARARGS | METH_KEYWORDS,
2096 math_isclose_doc},
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002097 {"isfinite", math_isfinite, METH_O, math_isfinite_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 {"isinf", math_isinf, METH_O, math_isinf_doc},
2099 {"isnan", math_isnan, METH_O, math_isnan_doc},
2100 {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc},
2101 {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
2102 {"log", math_log, METH_VARARGS, math_log_doc},
2103 {"log1p", math_log1p, METH_O, math_log1p_doc},
2104 {"log10", math_log10, METH_O, math_log10_doc},
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02002105 {"log2", math_log2, METH_O, math_log2_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 {"modf", math_modf, METH_O, math_modf_doc},
2107 {"pow", math_pow, METH_VARARGS, math_pow_doc},
2108 {"radians", math_radians, METH_O, math_radians_doc},
2109 {"sin", math_sin, METH_O, math_sin_doc},
2110 {"sinh", math_sinh, METH_O, math_sinh_doc},
2111 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
2112 {"tan", math_tan, METH_O, math_tan_doc},
2113 {"tanh", math_tanh, METH_O, math_tanh_doc},
2114 {"trunc", math_trunc, METH_O, math_trunc_doc},
2115 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002116};
2117
Guido van Rossumc6e22901998-12-04 19:26:43 +00002118
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002119PyDoc_STRVAR(module_doc,
Tim Peters63c94532001-09-04 23:17:42 +00002120"This module is always available. It provides access to the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002121"mathematical functions defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00002122
Martin v. Löwis1a214512008-06-11 05:26:20 +00002123
2124static struct PyModuleDef mathmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 PyModuleDef_HEAD_INIT,
2126 "math",
2127 module_doc,
2128 -1,
2129 math_methods,
2130 NULL,
2131 NULL,
2132 NULL,
2133 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002134};
2135
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002136PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002137PyInit_math(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002138{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 PyObject *m;
Tim Petersfe71f812001-08-07 22:10:00 +00002140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 m = PyModule_Create(&mathmodule);
2142 if (m == NULL)
2143 goto finally;
Barry Warsawfc93f751996-12-17 00:47:03 +00002144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
2146 PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
Guido van Rossum0a891d72016-08-15 09:12:52 -07002147 PyModule_AddObject(m, "tau", PyFloat_FromDouble(Py_MATH_TAU)); /* 2pi */
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +00002148 PyModule_AddObject(m, "inf", PyFloat_FromDouble(m_inf()));
2149#if !defined(PY_NO_SHORT_FLOAT_REPR) || defined(Py_NAN)
2150 PyModule_AddObject(m, "nan", PyFloat_FromDouble(m_nan()));
2151#endif
Barry Warsawfc93f751996-12-17 00:47:03 +00002152
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +00002153 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002155}