blob: 153d152a2e7c4c602f92a815de9cc090b5235cea [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
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000688/* Call is_error when errno != 0, and where x is the result libm
689 * returned. is_error will usually set up an exception and return
690 * true (1), but may return false (0) without setting up an exception.
691 */
692static int
693is_error(double x)
694{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 int result = 1; /* presumption of guilt */
696 assert(errno); /* non-zero errno is a precondition for calling */
697 if (errno == EDOM)
698 PyErr_SetString(PyExc_ValueError, "math domain error");
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 else if (errno == ERANGE) {
701 /* ANSI C generally requires libm functions to set ERANGE
702 * on overflow, but also generally *allows* them to set
703 * ERANGE on underflow too. There's no consistency about
704 * the latter across platforms.
705 * Alas, C99 never requires that errno be set.
706 * Here we suppress the underflow errors (libm functions
707 * should return a zero on underflow, and +- HUGE_VAL on
708 * overflow, so testing the result for zero suffices to
709 * distinguish the cases).
710 *
711 * On some platforms (Ubuntu/ia64) it seems that errno can be
712 * set to ERANGE for subnormal results that do *not* underflow
713 * to zero. So to be safe, we'll ignore ERANGE whenever the
714 * function result is less than one in absolute value.
715 */
716 if (fabs(x) < 1.0)
717 result = 0;
718 else
719 PyErr_SetString(PyExc_OverflowError,
720 "math range error");
721 }
722 else
723 /* Unexpected math error */
724 PyErr_SetFromErrno(PyExc_ValueError);
725 return result;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000726}
727
Mark Dickinsone675f082008-12-11 21:56:00 +0000728/*
Christian Heimes53876d92008-04-19 00:31:39 +0000729 math_1 is used to wrap a libm function f that takes a double
730 arguments and returns a double.
731
732 The error reporting follows these rules, which are designed to do
733 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
734 platforms.
735
736 - a NaN result from non-NaN inputs causes ValueError to be raised
737 - an infinite result from finite inputs causes OverflowError to be
738 raised if can_overflow is 1, or raises ValueError if can_overflow
739 is 0.
740 - if the result is finite and errno == EDOM then ValueError is
741 raised
742 - if the result is finite and nonzero and errno == ERANGE then
743 OverflowError is raised
744
745 The last rule is used to catch overflow on platforms which follow
746 C89 but for which HUGE_VAL is not an infinity.
747
748 For the majority of one-argument functions these rules are enough
749 to ensure that Python's functions behave as specified in 'Annex F'
750 of the C99 standard, with the 'invalid' and 'divide-by-zero'
751 floating-point exceptions mapping to Python's ValueError and the
752 'overflow' floating-point exception mapping to OverflowError.
753 math_1 only works for functions that don't have singularities *and*
754 the possibility of overflow; fortunately, that covers everything we
755 care about right now.
756*/
757
Barry Warsaw8b43b191996-12-09 22:32:36 +0000758static PyObject *
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000759math_1_to_whatever(PyObject *arg, double (*func) (double),
Christian Heimes53876d92008-04-19 00:31:39 +0000760 PyObject *(*from_double_func) (double),
761 int can_overflow)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 double x, r;
764 x = PyFloat_AsDouble(arg);
765 if (x == -1.0 && PyErr_Occurred())
766 return NULL;
767 errno = 0;
768 PyFPE_START_PROTECT("in math_1", return 0);
769 r = (*func)(x);
770 PyFPE_END_PROTECT(r);
771 if (Py_IS_NAN(r) && !Py_IS_NAN(x)) {
772 PyErr_SetString(PyExc_ValueError,
773 "math domain error"); /* invalid arg */
774 return NULL;
775 }
776 if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) {
Benjamin Peterson2354a752012-03-13 16:13:09 -0500777 if (can_overflow)
778 PyErr_SetString(PyExc_OverflowError,
779 "math range error"); /* overflow */
780 else
781 PyErr_SetString(PyExc_ValueError,
782 "math domain error"); /* singularity */
783 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 }
785 if (Py_IS_FINITE(r) && errno && is_error(r))
786 /* this branch unnecessary on most platforms */
787 return NULL;
Mark Dickinsonde429622008-05-01 00:19:23 +0000788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 return (*from_double_func)(r);
Christian Heimes53876d92008-04-19 00:31:39 +0000790}
791
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000792/* variant of math_1, to be used when the function being wrapped is known to
793 set errno properly (that is, errno = EDOM for invalid or divide-by-zero,
794 errno = ERANGE for overflow). */
795
796static PyObject *
797math_1a(PyObject *arg, double (*func) (double))
798{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 double x, r;
800 x = PyFloat_AsDouble(arg);
801 if (x == -1.0 && PyErr_Occurred())
802 return NULL;
803 errno = 0;
804 PyFPE_START_PROTECT("in math_1a", return 0);
805 r = (*func)(x);
806 PyFPE_END_PROTECT(r);
807 if (errno && is_error(r))
808 return NULL;
809 return PyFloat_FromDouble(r);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000810}
811
Christian Heimes53876d92008-04-19 00:31:39 +0000812/*
813 math_2 is used to wrap a libm function f that takes two double
814 arguments and returns a double.
815
816 The error reporting follows these rules, which are designed to do
817 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
818 platforms.
819
820 - a NaN result from non-NaN inputs causes ValueError to be raised
821 - an infinite result from finite inputs causes OverflowError to be
822 raised.
823 - if the result is finite and errno == EDOM then ValueError is
824 raised
825 - if the result is finite and nonzero and errno == ERANGE then
826 OverflowError is raised
827
828 The last rule is used to catch overflow on platforms which follow
829 C89 but for which HUGE_VAL is not an infinity.
830
831 For most two-argument functions (copysign, fmod, hypot, atan2)
832 these rules are enough to ensure that Python's functions behave as
833 specified in 'Annex F' of the C99 standard, with the 'invalid' and
834 'divide-by-zero' floating-point exceptions mapping to Python's
835 ValueError and the 'overflow' floating-point exception mapping to
836 OverflowError.
837*/
838
839static PyObject *
840math_1(PyObject *arg, double (*func) (double), int can_overflow)
841{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow);
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000843}
844
845static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000846math_1_to_int(PyObject *arg, double (*func) (double), int can_overflow)
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000847{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 return math_1_to_whatever(arg, func, PyLong_FromDouble, can_overflow);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000849}
850
Barry Warsaw8b43b191996-12-09 22:32:36 +0000851static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +0000852math_2(PyObject *args, double (*func) (double, double), char *funcname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000853{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 PyObject *ox, *oy;
855 double x, y, r;
856 if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy))
857 return NULL;
858 x = PyFloat_AsDouble(ox);
859 y = PyFloat_AsDouble(oy);
860 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
861 return NULL;
862 errno = 0;
863 PyFPE_START_PROTECT("in math_2", return 0);
864 r = (*func)(x, y);
865 PyFPE_END_PROTECT(r);
866 if (Py_IS_NAN(r)) {
867 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
868 errno = EDOM;
869 else
870 errno = 0;
871 }
872 else if (Py_IS_INFINITY(r)) {
873 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
874 errno = ERANGE;
875 else
876 errno = 0;
877 }
878 if (errno && is_error(r))
879 return NULL;
880 else
881 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000882}
883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884#define FUNC1(funcname, func, can_overflow, docstring) \
885 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
886 return math_1(args, func, can_overflow); \
887 }\
888 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890#define FUNC1A(funcname, func, docstring) \
891 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
892 return math_1a(args, func); \
893 }\
894 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000895
Fred Drake40c48682000-07-03 18:11:56 +0000896#define FUNC2(funcname, func, docstring) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
898 return math_2(args, func, #funcname); \
899 }\
900 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000901
Christian Heimes53876d92008-04-19 00:31:39 +0000902FUNC1(acos, acos, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000903 "acos(x)\n\nReturn the arc cosine (measured in radians) of x.")
Mark Dickinsonf3718592009-12-21 15:27:41 +0000904FUNC1(acosh, m_acosh, 0,
Mark Dickinsondfe0b232015-01-11 13:08:05 +0000905 "acosh(x)\n\nReturn the inverse hyperbolic cosine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000906FUNC1(asin, asin, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000907 "asin(x)\n\nReturn the arc sine (measured in radians) of x.")
Mark Dickinsonf3718592009-12-21 15:27:41 +0000908FUNC1(asinh, m_asinh, 0,
Mark Dickinsondfe0b232015-01-11 13:08:05 +0000909 "asinh(x)\n\nReturn the inverse hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000910FUNC1(atan, atan, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000911 "atan(x)\n\nReturn the arc tangent (measured in radians) of x.")
Christian Heimese57950f2008-04-21 13:08:03 +0000912FUNC2(atan2, m_atan2,
Tim Petersfe71f812001-08-07 22:10:00 +0000913 "atan2(y, x)\n\nReturn the arc tangent (measured in radians) of y/x.\n"
914 "Unlike atan(y/x), the signs of both x and y are considered.")
Mark Dickinsonf3718592009-12-21 15:27:41 +0000915FUNC1(atanh, m_atanh, 0,
Mark Dickinsondfe0b232015-01-11 13:08:05 +0000916 "atanh(x)\n\nReturn the inverse hyperbolic tangent of x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +0000917
918static PyObject * math_ceil(PyObject *self, PyObject *number) {
Benjamin Petersonce798522012-01-22 11:24:29 -0500919 _Py_IDENTIFIER(__ceil__);
Mark Dickinson6d02d9c2010-07-02 16:05:15 +0000920 PyObject *method, *result;
Guido van Rossum13e05de2007-08-23 22:56:55 +0000921
Benjamin Petersonce798522012-01-22 11:24:29 -0500922 method = _PyObject_LookupSpecial(number, &PyId___ceil__);
Benjamin Petersonf751bc92010-07-02 13:46:42 +0000923 if (method == NULL) {
924 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 return math_1_to_int(number, ceil, 0);
Benjamin Petersonf751bc92010-07-02 13:46:42 +0000927 }
Mark Dickinson6d02d9c2010-07-02 16:05:15 +0000928 result = PyObject_CallFunctionObjArgs(method, NULL);
929 Py_DECREF(method);
930 return result;
Guido van Rossum13e05de2007-08-23 22:56:55 +0000931}
932
933PyDoc_STRVAR(math_ceil_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 "ceil(x)\n\nReturn the ceiling of x as an int.\n"
935 "This is the smallest integral value >= x.");
Guido van Rossum13e05de2007-08-23 22:56:55 +0000936
Christian Heimes072c0f12008-01-03 23:01:04 +0000937FUNC2(copysign, copysign,
Andrew Kuchling8cb1ec32014-02-16 11:11:25 -0500938 "copysign(x, y)\n\nReturn a float with the magnitude (absolute value) "
939 "of x but the sign \nof y. On platforms that support signed zeros, "
Andrew Kuchling31378852014-02-16 12:09:35 -0500940 "copysign(1.0, -0.0) \nreturns -1.0.\n")
Christian Heimes53876d92008-04-19 00:31:39 +0000941FUNC1(cos, cos, 0,
942 "cos(x)\n\nReturn the cosine of x (measured in radians).")
943FUNC1(cosh, cosh, 1,
944 "cosh(x)\n\nReturn the hyperbolic cosine of x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +0000945FUNC1A(erf, m_erf,
946 "erf(x)\n\nError function at x.")
947FUNC1A(erfc, m_erfc,
948 "erfc(x)\n\nComplementary error function at x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000949FUNC1(exp, exp, 1,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000950 "exp(x)\n\nReturn e raised to the power of x.")
Mark Dickinson664b5112009-12-16 20:23:42 +0000951FUNC1(expm1, m_expm1, 1,
952 "expm1(x)\n\nReturn exp(x)-1.\n"
953 "This function avoids the loss of precision involved in the direct "
954 "evaluation of exp(x)-1 for small x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000955FUNC1(fabs, fabs, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000956 "fabs(x)\n\nReturn the absolute value of the float x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +0000957
958static PyObject * math_floor(PyObject *self, PyObject *number) {
Benjamin Petersonce798522012-01-22 11:24:29 -0500959 _Py_IDENTIFIER(__floor__);
Benjamin Petersonb0125892010-07-02 13:35:17 +0000960 PyObject *method, *result;
Guido van Rossum13e05de2007-08-23 22:56:55 +0000961
Benjamin Petersonce798522012-01-22 11:24:29 -0500962 method = _PyObject_LookupSpecial(number, &PyId___floor__);
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +0000963 if (method == NULL) {
964 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 return math_1_to_int(number, floor, 0);
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +0000967 }
Benjamin Petersonb0125892010-07-02 13:35:17 +0000968 result = PyObject_CallFunctionObjArgs(method, NULL);
969 Py_DECREF(method);
970 return result;
Guido van Rossum13e05de2007-08-23 22:56:55 +0000971}
972
973PyDoc_STRVAR(math_floor_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 "floor(x)\n\nReturn the floor of x as an int.\n"
975 "This is the largest integral value <= x.");
Guido van Rossum13e05de2007-08-23 22:56:55 +0000976
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000977FUNC1A(gamma, m_tgamma,
978 "gamma(x)\n\nGamma function at x.")
Mark Dickinson05d2e082009-12-11 20:17:17 +0000979FUNC1A(lgamma, m_lgamma,
980 "lgamma(x)\n\nNatural logarithm of absolute value of Gamma function at x.")
Mark Dickinsonbe64d952010-07-07 16:21:29 +0000981FUNC1(log1p, m_log1p, 0,
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000982 "log1p(x)\n\nReturn the natural logarithm of 1+x (base e).\n"
983 "The result is computed in a way which is accurate for x near zero.")
Christian Heimes53876d92008-04-19 00:31:39 +0000984FUNC1(sin, sin, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000985 "sin(x)\n\nReturn the sine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +0000986FUNC1(sinh, sinh, 1,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000987 "sinh(x)\n\nReturn the hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000988FUNC1(sqrt, sqrt, 0,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000989 "sqrt(x)\n\nReturn the square root of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000990FUNC1(tan, tan, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000991 "tan(x)\n\nReturn the tangent of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +0000992FUNC1(tanh, tanh, 0,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000993 "tanh(x)\n\nReturn the hyperbolic tangent of x.")
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000994
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000995/* Precision summation function as msum() by Raymond Hettinger in
996 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
997 enhanced with the exact partials sum and roundoff from Mark
998 Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
999 See those links for more details, proofs and other references.
1000
1001 Note 1: IEEE 754R floating point semantics are assumed,
1002 but the current implementation does not re-establish special
1003 value semantics across iterations (i.e. handling -Inf + Inf).
1004
1005 Note 2: No provision is made for intermediate overflow handling;
Georg Brandlf78e02b2008-06-10 17:40:04 +00001006 therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001007 sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
1008 overflow of the first partial sum.
1009
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001010 Note 3: The intermediate values lo, yr, and hi are declared volatile so
1011 aggressive compilers won't algebraically reduce lo to always be exactly 0.0.
Georg Brandlf78e02b2008-06-10 17:40:04 +00001012 Also, the volatile declaration forces the values to be stored in memory as
1013 regular doubles instead of extended long precision (80-bit) values. This
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001014 prevents double rounding because any addition or subtraction of two doubles
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 can be resolved exactly into double-sized hi and lo values. As long as the
Georg Brandlf78e02b2008-06-10 17:40:04 +00001016 hi value gets forced into a double before yr and lo are computed, the extra
1017 bits in downstream extended precision operations (x87 for example) will be
1018 exactly zero and therefore can be losslessly stored back into a double,
1019 thereby preventing double rounding.
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001020
1021 Note 4: A similar implementation is in Modules/cmathmodule.c.
1022 Be sure to update both when making changes.
1023
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001024 Note 5: The signature of math.fsum() differs from builtins.sum()
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001025 because the start argument doesn't make sense in the context of
1026 accurate summation. Since the partials table is collapsed before
1027 returning a result, sum(seq2, start=sum(seq1)) may not equal the
1028 accurate result returned by sum(itertools.chain(seq1, seq2)).
1029*/
1030
1031#define NUM_PARTIALS 32 /* initial partials array size, on stack */
1032
1033/* Extend the partials array p[] by doubling its size. */
1034static int /* non-zero on error */
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001035_fsum_realloc(double **p_ptr, Py_ssize_t n,
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001036 double *ps, Py_ssize_t *m_ptr)
1037{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 void *v = NULL;
1039 Py_ssize_t m = *m_ptr;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 m += m; /* double */
Victor Stinner049e5092014-08-17 22:20:00 +02001042 if (n < m && (size_t)m < ((size_t)PY_SSIZE_T_MAX / sizeof(double))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 double *p = *p_ptr;
1044 if (p == ps) {
1045 v = PyMem_Malloc(sizeof(double) * m);
1046 if (v != NULL)
1047 memcpy(v, ps, sizeof(double) * n);
1048 }
1049 else
1050 v = PyMem_Realloc(p, sizeof(double) * m);
1051 }
1052 if (v == NULL) { /* size overflow or no memory */
1053 PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
1054 return 1;
1055 }
1056 *p_ptr = (double*) v;
1057 *m_ptr = m;
1058 return 0;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001059}
1060
1061/* Full precision summation of a sequence of floats.
1062
1063 def msum(iterable):
1064 partials = [] # sorted, non-overlapping partial sums
1065 for x in iterable:
Mark Dickinsonfdb0acc2010-06-25 20:22:24 +00001066 i = 0
1067 for y in partials:
1068 if abs(x) < abs(y):
1069 x, y = y, x
1070 hi = x + y
1071 lo = y - (hi - x)
1072 if lo:
1073 partials[i] = lo
1074 i += 1
1075 x = hi
1076 partials[i:] = [x]
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001077 return sum_exact(partials)
1078
1079 Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
1080 are exactly equal to x+y. The inner loop applies hi/lo summation to each
1081 partial so that the list of partial sums remains exact.
1082
1083 Sum_exact() adds the partial sums exactly and correctly rounds the final
1084 result (using the round-half-to-even rule). The items in partials remain
1085 non-zero, non-special, non-overlapping and strictly increasing in
1086 magnitude, but possibly not all having the same sign.
1087
1088 Depends on IEEE 754 arithmetic guarantees and half-even rounding.
1089*/
1090
1091static PyObject*
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001092math_fsum(PyObject *self, PyObject *seq)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 PyObject *item, *iter, *sum = NULL;
1095 Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
1096 double x, y, t, ps[NUM_PARTIALS], *p = ps;
1097 double xsave, special_sum = 0.0, inf_sum = 0.0;
1098 volatile double hi, yr, lo;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 iter = PyObject_GetIter(seq);
1101 if (iter == NULL)
1102 return NULL;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 for(;;) { /* for x in iterable */
1107 assert(0 <= n && n <= m);
1108 assert((m == NUM_PARTIALS && p == ps) ||
1109 (m > NUM_PARTIALS && p != NULL));
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 item = PyIter_Next(iter);
1112 if (item == NULL) {
1113 if (PyErr_Occurred())
1114 goto _fsum_error;
1115 break;
1116 }
1117 x = PyFloat_AsDouble(item);
1118 Py_DECREF(item);
1119 if (PyErr_Occurred())
1120 goto _fsum_error;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 xsave = x;
1123 for (i = j = 0; j < n; j++) { /* for y in partials */
1124 y = p[j];
1125 if (fabs(x) < fabs(y)) {
1126 t = x; x = y; y = t;
1127 }
1128 hi = x + y;
1129 yr = hi - x;
1130 lo = y - yr;
1131 if (lo != 0.0)
1132 p[i++] = lo;
1133 x = hi;
1134 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 n = i; /* ps[i:] = [x] */
1137 if (x != 0.0) {
1138 if (! Py_IS_FINITE(x)) {
1139 /* a nonfinite x could arise either as
1140 a result of intermediate overflow, or
1141 as a result of a nan or inf in the
1142 summands */
1143 if (Py_IS_FINITE(xsave)) {
1144 PyErr_SetString(PyExc_OverflowError,
1145 "intermediate overflow in fsum");
1146 goto _fsum_error;
1147 }
1148 if (Py_IS_INFINITY(xsave))
1149 inf_sum += xsave;
1150 special_sum += xsave;
1151 /* reset partials */
1152 n = 0;
1153 }
1154 else if (n >= m && _fsum_realloc(&p, n, ps, &m))
1155 goto _fsum_error;
1156 else
1157 p[n++] = x;
1158 }
1159 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 if (special_sum != 0.0) {
1162 if (Py_IS_NAN(inf_sum))
1163 PyErr_SetString(PyExc_ValueError,
1164 "-inf + inf in fsum");
1165 else
1166 sum = PyFloat_FromDouble(special_sum);
1167 goto _fsum_error;
1168 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 hi = 0.0;
1171 if (n > 0) {
1172 hi = p[--n];
1173 /* sum_exact(ps, hi) from the top, stop when the sum becomes
1174 inexact. */
1175 while (n > 0) {
1176 x = hi;
1177 y = p[--n];
1178 assert(fabs(y) < fabs(x));
1179 hi = x + y;
1180 yr = hi - x;
1181 lo = y - yr;
1182 if (lo != 0.0)
1183 break;
1184 }
1185 /* Make half-even rounding work across multiple partials.
1186 Needed so that sum([1e-16, 1, 1e16]) will round-up the last
1187 digit to two instead of down to zero (the 1e-16 makes the 1
1188 slightly closer to two). With a potential 1 ULP rounding
1189 error fixed-up, math.fsum() can guarantee commutativity. */
1190 if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
1191 (lo > 0.0 && p[n-1] > 0.0))) {
1192 y = lo * 2.0;
1193 x = hi + y;
1194 yr = x - hi;
1195 if (y == yr)
1196 hi = x;
1197 }
1198 }
1199 sum = PyFloat_FromDouble(hi);
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001200
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001201_fsum_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 PyFPE_END_PROTECT(hi)
1203 Py_DECREF(iter);
1204 if (p != ps)
1205 PyMem_Free(p);
1206 return sum;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001207}
1208
1209#undef NUM_PARTIALS
1210
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001211PyDoc_STRVAR(math_fsum_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001212"fsum(iterable)\n\n\
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001213Return an accurate floating point sum of values in the iterable.\n\
1214Assumes IEEE-754 floating point arithmetic.");
1215
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001216/* Return the smallest integer k such that n < 2**k, or 0 if n == 0.
1217 * Equivalent to floor(lg(x))+1. Also equivalent to: bitwidth_of_type -
1218 * count_leading_zero_bits(x)
1219 */
1220
1221/* XXX: This routine does more or less the same thing as
1222 * bits_in_digit() in Objects/longobject.c. Someday it would be nice to
1223 * consolidate them. On BSD, there's a library function called fls()
1224 * that we could use, and GCC provides __builtin_clz().
1225 */
1226
1227static unsigned long
1228bit_length(unsigned long n)
1229{
1230 unsigned long len = 0;
1231 while (n != 0) {
1232 ++len;
1233 n >>= 1;
1234 }
1235 return len;
1236}
1237
1238static unsigned long
1239count_set_bits(unsigned long n)
1240{
1241 unsigned long count = 0;
1242 while (n != 0) {
1243 ++count;
1244 n &= n - 1; /* clear least significant bit */
1245 }
1246 return count;
1247}
1248
1249/* Divide-and-conquer factorial algorithm
1250 *
1251 * Based on the formula and psuedo-code provided at:
1252 * http://www.luschny.de/math/factorial/binarysplitfact.html
1253 *
1254 * Faster algorithms exist, but they're more complicated and depend on
Ezio Melotti9527afd2010-07-08 15:03:02 +00001255 * a fast prime factorization algorithm.
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001256 *
1257 * Notes on the algorithm
1258 * ----------------------
1259 *
1260 * factorial(n) is written in the form 2**k * m, with m odd. k and m are
1261 * computed separately, and then combined using a left shift.
1262 *
1263 * The function factorial_odd_part computes the odd part m (i.e., the greatest
1264 * odd divisor) of factorial(n), using the formula:
1265 *
1266 * factorial_odd_part(n) =
1267 *
1268 * product_{i >= 0} product_{0 < j <= n / 2**i, j odd} j
1269 *
1270 * Example: factorial_odd_part(20) =
1271 *
1272 * (1) *
1273 * (1) *
1274 * (1 * 3 * 5) *
1275 * (1 * 3 * 5 * 7 * 9)
1276 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1277 *
1278 * Here i goes from large to small: the first term corresponds to i=4 (any
1279 * larger i gives an empty product), and the last term corresponds to i=0.
1280 * Each term can be computed from the last by multiplying by the extra odd
1281 * numbers required: e.g., to get from the penultimate term to the last one,
1282 * we multiply by (11 * 13 * 15 * 17 * 19).
1283 *
1284 * To see a hint of why this formula works, here are the same numbers as above
1285 * but with the even parts (i.e., the appropriate powers of 2) included. For
1286 * each subterm in the product for i, we multiply that subterm by 2**i:
1287 *
1288 * factorial(20) =
1289 *
1290 * (16) *
1291 * (8) *
1292 * (4 * 12 * 20) *
1293 * (2 * 6 * 10 * 14 * 18) *
1294 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1295 *
1296 * The factorial_partial_product function computes the product of all odd j in
1297 * range(start, stop) for given start and stop. It's used to compute the
1298 * partial products like (11 * 13 * 15 * 17 * 19) in the example above. It
1299 * operates recursively, repeatedly splitting the range into two roughly equal
1300 * pieces until the subranges are small enough to be computed using only C
1301 * integer arithmetic.
1302 *
1303 * The two-valuation k (i.e., the exponent of the largest power of 2 dividing
1304 * the factorial) is computed independently in the main math_factorial
1305 * function. By standard results, its value is:
1306 *
1307 * two_valuation = n//2 + n//4 + n//8 + ....
1308 *
1309 * It can be shown (e.g., by complete induction on n) that two_valuation is
1310 * equal to n - count_set_bits(n), where count_set_bits(n) gives the number of
1311 * '1'-bits in the binary expansion of n.
1312 */
1313
1314/* factorial_partial_product: Compute product(range(start, stop, 2)) using
1315 * divide and conquer. Assumes start and stop are odd and stop > start.
1316 * max_bits must be >= bit_length(stop - 2). */
1317
1318static PyObject *
1319factorial_partial_product(unsigned long start, unsigned long stop,
1320 unsigned long max_bits)
1321{
1322 unsigned long midpoint, num_operands;
1323 PyObject *left = NULL, *right = NULL, *result = NULL;
1324
1325 /* If the return value will fit an unsigned long, then we can
1326 * multiply in a tight, fast loop where each multiply is O(1).
1327 * Compute an upper bound on the number of bits required to store
1328 * the answer.
1329 *
1330 * Storing some integer z requires floor(lg(z))+1 bits, which is
1331 * conveniently the value returned by bit_length(z). The
1332 * product x*y will require at most
1333 * bit_length(x) + bit_length(y) bits to store, based
1334 * on the idea that lg product = lg x + lg y.
1335 *
1336 * We know that stop - 2 is the largest number to be multiplied. From
1337 * there, we have: bit_length(answer) <= num_operands *
1338 * bit_length(stop - 2)
1339 */
1340
1341 num_operands = (stop - start) / 2;
1342 /* The "num_operands <= 8 * SIZEOF_LONG" check guards against the
1343 * unlikely case of an overflow in num_operands * max_bits. */
1344 if (num_operands <= 8 * SIZEOF_LONG &&
1345 num_operands * max_bits <= 8 * SIZEOF_LONG) {
1346 unsigned long j, total;
1347 for (total = start, j = start + 2; j < stop; j += 2)
1348 total *= j;
1349 return PyLong_FromUnsignedLong(total);
1350 }
1351
1352 /* find midpoint of range(start, stop), rounded up to next odd number. */
1353 midpoint = (start + num_operands) | 1;
1354 left = factorial_partial_product(start, midpoint,
1355 bit_length(midpoint - 2));
1356 if (left == NULL)
1357 goto error;
1358 right = factorial_partial_product(midpoint, stop, max_bits);
1359 if (right == NULL)
1360 goto error;
1361 result = PyNumber_Multiply(left, right);
1362
1363 error:
1364 Py_XDECREF(left);
1365 Py_XDECREF(right);
1366 return result;
1367}
1368
1369/* factorial_odd_part: compute the odd part of factorial(n). */
1370
1371static PyObject *
1372factorial_odd_part(unsigned long n)
1373{
1374 long i;
1375 unsigned long v, lower, upper;
1376 PyObject *partial, *tmp, *inner, *outer;
1377
1378 inner = PyLong_FromLong(1);
1379 if (inner == NULL)
1380 return NULL;
1381 outer = inner;
1382 Py_INCREF(outer);
1383
1384 upper = 3;
1385 for (i = bit_length(n) - 2; i >= 0; i--) {
1386 v = n >> i;
1387 if (v <= 2)
1388 continue;
1389 lower = upper;
1390 /* (v + 1) | 1 = least odd integer strictly larger than n / 2**i */
1391 upper = (v + 1) | 1;
1392 /* Here inner is the product of all odd integers j in the range (0,
1393 n/2**(i+1)]. The factorial_partial_product call below gives the
1394 product of all odd integers j in the range (n/2**(i+1), n/2**i]. */
1395 partial = factorial_partial_product(lower, upper, bit_length(upper-2));
1396 /* inner *= partial */
1397 if (partial == NULL)
1398 goto error;
1399 tmp = PyNumber_Multiply(inner, partial);
1400 Py_DECREF(partial);
1401 if (tmp == NULL)
1402 goto error;
1403 Py_DECREF(inner);
1404 inner = tmp;
1405 /* Now inner is the product of all odd integers j in the range (0,
1406 n/2**i], giving the inner product in the formula above. */
1407
1408 /* outer *= inner; */
1409 tmp = PyNumber_Multiply(outer, inner);
1410 if (tmp == NULL)
1411 goto error;
1412 Py_DECREF(outer);
1413 outer = tmp;
1414 }
Mark Dickinson76464492012-10-25 10:46:28 +01001415 Py_DECREF(inner);
1416 return outer;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001417
1418 error:
1419 Py_DECREF(outer);
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001420 Py_DECREF(inner);
Mark Dickinson76464492012-10-25 10:46:28 +01001421 return NULL;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001422}
1423
1424/* Lookup table for small factorial values */
1425
1426static const unsigned long SmallFactorials[] = {
1427 1, 1, 2, 6, 24, 120, 720, 5040, 40320,
1428 362880, 3628800, 39916800, 479001600,
1429#if SIZEOF_LONG >= 8
1430 6227020800, 87178291200, 1307674368000,
1431 20922789888000, 355687428096000, 6402373705728000,
1432 121645100408832000, 2432902008176640000
1433#endif
1434};
1435
Barry Warsaw8b43b191996-12-09 22:32:36 +00001436static PyObject *
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001437math_factorial(PyObject *self, PyObject *arg)
1438{
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001439 long x;
Mark Dickinson5990d282014-04-10 09:29:39 -04001440 int overflow;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001441 PyObject *result, *odd_part, *two_valuation;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 if (PyFloat_Check(arg)) {
1444 PyObject *lx;
1445 double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
1446 if (!(Py_IS_FINITE(dx) && dx == floor(dx))) {
1447 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001448 "factorial() only accepts integral values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 return NULL;
1450 }
1451 lx = PyLong_FromDouble(dx);
1452 if (lx == NULL)
1453 return NULL;
Mark Dickinson5990d282014-04-10 09:29:39 -04001454 x = PyLong_AsLongAndOverflow(lx, &overflow);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 Py_DECREF(lx);
1456 }
1457 else
Mark Dickinson5990d282014-04-10 09:29:39 -04001458 x = PyLong_AsLongAndOverflow(arg, &overflow);
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001459
Mark Dickinson5990d282014-04-10 09:29:39 -04001460 if (x == -1 && PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 return NULL;
Mark Dickinson5990d282014-04-10 09:29:39 -04001462 }
1463 else if (overflow == 1) {
1464 PyErr_Format(PyExc_OverflowError,
1465 "factorial() argument should not exceed %ld",
1466 LONG_MAX);
1467 return NULL;
1468 }
1469 else if (overflow == -1 || x < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001471 "factorial() not defined for negative values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 return NULL;
1473 }
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001474
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001475 /* use lookup table if x is small */
Victor Stinner63941882011-09-29 00:42:28 +02001476 if (x < (long)Py_ARRAY_LENGTH(SmallFactorials))
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001477 return PyLong_FromUnsignedLong(SmallFactorials[x]);
1478
1479 /* else express in the form odd_part * 2**two_valuation, and compute as
1480 odd_part << two_valuation. */
1481 odd_part = factorial_odd_part(x);
1482 if (odd_part == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 return NULL;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001484 two_valuation = PyLong_FromLong(x - count_set_bits(x));
1485 if (two_valuation == NULL) {
1486 Py_DECREF(odd_part);
1487 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 }
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001489 result = PyNumber_Lshift(odd_part, two_valuation);
1490 Py_DECREF(two_valuation);
1491 Py_DECREF(odd_part);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 return result;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001493}
1494
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001495PyDoc_STRVAR(math_factorial_doc,
1496"factorial(x) -> Integral\n"
1497"\n"
1498"Find x!. Raise a ValueError if x is negative or non-integral.");
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001499
1500static PyObject *
Christian Heimes400adb02008-02-01 08:12:03 +00001501math_trunc(PyObject *self, PyObject *number)
1502{
Benjamin Petersonce798522012-01-22 11:24:29 -05001503 _Py_IDENTIFIER(__trunc__);
Benjamin Petersonb0125892010-07-02 13:35:17 +00001504 PyObject *trunc, *result;
Christian Heimes400adb02008-02-01 08:12:03 +00001505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 if (Py_TYPE(number)->tp_dict == NULL) {
1507 if (PyType_Ready(Py_TYPE(number)) < 0)
1508 return NULL;
1509 }
Christian Heimes400adb02008-02-01 08:12:03 +00001510
Benjamin Petersonce798522012-01-22 11:24:29 -05001511 trunc = _PyObject_LookupSpecial(number, &PyId___trunc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 if (trunc == NULL) {
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001513 if (!PyErr_Occurred())
1514 PyErr_Format(PyExc_TypeError,
1515 "type %.100s doesn't define __trunc__ method",
1516 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 return NULL;
1518 }
Benjamin Petersonb0125892010-07-02 13:35:17 +00001519 result = PyObject_CallFunctionObjArgs(trunc, NULL);
1520 Py_DECREF(trunc);
1521 return result;
Christian Heimes400adb02008-02-01 08:12:03 +00001522}
1523
1524PyDoc_STRVAR(math_trunc_doc,
1525"trunc(x:Real) -> Integral\n"
1526"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001527"Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.");
Christian Heimes400adb02008-02-01 08:12:03 +00001528
1529static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001530math_frexp(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 int i;
1533 double x = PyFloat_AsDouble(arg);
1534 if (x == -1.0 && PyErr_Occurred())
1535 return NULL;
1536 /* deal with special cases directly, to sidestep platform
1537 differences */
1538 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
1539 i = 0;
1540 }
1541 else {
1542 PyFPE_START_PROTECT("in math_frexp", return 0);
1543 x = frexp(x, &i);
1544 PyFPE_END_PROTECT(x);
1545 }
1546 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001547}
1548
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001549PyDoc_STRVAR(math_frexp_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001550"frexp(x)\n"
1551"\n"
1552"Return the mantissa and exponent of x, as pair (m, e).\n"
1553"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 +00001554"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 +00001555
Barry Warsaw8b43b191996-12-09 22:32:36 +00001556static PyObject *
Fred Drake40c48682000-07-03 18:11:56 +00001557math_ldexp(PyObject *self, PyObject *args)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 double x, r;
1560 PyObject *oexp;
1561 long exp;
1562 int overflow;
1563 if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp))
1564 return NULL;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 if (PyLong_Check(oexp)) {
1567 /* on overflow, replace exponent with either LONG_MAX
1568 or LONG_MIN, depending on the sign. */
1569 exp = PyLong_AsLongAndOverflow(oexp, &overflow);
1570 if (exp == -1 && PyErr_Occurred())
1571 return NULL;
1572 if (overflow)
1573 exp = overflow < 0 ? LONG_MIN : LONG_MAX;
1574 }
1575 else {
1576 PyErr_SetString(PyExc_TypeError,
Serhiy Storchaka95949422013-08-27 19:40:23 +03001577 "Expected an int as second argument to ldexp.");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 return NULL;
1579 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 if (x == 0. || !Py_IS_FINITE(x)) {
1582 /* NaNs, zeros and infinities are returned unchanged */
1583 r = x;
1584 errno = 0;
1585 } else if (exp > INT_MAX) {
1586 /* overflow */
1587 r = copysign(Py_HUGE_VAL, x);
1588 errno = ERANGE;
1589 } else if (exp < INT_MIN) {
1590 /* underflow to +-0 */
1591 r = copysign(0., x);
1592 errno = 0;
1593 } else {
1594 errno = 0;
1595 PyFPE_START_PROTECT("in math_ldexp", return 0);
1596 r = ldexp(x, (int)exp);
1597 PyFPE_END_PROTECT(r);
1598 if (Py_IS_INFINITY(r))
1599 errno = ERANGE;
1600 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 if (errno && is_error(r))
1603 return NULL;
1604 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001605}
1606
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001607PyDoc_STRVAR(math_ldexp_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001608"ldexp(x, i)\n\n\
1609Return x * (2**i).");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001610
Barry Warsaw8b43b191996-12-09 22:32:36 +00001611static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001612math_modf(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001613{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 double y, x = PyFloat_AsDouble(arg);
1615 if (x == -1.0 && PyErr_Occurred())
1616 return NULL;
1617 /* some platforms don't do the right thing for NaNs and
1618 infinities, so we take care of special cases directly. */
1619 if (!Py_IS_FINITE(x)) {
1620 if (Py_IS_INFINITY(x))
1621 return Py_BuildValue("(dd)", copysign(0., x), x);
1622 else if (Py_IS_NAN(x))
1623 return Py_BuildValue("(dd)", x, x);
1624 }
Christian Heimesa342c012008-04-20 21:01:16 +00001625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 errno = 0;
1627 PyFPE_START_PROTECT("in math_modf", return 0);
1628 x = modf(x, &y);
1629 PyFPE_END_PROTECT(x);
1630 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001631}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001632
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001633PyDoc_STRVAR(math_modf_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001634"modf(x)\n"
1635"\n"
1636"Return the fractional and integer parts of x. Both results carry the sign\n"
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001637"of x and are floats.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001638
Serhiy Storchaka95949422013-08-27 19:40:23 +03001639/* A decent logarithm is easy to compute even for huge ints, but libm can't
Tim Peters78526162001-09-05 00:53:45 +00001640 do that by itself -- loghelper can. func is log or log10, and name is
Serhiy Storchaka95949422013-08-27 19:40:23 +03001641 "log" or "log10". Note that overflow of the result isn't possible: an int
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00001642 can contain no more than INT_MAX * SHIFT bits, so has value certainly less
1643 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 +00001644 small enough to fit in an IEEE single. log and log10 are even smaller.
Serhiy Storchaka95949422013-08-27 19:40:23 +03001645 However, intermediate overflow is possible for an int if the number of bits
1646 in that int is larger than PY_SSIZE_T_MAX. */
Tim Peters78526162001-09-05 00:53:45 +00001647
1648static PyObject*
Thomas Wouters89f507f2006-12-13 04:49:30 +00001649loghelper(PyObject* arg, double (*func)(double), char *funcname)
Tim Peters78526162001-09-05 00:53:45 +00001650{
Serhiy Storchaka95949422013-08-27 19:40:23 +03001651 /* If it is int, do it ourselves. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 if (PyLong_Check(arg)) {
Mark Dickinsonc6037172010-09-29 19:06:36 +00001653 double x, result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 Py_ssize_t e;
Mark Dickinsonc6037172010-09-29 19:06:36 +00001655
1656 /* Negative or zero inputs give a ValueError. */
1657 if (Py_SIZE(arg) <= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 PyErr_SetString(PyExc_ValueError,
1659 "math domain error");
1660 return NULL;
1661 }
Mark Dickinsonfa41e602010-09-28 07:22:27 +00001662
Mark Dickinsonc6037172010-09-29 19:06:36 +00001663 x = PyLong_AsDouble(arg);
1664 if (x == -1.0 && PyErr_Occurred()) {
1665 if (!PyErr_ExceptionMatches(PyExc_OverflowError))
1666 return NULL;
1667 /* Here the conversion to double overflowed, but it's possible
1668 to compute the log anyway. Clear the exception and continue. */
1669 PyErr_Clear();
1670 x = _PyLong_Frexp((PyLongObject *)arg, &e);
1671 if (x == -1.0 && PyErr_Occurred())
1672 return NULL;
1673 /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */
1674 result = func(x) + func(2.0) * e;
1675 }
1676 else
1677 /* Successfully converted x to a double. */
1678 result = func(x);
1679 return PyFloat_FromDouble(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 }
Tim Peters78526162001-09-05 00:53:45 +00001681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 /* Else let libm handle it by itself. */
1683 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +00001684}
1685
1686static PyObject *
1687math_log(PyObject *self, PyObject *args)
1688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 PyObject *arg;
1690 PyObject *base = NULL;
1691 PyObject *num, *den;
1692 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base))
1695 return NULL;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 num = loghelper(arg, m_log, "log");
1698 if (num == NULL || base == NULL)
1699 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 den = loghelper(base, m_log, "log");
1702 if (den == NULL) {
1703 Py_DECREF(num);
1704 return NULL;
1705 }
Raymond Hettinger866964c2002-12-14 19:51:34 +00001706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 ans = PyNumber_TrueDivide(num, den);
1708 Py_DECREF(num);
1709 Py_DECREF(den);
1710 return ans;
Tim Peters78526162001-09-05 00:53:45 +00001711}
1712
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001713PyDoc_STRVAR(math_log_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001714"log(x[, base])\n\n\
1715Return the logarithm of x to the given base.\n\
Raymond Hettinger866964c2002-12-14 19:51:34 +00001716If the base not specified, returns the natural logarithm (base e) of x.");
Tim Peters78526162001-09-05 00:53:45 +00001717
1718static PyObject *
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001719math_log2(PyObject *self, PyObject *arg)
1720{
1721 return loghelper(arg, m_log2, "log2");
1722}
1723
1724PyDoc_STRVAR(math_log2_doc,
1725"log2(x)\n\nReturn the base 2 logarithm of x.");
1726
1727static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001728math_log10(PyObject *self, PyObject *arg)
Tim Peters78526162001-09-05 00:53:45 +00001729{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 return loghelper(arg, m_log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +00001731}
1732
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001733PyDoc_STRVAR(math_log10_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001734"log10(x)\n\nReturn the base 10 logarithm of x.");
Tim Peters78526162001-09-05 00:53:45 +00001735
Christian Heimes53876d92008-04-19 00:31:39 +00001736static PyObject *
1737math_fmod(PyObject *self, PyObject *args)
1738{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 PyObject *ox, *oy;
1740 double r, x, y;
1741 if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy))
1742 return NULL;
1743 x = PyFloat_AsDouble(ox);
1744 y = PyFloat_AsDouble(oy);
1745 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1746 return NULL;
1747 /* fmod(x, +/-Inf) returns x for finite x. */
1748 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
1749 return PyFloat_FromDouble(x);
1750 errno = 0;
1751 PyFPE_START_PROTECT("in math_fmod", return 0);
1752 r = fmod(x, y);
1753 PyFPE_END_PROTECT(r);
1754 if (Py_IS_NAN(r)) {
1755 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1756 errno = EDOM;
1757 else
1758 errno = 0;
1759 }
1760 if (errno && is_error(r))
1761 return NULL;
1762 else
1763 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00001764}
1765
1766PyDoc_STRVAR(math_fmod_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001767"fmod(x, y)\n\nReturn fmod(x, y), according to platform C."
Christian Heimes53876d92008-04-19 00:31:39 +00001768" x % y may differ.");
1769
1770static PyObject *
1771math_hypot(PyObject *self, PyObject *args)
1772{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 PyObject *ox, *oy;
1774 double r, x, y;
1775 if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy))
1776 return NULL;
1777 x = PyFloat_AsDouble(ox);
1778 y = PyFloat_AsDouble(oy);
1779 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1780 return NULL;
1781 /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */
1782 if (Py_IS_INFINITY(x))
1783 return PyFloat_FromDouble(fabs(x));
1784 if (Py_IS_INFINITY(y))
1785 return PyFloat_FromDouble(fabs(y));
1786 errno = 0;
1787 PyFPE_START_PROTECT("in math_hypot", return 0);
1788 r = hypot(x, y);
1789 PyFPE_END_PROTECT(r);
1790 if (Py_IS_NAN(r)) {
1791 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1792 errno = EDOM;
1793 else
1794 errno = 0;
1795 }
1796 else if (Py_IS_INFINITY(r)) {
1797 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
1798 errno = ERANGE;
1799 else
1800 errno = 0;
1801 }
1802 if (errno && is_error(r))
1803 return NULL;
1804 else
1805 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00001806}
1807
1808PyDoc_STRVAR(math_hypot_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001809"hypot(x, y)\n\nReturn the Euclidean distance, sqrt(x*x + y*y).");
Christian Heimes53876d92008-04-19 00:31:39 +00001810
1811/* pow can't use math_2, but needs its own wrapper: the problem is
1812 that an infinite result can arise either as a result of overflow
1813 (in which case OverflowError should be raised) or as a result of
1814 e.g. 0.**-5. (for which ValueError needs to be raised.)
1815*/
1816
1817static PyObject *
1818math_pow(PyObject *self, PyObject *args)
1819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 PyObject *ox, *oy;
1821 double r, x, y;
1822 int odd_y;
Christian Heimes53876d92008-04-19 00:31:39 +00001823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy))
1825 return NULL;
1826 x = PyFloat_AsDouble(ox);
1827 y = PyFloat_AsDouble(oy);
1828 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1829 return NULL;
Christian Heimesa342c012008-04-20 21:01:16 +00001830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 /* deal directly with IEEE specials, to cope with problems on various
1832 platforms whose semantics don't exactly match C99 */
1833 r = 0.; /* silence compiler warning */
1834 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
1835 errno = 0;
1836 if (Py_IS_NAN(x))
1837 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
1838 else if (Py_IS_NAN(y))
1839 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
1840 else if (Py_IS_INFINITY(x)) {
1841 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
1842 if (y > 0.)
1843 r = odd_y ? x : fabs(x);
1844 else if (y == 0.)
1845 r = 1.;
1846 else /* y < 0. */
1847 r = odd_y ? copysign(0., x) : 0.;
1848 }
1849 else if (Py_IS_INFINITY(y)) {
1850 if (fabs(x) == 1.0)
1851 r = 1.;
1852 else if (y > 0. && fabs(x) > 1.0)
1853 r = y;
1854 else if (y < 0. && fabs(x) < 1.0) {
1855 r = -y; /* result is +inf */
1856 if (x == 0.) /* 0**-inf: divide-by-zero */
1857 errno = EDOM;
1858 }
1859 else
1860 r = 0.;
1861 }
1862 }
1863 else {
1864 /* let libm handle finite**finite */
1865 errno = 0;
1866 PyFPE_START_PROTECT("in math_pow", return 0);
1867 r = pow(x, y);
1868 PyFPE_END_PROTECT(r);
1869 /* a NaN result should arise only from (-ve)**(finite
1870 non-integer); in this case we want to raise ValueError. */
1871 if (!Py_IS_FINITE(r)) {
1872 if (Py_IS_NAN(r)) {
1873 errno = EDOM;
1874 }
1875 /*
1876 an infinite result here arises either from:
1877 (A) (+/-0.)**negative (-> divide-by-zero)
1878 (B) overflow of x**y with x and y finite
1879 */
1880 else if (Py_IS_INFINITY(r)) {
1881 if (x == 0.)
1882 errno = EDOM;
1883 else
1884 errno = ERANGE;
1885 }
1886 }
1887 }
Christian Heimes53876d92008-04-19 00:31:39 +00001888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 if (errno && is_error(r))
1890 return NULL;
1891 else
1892 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00001893}
1894
1895PyDoc_STRVAR(math_pow_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001896"pow(x, y)\n\nReturn x**y (x to the power of y).");
Christian Heimes53876d92008-04-19 00:31:39 +00001897
Christian Heimes072c0f12008-01-03 23:01:04 +00001898static const double degToRad = Py_MATH_PI / 180.0;
1899static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001900
1901static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001902math_degrees(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 double x = PyFloat_AsDouble(arg);
1905 if (x == -1.0 && PyErr_Occurred())
1906 return NULL;
1907 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001908}
1909
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001910PyDoc_STRVAR(math_degrees_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001911"degrees(x)\n\n\
1912Convert angle x from radians to degrees.");
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001913
1914static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001915math_radians(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001916{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001917 double x = PyFloat_AsDouble(arg);
1918 if (x == -1.0 && PyErr_Occurred())
1919 return NULL;
1920 return PyFloat_FromDouble(x * degToRad);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001921}
1922
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001923PyDoc_STRVAR(math_radians_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001924"radians(x)\n\n\
1925Convert angle x from degrees to radians.");
Tim Peters78526162001-09-05 00:53:45 +00001926
Christian Heimes072c0f12008-01-03 23:01:04 +00001927static PyObject *
Mark Dickinson8e0c9962010-07-11 17:38:24 +00001928math_isfinite(PyObject *self, PyObject *arg)
1929{
1930 double x = PyFloat_AsDouble(arg);
1931 if (x == -1.0 && PyErr_Occurred())
1932 return NULL;
1933 return PyBool_FromLong((long)Py_IS_FINITE(x));
1934}
1935
1936PyDoc_STRVAR(math_isfinite_doc,
1937"isfinite(x) -> bool\n\n\
Mark Dickinson226f5442010-07-11 18:13:41 +00001938Return True if x is neither an infinity nor a NaN, and False otherwise.");
Mark Dickinson8e0c9962010-07-11 17:38:24 +00001939
1940static PyObject *
Christian Heimes072c0f12008-01-03 23:01:04 +00001941math_isnan(PyObject *self, PyObject *arg)
1942{
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 PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00001947}
1948
1949PyDoc_STRVAR(math_isnan_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001950"isnan(x) -> bool\n\n\
Mark Dickinson226f5442010-07-11 18:13:41 +00001951Return True if x is a NaN (not a number), and False otherwise.");
Christian Heimes072c0f12008-01-03 23:01:04 +00001952
1953static PyObject *
1954math_isinf(PyObject *self, PyObject *arg)
1955{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 double x = PyFloat_AsDouble(arg);
1957 if (x == -1.0 && PyErr_Occurred())
1958 return NULL;
1959 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00001960}
1961
1962PyDoc_STRVAR(math_isinf_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001963"isinf(x) -> bool\n\n\
Mark Dickinson226f5442010-07-11 18:13:41 +00001964Return True if x is a positive or negative infinity, and False otherwise.");
Christian Heimes072c0f12008-01-03 23:01:04 +00001965
Barry Warsaw8b43b191996-12-09 22:32:36 +00001966static PyMethodDef math_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 {"acos", math_acos, METH_O, math_acos_doc},
1968 {"acosh", math_acosh, METH_O, math_acosh_doc},
1969 {"asin", math_asin, METH_O, math_asin_doc},
1970 {"asinh", math_asinh, METH_O, math_asinh_doc},
1971 {"atan", math_atan, METH_O, math_atan_doc},
1972 {"atan2", math_atan2, METH_VARARGS, math_atan2_doc},
1973 {"atanh", math_atanh, METH_O, math_atanh_doc},
1974 {"ceil", math_ceil, METH_O, math_ceil_doc},
1975 {"copysign", math_copysign, METH_VARARGS, math_copysign_doc},
1976 {"cos", math_cos, METH_O, math_cos_doc},
1977 {"cosh", math_cosh, METH_O, math_cosh_doc},
1978 {"degrees", math_degrees, METH_O, math_degrees_doc},
1979 {"erf", math_erf, METH_O, math_erf_doc},
1980 {"erfc", math_erfc, METH_O, math_erfc_doc},
1981 {"exp", math_exp, METH_O, math_exp_doc},
1982 {"expm1", math_expm1, METH_O, math_expm1_doc},
1983 {"fabs", math_fabs, METH_O, math_fabs_doc},
1984 {"factorial", math_factorial, METH_O, math_factorial_doc},
1985 {"floor", math_floor, METH_O, math_floor_doc},
1986 {"fmod", math_fmod, METH_VARARGS, math_fmod_doc},
1987 {"frexp", math_frexp, METH_O, math_frexp_doc},
1988 {"fsum", math_fsum, METH_O, math_fsum_doc},
1989 {"gamma", math_gamma, METH_O, math_gamma_doc},
1990 {"hypot", math_hypot, METH_VARARGS, math_hypot_doc},
Mark Dickinson8e0c9962010-07-11 17:38:24 +00001991 {"isfinite", math_isfinite, METH_O, math_isfinite_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 {"isinf", math_isinf, METH_O, math_isinf_doc},
1993 {"isnan", math_isnan, METH_O, math_isnan_doc},
1994 {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc},
1995 {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
1996 {"log", math_log, METH_VARARGS, math_log_doc},
1997 {"log1p", math_log1p, METH_O, math_log1p_doc},
1998 {"log10", math_log10, METH_O, math_log10_doc},
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001999 {"log2", math_log2, METH_O, math_log2_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 {"modf", math_modf, METH_O, math_modf_doc},
2001 {"pow", math_pow, METH_VARARGS, math_pow_doc},
2002 {"radians", math_radians, METH_O, math_radians_doc},
2003 {"sin", math_sin, METH_O, math_sin_doc},
2004 {"sinh", math_sinh, METH_O, math_sinh_doc},
2005 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
2006 {"tan", math_tan, METH_O, math_tan_doc},
2007 {"tanh", math_tanh, METH_O, math_tanh_doc},
2008 {"trunc", math_trunc, METH_O, math_trunc_doc},
2009 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002010};
2011
Guido van Rossumc6e22901998-12-04 19:26:43 +00002012
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002013PyDoc_STRVAR(module_doc,
Tim Peters63c94532001-09-04 23:17:42 +00002014"This module is always available. It provides access to the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002015"mathematical functions defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00002016
Martin v. Löwis1a214512008-06-11 05:26:20 +00002017
2018static struct PyModuleDef mathmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 PyModuleDef_HEAD_INIT,
2020 "math",
2021 module_doc,
2022 -1,
2023 math_methods,
2024 NULL,
2025 NULL,
2026 NULL,
2027 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002028};
2029
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002030PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002031PyInit_math(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002032{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002033 PyObject *m;
Tim Petersfe71f812001-08-07 22:10:00 +00002034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 m = PyModule_Create(&mathmodule);
2036 if (m == NULL)
2037 goto finally;
Barry Warsawfc93f751996-12-17 00:47:03 +00002038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
2040 PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +00002041 PyModule_AddObject(m, "inf", PyFloat_FromDouble(m_inf()));
2042#if !defined(PY_NO_SHORT_FLOAT_REPR) || defined(Py_NAN)
2043 PyModule_AddObject(m, "nan", PyFloat_FromDouble(m_nan()));
2044#endif
Barry Warsawfc93f751996-12-17 00:47:03 +00002045
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +00002046 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002048}