blob: 9359eb2b3a0f6ad71c663b128b48c9a0edb854fc [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
403 Method: following 'Numerical Recipes' by Flannery, Press et. al. (2nd ed.,
404 Cambridge University Press), we use a series approximation for erf for
405 small x, and a continued fraction approximation for erfc(x) for larger x;
406 combined with the relations erf(-x) = -erf(x) and erfc(x) = 1.0 - erf(x),
407 this gives us erf(x) and erfc(x) for all x.
408
409 The series expansion used is:
410
411 erf(x) = x*exp(-x*x)/sqrt(pi) * [
412 2/1 + 4/3 x**2 + 8/15 x**4 + 16/105 x**6 + ...]
413
414 The coefficient of x**(2k-2) here is 4**k*factorial(k)/factorial(2*k).
415 This series converges well for smallish x, but slowly for larger x.
416
417 The continued fraction expansion used is:
418
419 erfc(x) = x*exp(-x*x)/sqrt(pi) * [1/(0.5 + x**2 -) 0.5/(2.5 + x**2 - )
420 3.0/(4.5 + x**2 - ) 7.5/(6.5 + x**2 - ) ...]
421
422 after the first term, the general term has the form:
423
424 k*(k-0.5)/(2*k+0.5 + x**2 - ...).
425
426 This expansion converges fast for larger x, but convergence becomes
427 infinitely slow as x approaches 0.0. The (somewhat naive) continued
428 fraction evaluation algorithm used below also risks overflow for large x;
429 but for large x, erfc(x) == 0.0 to within machine precision. (For
430 example, erfc(30.0) is approximately 2.56e-393).
431
432 Parameters: use series expansion for abs(x) < ERF_SERIES_CUTOFF and
433 continued fraction expansion for ERF_SERIES_CUTOFF <= abs(x) <
434 ERFC_CONTFRAC_CUTOFF. ERFC_SERIES_TERMS and ERFC_CONTFRAC_TERMS are the
435 numbers of terms to use for the relevant expansions. */
436
437#define ERF_SERIES_CUTOFF 1.5
438#define ERF_SERIES_TERMS 25
439#define ERFC_CONTFRAC_CUTOFF 30.0
440#define ERFC_CONTFRAC_TERMS 50
441
442/*
443 Error function, via power series.
444
445 Given a finite float x, return an approximation to erf(x).
446 Converges reasonably fast for small x.
447*/
448
449static double
450m_erf_series(double x)
451{
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000452 double x2, acc, fk, result;
453 int i, saved_errno;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 x2 = x * x;
456 acc = 0.0;
457 fk = (double)ERF_SERIES_TERMS + 0.5;
458 for (i = 0; i < ERF_SERIES_TERMS; i++) {
459 acc = 2.0 + x2 * acc / fk;
460 fk -= 1.0;
461 }
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000462 /* Make sure the exp call doesn't affect errno;
463 see m_erfc_contfrac for more. */
464 saved_errno = errno;
465 result = acc * x * exp(-x2) / sqrtpi;
466 errno = saved_errno;
467 return result;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000468}
469
470/*
471 Complementary error function, via continued fraction expansion.
472
473 Given a positive float x, return an approximation to erfc(x). Converges
474 reasonably fast for x large (say, x > 2.0), and should be safe from
475 overflow if x and nterms are not too large. On an IEEE 754 machine, with x
476 <= 30.0, we're safe up to nterms = 100. For x >= 30.0, erfc(x) is smaller
477 than the smallest representable nonzero float. */
478
479static double
480m_erfc_contfrac(double x)
481{
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000482 double x2, a, da, p, p_last, q, q_last, b, result;
483 int i, saved_errno;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 if (x >= ERFC_CONTFRAC_CUTOFF)
486 return 0.0;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 x2 = x*x;
489 a = 0.0;
490 da = 0.5;
491 p = 1.0; p_last = 0.0;
492 q = da + x2; q_last = 1.0;
493 for (i = 0; i < ERFC_CONTFRAC_TERMS; i++) {
494 double temp;
495 a += da;
496 da += 2.0;
497 b = da + x2;
498 temp = p; p = b*p - a*p_last; p_last = temp;
499 temp = q; q = b*q - a*q_last; q_last = temp;
500 }
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000501 /* Issue #8986: On some platforms, exp sets errno on underflow to zero;
502 save the current errno value so that we can restore it later. */
503 saved_errno = errno;
504 result = p / q * x * exp(-x2) / sqrtpi;
505 errno = saved_errno;
506 return result;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000507}
508
509/* Error function erf(x), for general x */
510
511static double
512m_erf(double x)
513{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 double absx, cf;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 if (Py_IS_NAN(x))
517 return x;
518 absx = fabs(x);
519 if (absx < ERF_SERIES_CUTOFF)
520 return m_erf_series(x);
521 else {
522 cf = m_erfc_contfrac(absx);
523 return x > 0.0 ? 1.0 - cf : cf - 1.0;
524 }
Mark Dickinson45f992a2009-12-19 11:20:49 +0000525}
526
527/* Complementary error function erfc(x), for general x. */
528
529static double
530m_erfc(double x)
531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 double absx, cf;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 if (Py_IS_NAN(x))
535 return x;
536 absx = fabs(x);
537 if (absx < ERF_SERIES_CUTOFF)
538 return 1.0 - m_erf_series(x);
539 else {
540 cf = m_erfc_contfrac(absx);
541 return x > 0.0 ? cf : 2.0 - cf;
542 }
Mark Dickinson45f992a2009-12-19 11:20:49 +0000543}
Mark Dickinson05d2e082009-12-11 20:17:17 +0000544
545/*
Christian Heimese57950f2008-04-21 13:08:03 +0000546 wrapper for atan2 that deals directly with special cases before
547 delegating to the platform libm for the remaining cases. This
548 is necessary to get consistent behaviour across platforms.
549 Windows, FreeBSD and alpha Tru64 are amongst platforms that don't
550 always follow C99.
551*/
552
553static double
554m_atan2(double y, double x)
555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 if (Py_IS_NAN(x) || Py_IS_NAN(y))
557 return Py_NAN;
558 if (Py_IS_INFINITY(y)) {
559 if (Py_IS_INFINITY(x)) {
560 if (copysign(1., x) == 1.)
561 /* atan2(+-inf, +inf) == +-pi/4 */
562 return copysign(0.25*Py_MATH_PI, y);
563 else
564 /* atan2(+-inf, -inf) == +-pi*3/4 */
565 return copysign(0.75*Py_MATH_PI, y);
566 }
567 /* atan2(+-inf, x) == +-pi/2 for finite x */
568 return copysign(0.5*Py_MATH_PI, y);
569 }
570 if (Py_IS_INFINITY(x) || y == 0.) {
571 if (copysign(1., x) == 1.)
572 /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */
573 return copysign(0., y);
574 else
575 /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */
576 return copysign(Py_MATH_PI, y);
577 }
578 return atan2(y, x);
Christian Heimese57950f2008-04-21 13:08:03 +0000579}
580
581/*
Mark Dickinsone675f082008-12-11 21:56:00 +0000582 Various platforms (Solaris, OpenBSD) do nonstandard things for log(0),
583 log(-ve), log(NaN). Here are wrappers for log and log10 that deal with
584 special values directly, passing positive non-special values through to
585 the system log/log10.
586 */
587
588static double
589m_log(double x)
590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 if (Py_IS_FINITE(x)) {
592 if (x > 0.0)
593 return log(x);
594 errno = EDOM;
595 if (x == 0.0)
596 return -Py_HUGE_VAL; /* log(0) = -inf */
597 else
598 return Py_NAN; /* log(-ve) = nan */
599 }
600 else if (Py_IS_NAN(x))
601 return x; /* log(nan) = nan */
602 else if (x > 0.0)
603 return x; /* log(inf) = inf */
604 else {
605 errno = EDOM;
606 return Py_NAN; /* log(-inf) = nan */
607 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000608}
609
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200610/*
611 log2: log to base 2.
612
613 Uses an algorithm that should:
Mark Dickinson83b8c0b2011-05-09 08:40:20 +0100614
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200615 (a) produce exact results for powers of 2, and
Mark Dickinson83b8c0b2011-05-09 08:40:20 +0100616 (b) give a monotonic log2 (for positive finite floats),
617 assuming that the system log is monotonic.
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200618*/
619
620static double
621m_log2(double x)
622{
623 if (!Py_IS_FINITE(x)) {
624 if (Py_IS_NAN(x))
625 return x; /* log2(nan) = nan */
626 else if (x > 0.0)
627 return x; /* log2(+inf) = +inf */
628 else {
629 errno = EDOM;
630 return Py_NAN; /* log2(-inf) = nan, invalid-operation */
631 }
632 }
633
634 if (x > 0.0) {
Victor Stinner8f9f8d62011-05-09 12:45:41 +0200635#ifdef HAVE_LOG2
636 return log2(x);
637#else
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200638 double m;
639 int e;
640 m = frexp(x, &e);
641 /* We want log2(m * 2**e) == log(m) / log(2) + e. Care is needed when
642 * x is just greater than 1.0: in that case e is 1, log(m) is negative,
643 * and we get significant cancellation error from the addition of
644 * log(m) / log(2) to e. The slight rewrite of the expression below
645 * avoids this problem.
646 */
647 if (x >= 1.0) {
648 return log(2.0 * m) / log(2.0) + (e - 1);
649 }
650 else {
651 return log(m) / log(2.0) + e;
652 }
Victor Stinner8f9f8d62011-05-09 12:45:41 +0200653#endif
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200654 }
655 else if (x == 0.0) {
656 errno = EDOM;
657 return -Py_HUGE_VAL; /* log2(0) = -inf, divide-by-zero */
658 }
659 else {
660 errno = EDOM;
Mark Dickinson23442582011-05-09 08:05:00 +0100661 return Py_NAN; /* log2(-inf) = nan, invalid-operation */
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200662 }
663}
664
Mark Dickinsone675f082008-12-11 21:56:00 +0000665static double
666m_log10(double x)
667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 if (Py_IS_FINITE(x)) {
669 if (x > 0.0)
670 return log10(x);
671 errno = EDOM;
672 if (x == 0.0)
673 return -Py_HUGE_VAL; /* log10(0) = -inf */
674 else
675 return Py_NAN; /* log10(-ve) = nan */
676 }
677 else if (Py_IS_NAN(x))
678 return x; /* log10(nan) = nan */
679 else if (x > 0.0)
680 return x; /* log10(inf) = inf */
681 else {
682 errno = EDOM;
683 return Py_NAN; /* log10(-inf) = nan */
684 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000685}
686
687
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300688static PyObject *
689math_gcd(PyObject *self, PyObject *args)
690{
691 PyObject *a, *b, *g;
692
693 if (!PyArg_ParseTuple(args, "OO:gcd", &a, &b))
694 return NULL;
695
696 a = PyNumber_Index(a);
697 if (a == NULL)
698 return NULL;
699 b = PyNumber_Index(b);
700 if (b == NULL) {
701 Py_DECREF(a);
702 return NULL;
703 }
704 g = _PyLong_GCD(a, b);
705 Py_DECREF(a);
706 Py_DECREF(b);
707 return g;
708}
709
710PyDoc_STRVAR(math_gcd_doc,
711"gcd(x, y) -> int\n\
712greatest common divisor of x and y");
713
714
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000715/* Call is_error when errno != 0, and where x is the result libm
716 * returned. is_error will usually set up an exception and return
717 * true (1), but may return false (0) without setting up an exception.
718 */
719static int
720is_error(double x)
721{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 int result = 1; /* presumption of guilt */
723 assert(errno); /* non-zero errno is a precondition for calling */
724 if (errno == EDOM)
725 PyErr_SetString(PyExc_ValueError, "math domain error");
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 else if (errno == ERANGE) {
728 /* ANSI C generally requires libm functions to set ERANGE
729 * on overflow, but also generally *allows* them to set
730 * ERANGE on underflow too. There's no consistency about
731 * the latter across platforms.
732 * Alas, C99 never requires that errno be set.
733 * Here we suppress the underflow errors (libm functions
734 * should return a zero on underflow, and +- HUGE_VAL on
735 * overflow, so testing the result for zero suffices to
736 * distinguish the cases).
737 *
738 * On some platforms (Ubuntu/ia64) it seems that errno can be
739 * set to ERANGE for subnormal results that do *not* underflow
740 * to zero. So to be safe, we'll ignore ERANGE whenever the
741 * function result is less than one in absolute value.
742 */
743 if (fabs(x) < 1.0)
744 result = 0;
745 else
746 PyErr_SetString(PyExc_OverflowError,
747 "math range error");
748 }
749 else
750 /* Unexpected math error */
751 PyErr_SetFromErrno(PyExc_ValueError);
752 return result;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000753}
754
Mark Dickinsone675f082008-12-11 21:56:00 +0000755/*
Christian Heimes53876d92008-04-19 00:31:39 +0000756 math_1 is used to wrap a libm function f that takes a double
757 arguments and returns a double.
758
759 The error reporting follows these rules, which are designed to do
760 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
761 platforms.
762
763 - a NaN result from non-NaN inputs causes ValueError to be raised
764 - an infinite result from finite inputs causes OverflowError to be
765 raised if can_overflow is 1, or raises ValueError if can_overflow
766 is 0.
767 - if the result is finite and errno == EDOM then ValueError is
768 raised
769 - if the result is finite and nonzero and errno == ERANGE then
770 OverflowError is raised
771
772 The last rule is used to catch overflow on platforms which follow
773 C89 but for which HUGE_VAL is not an infinity.
774
775 For the majority of one-argument functions these rules are enough
776 to ensure that Python's functions behave as specified in 'Annex F'
777 of the C99 standard, with the 'invalid' and 'divide-by-zero'
778 floating-point exceptions mapping to Python's ValueError and the
779 'overflow' floating-point exception mapping to OverflowError.
780 math_1 only works for functions that don't have singularities *and*
781 the possibility of overflow; fortunately, that covers everything we
782 care about right now.
783*/
784
Barry Warsaw8b43b191996-12-09 22:32:36 +0000785static PyObject *
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000786math_1_to_whatever(PyObject *arg, double (*func) (double),
Christian Heimes53876d92008-04-19 00:31:39 +0000787 PyObject *(*from_double_func) (double),
788 int can_overflow)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000789{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 double x, r;
791 x = PyFloat_AsDouble(arg);
792 if (x == -1.0 && PyErr_Occurred())
793 return NULL;
794 errno = 0;
795 PyFPE_START_PROTECT("in math_1", return 0);
796 r = (*func)(x);
797 PyFPE_END_PROTECT(r);
798 if (Py_IS_NAN(r) && !Py_IS_NAN(x)) {
799 PyErr_SetString(PyExc_ValueError,
800 "math domain error"); /* invalid arg */
801 return NULL;
802 }
803 if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) {
Benjamin Peterson2354a752012-03-13 16:13:09 -0500804 if (can_overflow)
805 PyErr_SetString(PyExc_OverflowError,
806 "math range error"); /* overflow */
807 else
808 PyErr_SetString(PyExc_ValueError,
809 "math domain error"); /* singularity */
810 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 }
812 if (Py_IS_FINITE(r) && errno && is_error(r))
813 /* this branch unnecessary on most platforms */
814 return NULL;
Mark Dickinsonde429622008-05-01 00:19:23 +0000815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 return (*from_double_func)(r);
Christian Heimes53876d92008-04-19 00:31:39 +0000817}
818
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000819/* variant of math_1, to be used when the function being wrapped is known to
820 set errno properly (that is, errno = EDOM for invalid or divide-by-zero,
821 errno = ERANGE for overflow). */
822
823static PyObject *
824math_1a(PyObject *arg, double (*func) (double))
825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 double x, r;
827 x = PyFloat_AsDouble(arg);
828 if (x == -1.0 && PyErr_Occurred())
829 return NULL;
830 errno = 0;
831 PyFPE_START_PROTECT("in math_1a", return 0);
832 r = (*func)(x);
833 PyFPE_END_PROTECT(r);
834 if (errno && is_error(r))
835 return NULL;
836 return PyFloat_FromDouble(r);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000837}
838
Christian Heimes53876d92008-04-19 00:31:39 +0000839/*
840 math_2 is used to wrap a libm function f that takes two double
841 arguments and returns a double.
842
843 The error reporting follows these rules, which are designed to do
844 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
845 platforms.
846
847 - a NaN result from non-NaN inputs causes ValueError to be raised
848 - an infinite result from finite inputs causes OverflowError to be
849 raised.
850 - if the result is finite and errno == EDOM then ValueError is
851 raised
852 - if the result is finite and nonzero and errno == ERANGE then
853 OverflowError is raised
854
855 The last rule is used to catch overflow on platforms which follow
856 C89 but for which HUGE_VAL is not an infinity.
857
858 For most two-argument functions (copysign, fmod, hypot, atan2)
859 these rules are enough to ensure that Python's functions behave as
860 specified in 'Annex F' of the C99 standard, with the 'invalid' and
861 'divide-by-zero' floating-point exceptions mapping to Python's
862 ValueError and the 'overflow' floating-point exception mapping to
863 OverflowError.
864*/
865
866static PyObject *
867math_1(PyObject *arg, double (*func) (double), int can_overflow)
868{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow);
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000870}
871
872static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000873math_1_to_int(PyObject *arg, double (*func) (double), int can_overflow)
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000874{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 return math_1_to_whatever(arg, func, PyLong_FromDouble, can_overflow);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000876}
877
Barry Warsaw8b43b191996-12-09 22:32:36 +0000878static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +0000879math_2(PyObject *args, double (*func) (double, double), char *funcname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000880{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 PyObject *ox, *oy;
882 double x, y, r;
883 if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy))
884 return NULL;
885 x = PyFloat_AsDouble(ox);
886 y = PyFloat_AsDouble(oy);
887 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
888 return NULL;
889 errno = 0;
890 PyFPE_START_PROTECT("in math_2", return 0);
891 r = (*func)(x, y);
892 PyFPE_END_PROTECT(r);
893 if (Py_IS_NAN(r)) {
894 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
895 errno = EDOM;
896 else
897 errno = 0;
898 }
899 else if (Py_IS_INFINITY(r)) {
900 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
901 errno = ERANGE;
902 else
903 errno = 0;
904 }
905 if (errno && is_error(r))
906 return NULL;
907 else
908 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000909}
910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911#define FUNC1(funcname, func, can_overflow, docstring) \
912 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
913 return math_1(args, func, can_overflow); \
914 }\
915 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917#define FUNC1A(funcname, func, docstring) \
918 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
919 return math_1a(args, func); \
920 }\
921 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000922
Fred Drake40c48682000-07-03 18:11:56 +0000923#define FUNC2(funcname, func, docstring) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
925 return math_2(args, func, #funcname); \
926 }\
927 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000928
Christian Heimes53876d92008-04-19 00:31:39 +0000929FUNC1(acos, acos, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000930 "acos(x)\n\nReturn the arc cosine (measured in radians) of x.")
Mark Dickinsonf3718592009-12-21 15:27:41 +0000931FUNC1(acosh, m_acosh, 0,
Mark Dickinsondfe0b232015-01-11 13:08:05 +0000932 "acosh(x)\n\nReturn the inverse hyperbolic cosine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000933FUNC1(asin, asin, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000934 "asin(x)\n\nReturn the arc sine (measured in radians) of x.")
Mark Dickinsonf3718592009-12-21 15:27:41 +0000935FUNC1(asinh, m_asinh, 0,
Mark Dickinsondfe0b232015-01-11 13:08:05 +0000936 "asinh(x)\n\nReturn the inverse hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000937FUNC1(atan, atan, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000938 "atan(x)\n\nReturn the arc tangent (measured in radians) of x.")
Christian Heimese57950f2008-04-21 13:08:03 +0000939FUNC2(atan2, m_atan2,
Tim Petersfe71f812001-08-07 22:10:00 +0000940 "atan2(y, x)\n\nReturn the arc tangent (measured in radians) of y/x.\n"
941 "Unlike atan(y/x), the signs of both x and y are considered.")
Mark Dickinsonf3718592009-12-21 15:27:41 +0000942FUNC1(atanh, m_atanh, 0,
Mark Dickinsondfe0b232015-01-11 13:08:05 +0000943 "atanh(x)\n\nReturn the inverse hyperbolic tangent of x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +0000944
945static PyObject * math_ceil(PyObject *self, PyObject *number) {
Benjamin Petersonce798522012-01-22 11:24:29 -0500946 _Py_IDENTIFIER(__ceil__);
Mark Dickinson6d02d9c2010-07-02 16:05:15 +0000947 PyObject *method, *result;
Guido van Rossum13e05de2007-08-23 22:56:55 +0000948
Benjamin Petersonce798522012-01-22 11:24:29 -0500949 method = _PyObject_LookupSpecial(number, &PyId___ceil__);
Benjamin Petersonf751bc92010-07-02 13:46:42 +0000950 if (method == NULL) {
951 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 return math_1_to_int(number, ceil, 0);
Benjamin Petersonf751bc92010-07-02 13:46:42 +0000954 }
Mark Dickinson6d02d9c2010-07-02 16:05:15 +0000955 result = PyObject_CallFunctionObjArgs(method, NULL);
956 Py_DECREF(method);
957 return result;
Guido van Rossum13e05de2007-08-23 22:56:55 +0000958}
959
960PyDoc_STRVAR(math_ceil_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 "ceil(x)\n\nReturn the ceiling of x as an int.\n"
962 "This is the smallest integral value >= x.");
Guido van Rossum13e05de2007-08-23 22:56:55 +0000963
Christian Heimes072c0f12008-01-03 23:01:04 +0000964FUNC2(copysign, copysign,
Andrew Kuchling8cb1ec32014-02-16 11:11:25 -0500965 "copysign(x, y)\n\nReturn a float with the magnitude (absolute value) "
966 "of x but the sign \nof y. On platforms that support signed zeros, "
Andrew Kuchling31378852014-02-16 12:09:35 -0500967 "copysign(1.0, -0.0) \nreturns -1.0.\n")
Christian Heimes53876d92008-04-19 00:31:39 +0000968FUNC1(cos, cos, 0,
969 "cos(x)\n\nReturn the cosine of x (measured in radians).")
970FUNC1(cosh, cosh, 1,
971 "cosh(x)\n\nReturn the hyperbolic cosine of x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +0000972FUNC1A(erf, m_erf,
973 "erf(x)\n\nError function at x.")
974FUNC1A(erfc, m_erfc,
975 "erfc(x)\n\nComplementary error function at x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000976FUNC1(exp, exp, 1,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000977 "exp(x)\n\nReturn e raised to the power of x.")
Mark Dickinson664b5112009-12-16 20:23:42 +0000978FUNC1(expm1, m_expm1, 1,
979 "expm1(x)\n\nReturn exp(x)-1.\n"
980 "This function avoids the loss of precision involved in the direct "
981 "evaluation of exp(x)-1 for small x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000982FUNC1(fabs, fabs, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000983 "fabs(x)\n\nReturn the absolute value of the float x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +0000984
985static PyObject * math_floor(PyObject *self, PyObject *number) {
Benjamin Petersonce798522012-01-22 11:24:29 -0500986 _Py_IDENTIFIER(__floor__);
Benjamin Petersonb0125892010-07-02 13:35:17 +0000987 PyObject *method, *result;
Guido van Rossum13e05de2007-08-23 22:56:55 +0000988
Benjamin Petersonce798522012-01-22 11:24:29 -0500989 method = _PyObject_LookupSpecial(number, &PyId___floor__);
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +0000990 if (method == NULL) {
991 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 return math_1_to_int(number, floor, 0);
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +0000994 }
Benjamin Petersonb0125892010-07-02 13:35:17 +0000995 result = PyObject_CallFunctionObjArgs(method, NULL);
996 Py_DECREF(method);
997 return result;
Guido van Rossum13e05de2007-08-23 22:56:55 +0000998}
999
1000PyDoc_STRVAR(math_floor_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 "floor(x)\n\nReturn the floor of x as an int.\n"
1002 "This is the largest integral value <= x.");
Guido van Rossum13e05de2007-08-23 22:56:55 +00001003
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001004FUNC1A(gamma, m_tgamma,
1005 "gamma(x)\n\nGamma function at x.")
Mark Dickinson05d2e082009-12-11 20:17:17 +00001006FUNC1A(lgamma, m_lgamma,
1007 "lgamma(x)\n\nNatural logarithm of absolute value of Gamma function at x.")
Mark Dickinsonbe64d952010-07-07 16:21:29 +00001008FUNC1(log1p, m_log1p, 0,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001009 "log1p(x)\n\nReturn the natural logarithm of 1+x (base e).\n"
1010 "The result is computed in a way which is accurate for x near zero.")
Christian Heimes53876d92008-04-19 00:31:39 +00001011FUNC1(sin, sin, 0,
Tim Petersfe71f812001-08-07 22:10:00 +00001012 "sin(x)\n\nReturn the sine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001013FUNC1(sinh, sinh, 1,
Guido van Rossumc6e22901998-12-04 19:26:43 +00001014 "sinh(x)\n\nReturn the hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001015FUNC1(sqrt, sqrt, 0,
Guido van Rossumc6e22901998-12-04 19:26:43 +00001016 "sqrt(x)\n\nReturn the square root of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001017FUNC1(tan, tan, 0,
Tim Petersfe71f812001-08-07 22:10:00 +00001018 "tan(x)\n\nReturn the tangent of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001019FUNC1(tanh, tanh, 0,
Guido van Rossumc6e22901998-12-04 19:26:43 +00001020 "tanh(x)\n\nReturn the hyperbolic tangent of x.")
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001021
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001022/* Precision summation function as msum() by Raymond Hettinger in
1023 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
1024 enhanced with the exact partials sum and roundoff from Mark
1025 Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
1026 See those links for more details, proofs and other references.
1027
1028 Note 1: IEEE 754R floating point semantics are assumed,
1029 but the current implementation does not re-establish special
1030 value semantics across iterations (i.e. handling -Inf + Inf).
1031
1032 Note 2: No provision is made for intermediate overflow handling;
Georg Brandlf78e02b2008-06-10 17:40:04 +00001033 therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001034 sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
1035 overflow of the first partial sum.
1036
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001037 Note 3: The intermediate values lo, yr, and hi are declared volatile so
1038 aggressive compilers won't algebraically reduce lo to always be exactly 0.0.
Georg Brandlf78e02b2008-06-10 17:40:04 +00001039 Also, the volatile declaration forces the values to be stored in memory as
1040 regular doubles instead of extended long precision (80-bit) values. This
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001041 prevents double rounding because any addition or subtraction of two doubles
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 can be resolved exactly into double-sized hi and lo values. As long as the
Georg Brandlf78e02b2008-06-10 17:40:04 +00001043 hi value gets forced into a double before yr and lo are computed, the extra
1044 bits in downstream extended precision operations (x87 for example) will be
1045 exactly zero and therefore can be losslessly stored back into a double,
1046 thereby preventing double rounding.
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001047
1048 Note 4: A similar implementation is in Modules/cmathmodule.c.
1049 Be sure to update both when making changes.
1050
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001051 Note 5: The signature of math.fsum() differs from builtins.sum()
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001052 because the start argument doesn't make sense in the context of
1053 accurate summation. Since the partials table is collapsed before
1054 returning a result, sum(seq2, start=sum(seq1)) may not equal the
1055 accurate result returned by sum(itertools.chain(seq1, seq2)).
1056*/
1057
1058#define NUM_PARTIALS 32 /* initial partials array size, on stack */
1059
1060/* Extend the partials array p[] by doubling its size. */
1061static int /* non-zero on error */
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001062_fsum_realloc(double **p_ptr, Py_ssize_t n,
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001063 double *ps, Py_ssize_t *m_ptr)
1064{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 void *v = NULL;
1066 Py_ssize_t m = *m_ptr;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 m += m; /* double */
Victor Stinner049e5092014-08-17 22:20:00 +02001069 if (n < m && (size_t)m < ((size_t)PY_SSIZE_T_MAX / sizeof(double))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 double *p = *p_ptr;
1071 if (p == ps) {
1072 v = PyMem_Malloc(sizeof(double) * m);
1073 if (v != NULL)
1074 memcpy(v, ps, sizeof(double) * n);
1075 }
1076 else
1077 v = PyMem_Realloc(p, sizeof(double) * m);
1078 }
1079 if (v == NULL) { /* size overflow or no memory */
1080 PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
1081 return 1;
1082 }
1083 *p_ptr = (double*) v;
1084 *m_ptr = m;
1085 return 0;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001086}
1087
1088/* Full precision summation of a sequence of floats.
1089
1090 def msum(iterable):
1091 partials = [] # sorted, non-overlapping partial sums
1092 for x in iterable:
Mark Dickinsonfdb0acc2010-06-25 20:22:24 +00001093 i = 0
1094 for y in partials:
1095 if abs(x) < abs(y):
1096 x, y = y, x
1097 hi = x + y
1098 lo = y - (hi - x)
1099 if lo:
1100 partials[i] = lo
1101 i += 1
1102 x = hi
1103 partials[i:] = [x]
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001104 return sum_exact(partials)
1105
1106 Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
1107 are exactly equal to x+y. The inner loop applies hi/lo summation to each
1108 partial so that the list of partial sums remains exact.
1109
1110 Sum_exact() adds the partial sums exactly and correctly rounds the final
1111 result (using the round-half-to-even rule). The items in partials remain
1112 non-zero, non-special, non-overlapping and strictly increasing in
1113 magnitude, but possibly not all having the same sign.
1114
1115 Depends on IEEE 754 arithmetic guarantees and half-even rounding.
1116*/
1117
1118static PyObject*
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001119math_fsum(PyObject *self, PyObject *seq)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001120{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 PyObject *item, *iter, *sum = NULL;
1122 Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
1123 double x, y, t, ps[NUM_PARTIALS], *p = ps;
1124 double xsave, special_sum = 0.0, inf_sum = 0.0;
1125 volatile double hi, yr, lo;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 iter = PyObject_GetIter(seq);
1128 if (iter == NULL)
1129 return NULL;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 for(;;) { /* for x in iterable */
1134 assert(0 <= n && n <= m);
1135 assert((m == NUM_PARTIALS && p == ps) ||
1136 (m > NUM_PARTIALS && p != NULL));
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 item = PyIter_Next(iter);
1139 if (item == NULL) {
1140 if (PyErr_Occurred())
1141 goto _fsum_error;
1142 break;
1143 }
1144 x = PyFloat_AsDouble(item);
1145 Py_DECREF(item);
1146 if (PyErr_Occurred())
1147 goto _fsum_error;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 xsave = x;
1150 for (i = j = 0; j < n; j++) { /* for y in partials */
1151 y = p[j];
1152 if (fabs(x) < fabs(y)) {
1153 t = x; x = y; y = t;
1154 }
1155 hi = x + y;
1156 yr = hi - x;
1157 lo = y - yr;
1158 if (lo != 0.0)
1159 p[i++] = lo;
1160 x = hi;
1161 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 n = i; /* ps[i:] = [x] */
1164 if (x != 0.0) {
1165 if (! Py_IS_FINITE(x)) {
1166 /* a nonfinite x could arise either as
1167 a result of intermediate overflow, or
1168 as a result of a nan or inf in the
1169 summands */
1170 if (Py_IS_FINITE(xsave)) {
1171 PyErr_SetString(PyExc_OverflowError,
1172 "intermediate overflow in fsum");
1173 goto _fsum_error;
1174 }
1175 if (Py_IS_INFINITY(xsave))
1176 inf_sum += xsave;
1177 special_sum += xsave;
1178 /* reset partials */
1179 n = 0;
1180 }
1181 else if (n >= m && _fsum_realloc(&p, n, ps, &m))
1182 goto _fsum_error;
1183 else
1184 p[n++] = x;
1185 }
1186 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 if (special_sum != 0.0) {
1189 if (Py_IS_NAN(inf_sum))
1190 PyErr_SetString(PyExc_ValueError,
1191 "-inf + inf in fsum");
1192 else
1193 sum = PyFloat_FromDouble(special_sum);
1194 goto _fsum_error;
1195 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 hi = 0.0;
1198 if (n > 0) {
1199 hi = p[--n];
1200 /* sum_exact(ps, hi) from the top, stop when the sum becomes
1201 inexact. */
1202 while (n > 0) {
1203 x = hi;
1204 y = p[--n];
1205 assert(fabs(y) < fabs(x));
1206 hi = x + y;
1207 yr = hi - x;
1208 lo = y - yr;
1209 if (lo != 0.0)
1210 break;
1211 }
1212 /* Make half-even rounding work across multiple partials.
1213 Needed so that sum([1e-16, 1, 1e16]) will round-up the last
1214 digit to two instead of down to zero (the 1e-16 makes the 1
1215 slightly closer to two). With a potential 1 ULP rounding
1216 error fixed-up, math.fsum() can guarantee commutativity. */
1217 if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
1218 (lo > 0.0 && p[n-1] > 0.0))) {
1219 y = lo * 2.0;
1220 x = hi + y;
1221 yr = x - hi;
1222 if (y == yr)
1223 hi = x;
1224 }
1225 }
1226 sum = PyFloat_FromDouble(hi);
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001227
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001228_fsum_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 PyFPE_END_PROTECT(hi)
1230 Py_DECREF(iter);
1231 if (p != ps)
1232 PyMem_Free(p);
1233 return sum;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001234}
1235
1236#undef NUM_PARTIALS
1237
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001238PyDoc_STRVAR(math_fsum_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001239"fsum(iterable)\n\n\
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001240Return an accurate floating point sum of values in the iterable.\n\
1241Assumes IEEE-754 floating point arithmetic.");
1242
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001243/* Return the smallest integer k such that n < 2**k, or 0 if n == 0.
1244 * Equivalent to floor(lg(x))+1. Also equivalent to: bitwidth_of_type -
1245 * count_leading_zero_bits(x)
1246 */
1247
1248/* XXX: This routine does more or less the same thing as
1249 * bits_in_digit() in Objects/longobject.c. Someday it would be nice to
1250 * consolidate them. On BSD, there's a library function called fls()
1251 * that we could use, and GCC provides __builtin_clz().
1252 */
1253
1254static unsigned long
1255bit_length(unsigned long n)
1256{
1257 unsigned long len = 0;
1258 while (n != 0) {
1259 ++len;
1260 n >>= 1;
1261 }
1262 return len;
1263}
1264
1265static unsigned long
1266count_set_bits(unsigned long n)
1267{
1268 unsigned long count = 0;
1269 while (n != 0) {
1270 ++count;
1271 n &= n - 1; /* clear least significant bit */
1272 }
1273 return count;
1274}
1275
1276/* Divide-and-conquer factorial algorithm
1277 *
1278 * Based on the formula and psuedo-code provided at:
1279 * http://www.luschny.de/math/factorial/binarysplitfact.html
1280 *
1281 * Faster algorithms exist, but they're more complicated and depend on
Ezio Melotti9527afd2010-07-08 15:03:02 +00001282 * a fast prime factorization algorithm.
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001283 *
1284 * Notes on the algorithm
1285 * ----------------------
1286 *
1287 * factorial(n) is written in the form 2**k * m, with m odd. k and m are
1288 * computed separately, and then combined using a left shift.
1289 *
1290 * The function factorial_odd_part computes the odd part m (i.e., the greatest
1291 * odd divisor) of factorial(n), using the formula:
1292 *
1293 * factorial_odd_part(n) =
1294 *
1295 * product_{i >= 0} product_{0 < j <= n / 2**i, j odd} j
1296 *
1297 * Example: factorial_odd_part(20) =
1298 *
1299 * (1) *
1300 * (1) *
1301 * (1 * 3 * 5) *
1302 * (1 * 3 * 5 * 7 * 9)
1303 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1304 *
1305 * Here i goes from large to small: the first term corresponds to i=4 (any
1306 * larger i gives an empty product), and the last term corresponds to i=0.
1307 * Each term can be computed from the last by multiplying by the extra odd
1308 * numbers required: e.g., to get from the penultimate term to the last one,
1309 * we multiply by (11 * 13 * 15 * 17 * 19).
1310 *
1311 * To see a hint of why this formula works, here are the same numbers as above
1312 * but with the even parts (i.e., the appropriate powers of 2) included. For
1313 * each subterm in the product for i, we multiply that subterm by 2**i:
1314 *
1315 * factorial(20) =
1316 *
1317 * (16) *
1318 * (8) *
1319 * (4 * 12 * 20) *
1320 * (2 * 6 * 10 * 14 * 18) *
1321 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1322 *
1323 * The factorial_partial_product function computes the product of all odd j in
1324 * range(start, stop) for given start and stop. It's used to compute the
1325 * partial products like (11 * 13 * 15 * 17 * 19) in the example above. It
1326 * operates recursively, repeatedly splitting the range into two roughly equal
1327 * pieces until the subranges are small enough to be computed using only C
1328 * integer arithmetic.
1329 *
1330 * The two-valuation k (i.e., the exponent of the largest power of 2 dividing
1331 * the factorial) is computed independently in the main math_factorial
1332 * function. By standard results, its value is:
1333 *
1334 * two_valuation = n//2 + n//4 + n//8 + ....
1335 *
1336 * It can be shown (e.g., by complete induction on n) that two_valuation is
1337 * equal to n - count_set_bits(n), where count_set_bits(n) gives the number of
1338 * '1'-bits in the binary expansion of n.
1339 */
1340
1341/* factorial_partial_product: Compute product(range(start, stop, 2)) using
1342 * divide and conquer. Assumes start and stop are odd and stop > start.
1343 * max_bits must be >= bit_length(stop - 2). */
1344
1345static PyObject *
1346factorial_partial_product(unsigned long start, unsigned long stop,
1347 unsigned long max_bits)
1348{
1349 unsigned long midpoint, num_operands;
1350 PyObject *left = NULL, *right = NULL, *result = NULL;
1351
1352 /* If the return value will fit an unsigned long, then we can
1353 * multiply in a tight, fast loop where each multiply is O(1).
1354 * Compute an upper bound on the number of bits required to store
1355 * the answer.
1356 *
1357 * Storing some integer z requires floor(lg(z))+1 bits, which is
1358 * conveniently the value returned by bit_length(z). The
1359 * product x*y will require at most
1360 * bit_length(x) + bit_length(y) bits to store, based
1361 * on the idea that lg product = lg x + lg y.
1362 *
1363 * We know that stop - 2 is the largest number to be multiplied. From
1364 * there, we have: bit_length(answer) <= num_operands *
1365 * bit_length(stop - 2)
1366 */
1367
1368 num_operands = (stop - start) / 2;
1369 /* The "num_operands <= 8 * SIZEOF_LONG" check guards against the
1370 * unlikely case of an overflow in num_operands * max_bits. */
1371 if (num_operands <= 8 * SIZEOF_LONG &&
1372 num_operands * max_bits <= 8 * SIZEOF_LONG) {
1373 unsigned long j, total;
1374 for (total = start, j = start + 2; j < stop; j += 2)
1375 total *= j;
1376 return PyLong_FromUnsignedLong(total);
1377 }
1378
1379 /* find midpoint of range(start, stop), rounded up to next odd number. */
1380 midpoint = (start + num_operands) | 1;
1381 left = factorial_partial_product(start, midpoint,
1382 bit_length(midpoint - 2));
1383 if (left == NULL)
1384 goto error;
1385 right = factorial_partial_product(midpoint, stop, max_bits);
1386 if (right == NULL)
1387 goto error;
1388 result = PyNumber_Multiply(left, right);
1389
1390 error:
1391 Py_XDECREF(left);
1392 Py_XDECREF(right);
1393 return result;
1394}
1395
1396/* factorial_odd_part: compute the odd part of factorial(n). */
1397
1398static PyObject *
1399factorial_odd_part(unsigned long n)
1400{
1401 long i;
1402 unsigned long v, lower, upper;
1403 PyObject *partial, *tmp, *inner, *outer;
1404
1405 inner = PyLong_FromLong(1);
1406 if (inner == NULL)
1407 return NULL;
1408 outer = inner;
1409 Py_INCREF(outer);
1410
1411 upper = 3;
1412 for (i = bit_length(n) - 2; i >= 0; i--) {
1413 v = n >> i;
1414 if (v <= 2)
1415 continue;
1416 lower = upper;
1417 /* (v + 1) | 1 = least odd integer strictly larger than n / 2**i */
1418 upper = (v + 1) | 1;
1419 /* Here inner is the product of all odd integers j in the range (0,
1420 n/2**(i+1)]. The factorial_partial_product call below gives the
1421 product of all odd integers j in the range (n/2**(i+1), n/2**i]. */
1422 partial = factorial_partial_product(lower, upper, bit_length(upper-2));
1423 /* inner *= partial */
1424 if (partial == NULL)
1425 goto error;
1426 tmp = PyNumber_Multiply(inner, partial);
1427 Py_DECREF(partial);
1428 if (tmp == NULL)
1429 goto error;
1430 Py_DECREF(inner);
1431 inner = tmp;
1432 /* Now inner is the product of all odd integers j in the range (0,
1433 n/2**i], giving the inner product in the formula above. */
1434
1435 /* outer *= inner; */
1436 tmp = PyNumber_Multiply(outer, inner);
1437 if (tmp == NULL)
1438 goto error;
1439 Py_DECREF(outer);
1440 outer = tmp;
1441 }
Mark Dickinson76464492012-10-25 10:46:28 +01001442 Py_DECREF(inner);
1443 return outer;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001444
1445 error:
1446 Py_DECREF(outer);
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001447 Py_DECREF(inner);
Mark Dickinson76464492012-10-25 10:46:28 +01001448 return NULL;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001449}
1450
1451/* Lookup table for small factorial values */
1452
1453static const unsigned long SmallFactorials[] = {
1454 1, 1, 2, 6, 24, 120, 720, 5040, 40320,
1455 362880, 3628800, 39916800, 479001600,
1456#if SIZEOF_LONG >= 8
1457 6227020800, 87178291200, 1307674368000,
1458 20922789888000, 355687428096000, 6402373705728000,
1459 121645100408832000, 2432902008176640000
1460#endif
1461};
1462
Barry Warsaw8b43b191996-12-09 22:32:36 +00001463static PyObject *
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001464math_factorial(PyObject *self, PyObject *arg)
1465{
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001466 long x;
Mark Dickinson5990d282014-04-10 09:29:39 -04001467 int overflow;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001468 PyObject *result, *odd_part, *two_valuation;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 if (PyFloat_Check(arg)) {
1471 PyObject *lx;
1472 double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
1473 if (!(Py_IS_FINITE(dx) && dx == floor(dx))) {
1474 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001475 "factorial() only accepts integral values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 return NULL;
1477 }
1478 lx = PyLong_FromDouble(dx);
1479 if (lx == NULL)
1480 return NULL;
Mark Dickinson5990d282014-04-10 09:29:39 -04001481 x = PyLong_AsLongAndOverflow(lx, &overflow);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 Py_DECREF(lx);
1483 }
1484 else
Mark Dickinson5990d282014-04-10 09:29:39 -04001485 x = PyLong_AsLongAndOverflow(arg, &overflow);
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001486
Mark Dickinson5990d282014-04-10 09:29:39 -04001487 if (x == -1 && PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 return NULL;
Mark Dickinson5990d282014-04-10 09:29:39 -04001489 }
1490 else if (overflow == 1) {
1491 PyErr_Format(PyExc_OverflowError,
1492 "factorial() argument should not exceed %ld",
1493 LONG_MAX);
1494 return NULL;
1495 }
1496 else if (overflow == -1 || x < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001498 "factorial() not defined for negative values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 return NULL;
1500 }
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001501
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001502 /* use lookup table if x is small */
Victor Stinner63941882011-09-29 00:42:28 +02001503 if (x < (long)Py_ARRAY_LENGTH(SmallFactorials))
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001504 return PyLong_FromUnsignedLong(SmallFactorials[x]);
1505
1506 /* else express in the form odd_part * 2**two_valuation, and compute as
1507 odd_part << two_valuation. */
1508 odd_part = factorial_odd_part(x);
1509 if (odd_part == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 return NULL;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001511 two_valuation = PyLong_FromLong(x - count_set_bits(x));
1512 if (two_valuation == NULL) {
1513 Py_DECREF(odd_part);
1514 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 }
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001516 result = PyNumber_Lshift(odd_part, two_valuation);
1517 Py_DECREF(two_valuation);
1518 Py_DECREF(odd_part);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 return result;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001520}
1521
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001522PyDoc_STRVAR(math_factorial_doc,
1523"factorial(x) -> Integral\n"
1524"\n"
1525"Find x!. Raise a ValueError if x is negative or non-integral.");
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001526
1527static PyObject *
Christian Heimes400adb02008-02-01 08:12:03 +00001528math_trunc(PyObject *self, PyObject *number)
1529{
Benjamin Petersonce798522012-01-22 11:24:29 -05001530 _Py_IDENTIFIER(__trunc__);
Benjamin Petersonb0125892010-07-02 13:35:17 +00001531 PyObject *trunc, *result;
Christian Heimes400adb02008-02-01 08:12:03 +00001532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 if (Py_TYPE(number)->tp_dict == NULL) {
1534 if (PyType_Ready(Py_TYPE(number)) < 0)
1535 return NULL;
1536 }
Christian Heimes400adb02008-02-01 08:12:03 +00001537
Benjamin Petersonce798522012-01-22 11:24:29 -05001538 trunc = _PyObject_LookupSpecial(number, &PyId___trunc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 if (trunc == NULL) {
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001540 if (!PyErr_Occurred())
1541 PyErr_Format(PyExc_TypeError,
1542 "type %.100s doesn't define __trunc__ method",
1543 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 return NULL;
1545 }
Benjamin Petersonb0125892010-07-02 13:35:17 +00001546 result = PyObject_CallFunctionObjArgs(trunc, NULL);
1547 Py_DECREF(trunc);
1548 return result;
Christian Heimes400adb02008-02-01 08:12:03 +00001549}
1550
1551PyDoc_STRVAR(math_trunc_doc,
1552"trunc(x:Real) -> Integral\n"
1553"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001554"Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.");
Christian Heimes400adb02008-02-01 08:12:03 +00001555
1556static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001557math_frexp(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 int i;
1560 double x = PyFloat_AsDouble(arg);
1561 if (x == -1.0 && PyErr_Occurred())
1562 return NULL;
1563 /* deal with special cases directly, to sidestep platform
1564 differences */
1565 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
1566 i = 0;
1567 }
1568 else {
1569 PyFPE_START_PROTECT("in math_frexp", return 0);
1570 x = frexp(x, &i);
1571 PyFPE_END_PROTECT(x);
1572 }
1573 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001574}
1575
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001576PyDoc_STRVAR(math_frexp_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001577"frexp(x)\n"
1578"\n"
1579"Return the mantissa and exponent of x, as pair (m, e).\n"
1580"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 +00001581"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 +00001582
Barry Warsaw8b43b191996-12-09 22:32:36 +00001583static PyObject *
Fred Drake40c48682000-07-03 18:11:56 +00001584math_ldexp(PyObject *self, PyObject *args)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 double x, r;
1587 PyObject *oexp;
1588 long exp;
1589 int overflow;
1590 if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp))
1591 return NULL;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 if (PyLong_Check(oexp)) {
1594 /* on overflow, replace exponent with either LONG_MAX
1595 or LONG_MIN, depending on the sign. */
1596 exp = PyLong_AsLongAndOverflow(oexp, &overflow);
1597 if (exp == -1 && PyErr_Occurred())
1598 return NULL;
1599 if (overflow)
1600 exp = overflow < 0 ? LONG_MIN : LONG_MAX;
1601 }
1602 else {
1603 PyErr_SetString(PyExc_TypeError,
Serhiy Storchaka95949422013-08-27 19:40:23 +03001604 "Expected an int as second argument to ldexp.");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 return NULL;
1606 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 if (x == 0. || !Py_IS_FINITE(x)) {
1609 /* NaNs, zeros and infinities are returned unchanged */
1610 r = x;
1611 errno = 0;
1612 } else if (exp > INT_MAX) {
1613 /* overflow */
1614 r = copysign(Py_HUGE_VAL, x);
1615 errno = ERANGE;
1616 } else if (exp < INT_MIN) {
1617 /* underflow to +-0 */
1618 r = copysign(0., x);
1619 errno = 0;
1620 } else {
1621 errno = 0;
1622 PyFPE_START_PROTECT("in math_ldexp", return 0);
1623 r = ldexp(x, (int)exp);
1624 PyFPE_END_PROTECT(r);
1625 if (Py_IS_INFINITY(r))
1626 errno = ERANGE;
1627 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 if (errno && is_error(r))
1630 return NULL;
1631 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001632}
1633
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001634PyDoc_STRVAR(math_ldexp_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001635"ldexp(x, i)\n\n\
1636Return x * (2**i).");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001637
Barry Warsaw8b43b191996-12-09 22:32:36 +00001638static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001639math_modf(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 double y, x = PyFloat_AsDouble(arg);
1642 if (x == -1.0 && PyErr_Occurred())
1643 return NULL;
1644 /* some platforms don't do the right thing for NaNs and
1645 infinities, so we take care of special cases directly. */
1646 if (!Py_IS_FINITE(x)) {
1647 if (Py_IS_INFINITY(x))
1648 return Py_BuildValue("(dd)", copysign(0., x), x);
1649 else if (Py_IS_NAN(x))
1650 return Py_BuildValue("(dd)", x, x);
1651 }
Christian Heimesa342c012008-04-20 21:01:16 +00001652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 errno = 0;
1654 PyFPE_START_PROTECT("in math_modf", return 0);
1655 x = modf(x, &y);
1656 PyFPE_END_PROTECT(x);
1657 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001658}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001659
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001660PyDoc_STRVAR(math_modf_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001661"modf(x)\n"
1662"\n"
1663"Return the fractional and integer parts of x. Both results carry the sign\n"
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001664"of x and are floats.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001665
Serhiy Storchaka95949422013-08-27 19:40:23 +03001666/* A decent logarithm is easy to compute even for huge ints, but libm can't
Tim Peters78526162001-09-05 00:53:45 +00001667 do that by itself -- loghelper can. func is log or log10, and name is
Serhiy Storchaka95949422013-08-27 19:40:23 +03001668 "log" or "log10". Note that overflow of the result isn't possible: an int
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00001669 can contain no more than INT_MAX * SHIFT bits, so has value certainly less
1670 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 +00001671 small enough to fit in an IEEE single. log and log10 are even smaller.
Serhiy Storchaka95949422013-08-27 19:40:23 +03001672 However, intermediate overflow is possible for an int if the number of bits
1673 in that int is larger than PY_SSIZE_T_MAX. */
Tim Peters78526162001-09-05 00:53:45 +00001674
1675static PyObject*
Thomas Wouters89f507f2006-12-13 04:49:30 +00001676loghelper(PyObject* arg, double (*func)(double), char *funcname)
Tim Peters78526162001-09-05 00:53:45 +00001677{
Serhiy Storchaka95949422013-08-27 19:40:23 +03001678 /* If it is int, do it ourselves. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 if (PyLong_Check(arg)) {
Mark Dickinsonc6037172010-09-29 19:06:36 +00001680 double x, result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 Py_ssize_t e;
Mark Dickinsonc6037172010-09-29 19:06:36 +00001682
1683 /* Negative or zero inputs give a ValueError. */
1684 if (Py_SIZE(arg) <= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 PyErr_SetString(PyExc_ValueError,
1686 "math domain error");
1687 return NULL;
1688 }
Mark Dickinsonfa41e602010-09-28 07:22:27 +00001689
Mark Dickinsonc6037172010-09-29 19:06:36 +00001690 x = PyLong_AsDouble(arg);
1691 if (x == -1.0 && PyErr_Occurred()) {
1692 if (!PyErr_ExceptionMatches(PyExc_OverflowError))
1693 return NULL;
1694 /* Here the conversion to double overflowed, but it's possible
1695 to compute the log anyway. Clear the exception and continue. */
1696 PyErr_Clear();
1697 x = _PyLong_Frexp((PyLongObject *)arg, &e);
1698 if (x == -1.0 && PyErr_Occurred())
1699 return NULL;
1700 /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */
1701 result = func(x) + func(2.0) * e;
1702 }
1703 else
1704 /* Successfully converted x to a double. */
1705 result = func(x);
1706 return PyFloat_FromDouble(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 }
Tim Peters78526162001-09-05 00:53:45 +00001708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 /* Else let libm handle it by itself. */
1710 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +00001711}
1712
1713static PyObject *
1714math_log(PyObject *self, PyObject *args)
1715{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 PyObject *arg;
1717 PyObject *base = NULL;
1718 PyObject *num, *den;
1719 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base))
1722 return NULL;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 num = loghelper(arg, m_log, "log");
1725 if (num == NULL || base == NULL)
1726 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 den = loghelper(base, m_log, "log");
1729 if (den == NULL) {
1730 Py_DECREF(num);
1731 return NULL;
1732 }
Raymond Hettinger866964c2002-12-14 19:51:34 +00001733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 ans = PyNumber_TrueDivide(num, den);
1735 Py_DECREF(num);
1736 Py_DECREF(den);
1737 return ans;
Tim Peters78526162001-09-05 00:53:45 +00001738}
1739
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001740PyDoc_STRVAR(math_log_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001741"log(x[, base])\n\n\
1742Return the logarithm of x to the given base.\n\
Raymond Hettinger866964c2002-12-14 19:51:34 +00001743If the base not specified, returns the natural logarithm (base e) of x.");
Tim Peters78526162001-09-05 00:53:45 +00001744
1745static PyObject *
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001746math_log2(PyObject *self, PyObject *arg)
1747{
1748 return loghelper(arg, m_log2, "log2");
1749}
1750
1751PyDoc_STRVAR(math_log2_doc,
1752"log2(x)\n\nReturn the base 2 logarithm of x.");
1753
1754static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001755math_log10(PyObject *self, PyObject *arg)
Tim Peters78526162001-09-05 00:53:45 +00001756{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 return loghelper(arg, m_log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +00001758}
1759
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001760PyDoc_STRVAR(math_log10_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001761"log10(x)\n\nReturn the base 10 logarithm of x.");
Tim Peters78526162001-09-05 00:53:45 +00001762
Christian Heimes53876d92008-04-19 00:31:39 +00001763static PyObject *
1764math_fmod(PyObject *self, PyObject *args)
1765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 PyObject *ox, *oy;
1767 double r, x, y;
1768 if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy))
1769 return NULL;
1770 x = PyFloat_AsDouble(ox);
1771 y = PyFloat_AsDouble(oy);
1772 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1773 return NULL;
1774 /* fmod(x, +/-Inf) returns x for finite x. */
1775 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
1776 return PyFloat_FromDouble(x);
1777 errno = 0;
1778 PyFPE_START_PROTECT("in math_fmod", return 0);
1779 r = fmod(x, y);
1780 PyFPE_END_PROTECT(r);
1781 if (Py_IS_NAN(r)) {
1782 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1783 errno = EDOM;
1784 else
1785 errno = 0;
1786 }
1787 if (errno && is_error(r))
1788 return NULL;
1789 else
1790 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00001791}
1792
1793PyDoc_STRVAR(math_fmod_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001794"fmod(x, y)\n\nReturn fmod(x, y), according to platform C."
Christian Heimes53876d92008-04-19 00:31:39 +00001795" x % y may differ.");
1796
1797static PyObject *
1798math_hypot(PyObject *self, PyObject *args)
1799{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 PyObject *ox, *oy;
1801 double r, x, y;
1802 if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy))
1803 return NULL;
1804 x = PyFloat_AsDouble(ox);
1805 y = PyFloat_AsDouble(oy);
1806 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1807 return NULL;
1808 /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */
1809 if (Py_IS_INFINITY(x))
1810 return PyFloat_FromDouble(fabs(x));
1811 if (Py_IS_INFINITY(y))
1812 return PyFloat_FromDouble(fabs(y));
1813 errno = 0;
1814 PyFPE_START_PROTECT("in math_hypot", return 0);
1815 r = hypot(x, y);
1816 PyFPE_END_PROTECT(r);
1817 if (Py_IS_NAN(r)) {
1818 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1819 errno = EDOM;
1820 else
1821 errno = 0;
1822 }
1823 else if (Py_IS_INFINITY(r)) {
1824 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
1825 errno = ERANGE;
1826 else
1827 errno = 0;
1828 }
1829 if (errno && is_error(r))
1830 return NULL;
1831 else
1832 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00001833}
1834
1835PyDoc_STRVAR(math_hypot_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001836"hypot(x, y)\n\nReturn the Euclidean distance, sqrt(x*x + y*y).");
Christian Heimes53876d92008-04-19 00:31:39 +00001837
1838/* pow can't use math_2, but needs its own wrapper: the problem is
1839 that an infinite result can arise either as a result of overflow
1840 (in which case OverflowError should be raised) or as a result of
1841 e.g. 0.**-5. (for which ValueError needs to be raised.)
1842*/
1843
1844static PyObject *
1845math_pow(PyObject *self, PyObject *args)
1846{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 PyObject *ox, *oy;
1848 double r, x, y;
1849 int odd_y;
Christian Heimes53876d92008-04-19 00:31:39 +00001850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy))
1852 return NULL;
1853 x = PyFloat_AsDouble(ox);
1854 y = PyFloat_AsDouble(oy);
1855 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1856 return NULL;
Christian Heimesa342c012008-04-20 21:01:16 +00001857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 /* deal directly with IEEE specials, to cope with problems on various
1859 platforms whose semantics don't exactly match C99 */
1860 r = 0.; /* silence compiler warning */
1861 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
1862 errno = 0;
1863 if (Py_IS_NAN(x))
1864 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
1865 else if (Py_IS_NAN(y))
1866 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
1867 else if (Py_IS_INFINITY(x)) {
1868 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
1869 if (y > 0.)
1870 r = odd_y ? x : fabs(x);
1871 else if (y == 0.)
1872 r = 1.;
1873 else /* y < 0. */
1874 r = odd_y ? copysign(0., x) : 0.;
1875 }
1876 else if (Py_IS_INFINITY(y)) {
1877 if (fabs(x) == 1.0)
1878 r = 1.;
1879 else if (y > 0. && fabs(x) > 1.0)
1880 r = y;
1881 else if (y < 0. && fabs(x) < 1.0) {
1882 r = -y; /* result is +inf */
1883 if (x == 0.) /* 0**-inf: divide-by-zero */
1884 errno = EDOM;
1885 }
1886 else
1887 r = 0.;
1888 }
1889 }
1890 else {
1891 /* let libm handle finite**finite */
1892 errno = 0;
1893 PyFPE_START_PROTECT("in math_pow", return 0);
1894 r = pow(x, y);
1895 PyFPE_END_PROTECT(r);
1896 /* a NaN result should arise only from (-ve)**(finite
1897 non-integer); in this case we want to raise ValueError. */
1898 if (!Py_IS_FINITE(r)) {
1899 if (Py_IS_NAN(r)) {
1900 errno = EDOM;
1901 }
1902 /*
1903 an infinite result here arises either from:
1904 (A) (+/-0.)**negative (-> divide-by-zero)
1905 (B) overflow of x**y with x and y finite
1906 */
1907 else if (Py_IS_INFINITY(r)) {
1908 if (x == 0.)
1909 errno = EDOM;
1910 else
1911 errno = ERANGE;
1912 }
1913 }
1914 }
Christian Heimes53876d92008-04-19 00:31:39 +00001915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 if (errno && is_error(r))
1917 return NULL;
1918 else
1919 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00001920}
1921
1922PyDoc_STRVAR(math_pow_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001923"pow(x, y)\n\nReturn x**y (x to the power of y).");
Christian Heimes53876d92008-04-19 00:31:39 +00001924
Christian Heimes072c0f12008-01-03 23:01:04 +00001925static const double degToRad = Py_MATH_PI / 180.0;
1926static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001927
1928static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001929math_degrees(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001930{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 double x = PyFloat_AsDouble(arg);
1932 if (x == -1.0 && PyErr_Occurred())
1933 return NULL;
1934 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001935}
1936
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001937PyDoc_STRVAR(math_degrees_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001938"degrees(x)\n\n\
1939Convert angle x from radians to degrees.");
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001940
1941static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001942math_radians(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001943{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 double x = PyFloat_AsDouble(arg);
1945 if (x == -1.0 && PyErr_Occurred())
1946 return NULL;
1947 return PyFloat_FromDouble(x * degToRad);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001948}
1949
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001950PyDoc_STRVAR(math_radians_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001951"radians(x)\n\n\
1952Convert angle x from degrees to radians.");
Tim Peters78526162001-09-05 00:53:45 +00001953
Christian Heimes072c0f12008-01-03 23:01:04 +00001954static PyObject *
Mark Dickinson8e0c9962010-07-11 17:38:24 +00001955math_isfinite(PyObject *self, PyObject *arg)
1956{
1957 double x = PyFloat_AsDouble(arg);
1958 if (x == -1.0 && PyErr_Occurred())
1959 return NULL;
1960 return PyBool_FromLong((long)Py_IS_FINITE(x));
1961}
1962
1963PyDoc_STRVAR(math_isfinite_doc,
1964"isfinite(x) -> bool\n\n\
Mark Dickinson226f5442010-07-11 18:13:41 +00001965Return True if x is neither an infinity nor a NaN, and False otherwise.");
Mark Dickinson8e0c9962010-07-11 17:38:24 +00001966
1967static PyObject *
Christian Heimes072c0f12008-01-03 23:01:04 +00001968math_isnan(PyObject *self, PyObject *arg)
1969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 double x = PyFloat_AsDouble(arg);
1971 if (x == -1.0 && PyErr_Occurred())
1972 return NULL;
1973 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00001974}
1975
1976PyDoc_STRVAR(math_isnan_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001977"isnan(x) -> bool\n\n\
Mark Dickinson226f5442010-07-11 18:13:41 +00001978Return True if x is a NaN (not a number), and False otherwise.");
Christian Heimes072c0f12008-01-03 23:01:04 +00001979
1980static PyObject *
1981math_isinf(PyObject *self, PyObject *arg)
1982{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 double x = PyFloat_AsDouble(arg);
1984 if (x == -1.0 && PyErr_Occurred())
1985 return NULL;
1986 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00001987}
1988
1989PyDoc_STRVAR(math_isinf_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001990"isinf(x) -> bool\n\n\
Mark Dickinson226f5442010-07-11 18:13:41 +00001991Return True if x is a positive or negative infinity, and False otherwise.");
Christian Heimes072c0f12008-01-03 23:01:04 +00001992
Tal Einatd5519ed2015-05-31 22:05:00 +03001993static PyObject *
1994math_isclose(PyObject *self, PyObject *args, PyObject *kwargs)
1995{
1996 double a, b;
1997 double rel_tol = 1e-9;
1998 double abs_tol = 0.0;
1999 double diff = 0.0;
2000 long result = 0;
2001
2002 static char *keywords[] = {"a", "b", "rel_tol", "abs_tol", NULL};
2003
2004
2005 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "dd|$dd:isclose",
2006 keywords,
2007 &a, &b, &rel_tol, &abs_tol
2008 ))
2009 return NULL;
2010
2011 /* sanity check on the inputs */
2012 if (rel_tol < 0.0 || abs_tol < 0.0 ) {
2013 PyErr_SetString(PyExc_ValueError,
2014 "tolerances must be non-negative");
2015 return NULL;
2016 }
2017
2018 if ( a == b ) {
2019 /* short circuit exact equality -- needed to catch two infinities of
2020 the same sign. And perhaps speeds things up a bit sometimes.
2021 */
2022 Py_RETURN_TRUE;
2023 }
2024
2025 /* This catches the case of two infinities of opposite sign, or
2026 one infinity and one finite number. Two infinities of opposite
2027 sign would otherwise have an infinite relative tolerance.
2028 Two infinities of the same sign are caught by the equality check
2029 above.
2030 */
2031
2032 if (Py_IS_INFINITY(a) || Py_IS_INFINITY(b)) {
2033 Py_RETURN_FALSE;
2034 }
2035
2036 /* now do the regular computation
2037 this is essentially the "weak" test from the Boost library
2038 */
2039
2040 diff = fabs(b - a);
2041
2042 result = (((diff <= fabs(rel_tol * b)) ||
2043 (diff <= fabs(rel_tol * a))) ||
2044 (diff <= abs_tol));
2045
2046 return PyBool_FromLong(result);
2047}
2048
2049PyDoc_STRVAR(math_isclose_doc,
2050"is_close(a, b, *, rel_tol=1e-09, abs_tol=0.0) -> bool\n"
2051"\n"
2052"Determine whether two floating point numbers are close in value.\n"
2053"\n"
2054" rel_tol\n"
2055" maximum difference for being considered \"close\", relative to the\n"
2056" magnitude of the input values\n"
2057" abs_tol\n"
2058" maximum difference for being considered \"close\", regardless of the\n"
2059" magnitude of the input values\n"
2060"\n"
2061"Return True if a is close in value to b, and False otherwise.\n"
2062"\n"
2063"For the values to be considered close, the difference between them\n"
2064"must be smaller than at least one of the tolerances.\n"
2065"\n"
2066"-inf, inf and NaN behave similarly to the IEEE 754 Standard. That\n"
2067"is, NaN is not close to anything, even itself. inf and -inf are\n"
2068"only close to themselves.");
2069
Barry Warsaw8b43b191996-12-09 22:32:36 +00002070static PyMethodDef math_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 {"acos", math_acos, METH_O, math_acos_doc},
2072 {"acosh", math_acosh, METH_O, math_acosh_doc},
2073 {"asin", math_asin, METH_O, math_asin_doc},
2074 {"asinh", math_asinh, METH_O, math_asinh_doc},
2075 {"atan", math_atan, METH_O, math_atan_doc},
2076 {"atan2", math_atan2, METH_VARARGS, math_atan2_doc},
2077 {"atanh", math_atanh, METH_O, math_atanh_doc},
2078 {"ceil", math_ceil, METH_O, math_ceil_doc},
2079 {"copysign", math_copysign, METH_VARARGS, math_copysign_doc},
2080 {"cos", math_cos, METH_O, math_cos_doc},
2081 {"cosh", math_cosh, METH_O, math_cosh_doc},
2082 {"degrees", math_degrees, METH_O, math_degrees_doc},
2083 {"erf", math_erf, METH_O, math_erf_doc},
2084 {"erfc", math_erfc, METH_O, math_erfc_doc},
2085 {"exp", math_exp, METH_O, math_exp_doc},
2086 {"expm1", math_expm1, METH_O, math_expm1_doc},
2087 {"fabs", math_fabs, METH_O, math_fabs_doc},
2088 {"factorial", math_factorial, METH_O, math_factorial_doc},
2089 {"floor", math_floor, METH_O, math_floor_doc},
2090 {"fmod", math_fmod, METH_VARARGS, math_fmod_doc},
2091 {"frexp", math_frexp, METH_O, math_frexp_doc},
2092 {"fsum", math_fsum, METH_O, math_fsum_doc},
2093 {"gamma", math_gamma, METH_O, math_gamma_doc},
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03002094 {"gcd", math_gcd, METH_VARARGS, math_gcd_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 {"hypot", math_hypot, METH_VARARGS, math_hypot_doc},
Tal Einatd5519ed2015-05-31 22:05:00 +03002096 {"isclose", (PyCFunction) math_isclose, METH_VARARGS | METH_KEYWORDS,
2097 math_isclose_doc},
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002098 {"isfinite", math_isfinite, METH_O, math_isfinite_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 {"isinf", math_isinf, METH_O, math_isinf_doc},
2100 {"isnan", math_isnan, METH_O, math_isnan_doc},
2101 {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc},
2102 {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
2103 {"log", math_log, METH_VARARGS, math_log_doc},
2104 {"log1p", math_log1p, METH_O, math_log1p_doc},
2105 {"log10", math_log10, METH_O, math_log10_doc},
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02002106 {"log2", math_log2, METH_O, math_log2_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 {"modf", math_modf, METH_O, math_modf_doc},
2108 {"pow", math_pow, METH_VARARGS, math_pow_doc},
2109 {"radians", math_radians, METH_O, math_radians_doc},
2110 {"sin", math_sin, METH_O, math_sin_doc},
2111 {"sinh", math_sinh, METH_O, math_sinh_doc},
2112 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
2113 {"tan", math_tan, METH_O, math_tan_doc},
2114 {"tanh", math_tanh, METH_O, math_tanh_doc},
2115 {"trunc", math_trunc, METH_O, math_trunc_doc},
2116 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002117};
2118
Guido van Rossumc6e22901998-12-04 19:26:43 +00002119
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002120PyDoc_STRVAR(module_doc,
Tim Peters63c94532001-09-04 23:17:42 +00002121"This module is always available. It provides access to the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002122"mathematical functions defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00002123
Martin v. Löwis1a214512008-06-11 05:26:20 +00002124
2125static struct PyModuleDef mathmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 PyModuleDef_HEAD_INIT,
2127 "math",
2128 module_doc,
2129 -1,
2130 math_methods,
2131 NULL,
2132 NULL,
2133 NULL,
2134 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002135};
2136
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002137PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002138PyInit_math(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 PyObject *m;
Tim Petersfe71f812001-08-07 22:10:00 +00002141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 m = PyModule_Create(&mathmodule);
2143 if (m == NULL)
2144 goto finally;
Barry Warsawfc93f751996-12-17 00:47:03 +00002145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
2147 PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
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}