blob: d2d461e096d57589bccffddcbe5c84dc0d34881b [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
226static double
227m_tgamma(double x)
228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 double absx, r, y, z, sqrtpow;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 /* special cases */
232 if (!Py_IS_FINITE(x)) {
233 if (Py_IS_NAN(x) || x > 0.0)
234 return x; /* tgamma(nan) = nan, tgamma(inf) = inf */
235 else {
236 errno = EDOM;
237 return Py_NAN; /* tgamma(-inf) = nan, invalid */
238 }
239 }
240 if (x == 0.0) {
241 errno = EDOM;
242 return 1.0/x; /* tgamma(+-0.0) = +-inf, divide-by-zero */
243 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 /* integer arguments */
246 if (x == floor(x)) {
247 if (x < 0.0) {
248 errno = EDOM; /* tgamma(n) = nan, invalid for */
249 return Py_NAN; /* negative integers n */
250 }
251 if (x <= NGAMMA_INTEGRAL)
252 return gamma_integral[(int)x - 1];
253 }
254 absx = fabs(x);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 /* tiny arguments: tgamma(x) ~ 1/x for x near 0 */
257 if (absx < 1e-20) {
258 r = 1.0/x;
259 if (Py_IS_INFINITY(r))
260 errno = ERANGE;
261 return r;
262 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 /* large arguments: assuming IEEE 754 doubles, tgamma(x) overflows for
265 x > 200, and underflows to +-0.0 for x < -200, not a negative
266 integer. */
267 if (absx > 200.0) {
268 if (x < 0.0) {
269 return 0.0/sinpi(x);
270 }
271 else {
272 errno = ERANGE;
273 return Py_HUGE_VAL;
274 }
275 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 y = absx + lanczos_g_minus_half;
278 /* compute error in sum */
279 if (absx > lanczos_g_minus_half) {
280 /* note: the correction can be foiled by an optimizing
281 compiler that (incorrectly) thinks that an expression like
282 a + b - a - b can be optimized to 0.0. This shouldn't
283 happen in a standards-conforming compiler. */
284 double q = y - absx;
285 z = q - lanczos_g_minus_half;
286 }
287 else {
288 double q = y - lanczos_g_minus_half;
289 z = q - absx;
290 }
291 z = z * lanczos_g / y;
292 if (x < 0.0) {
293 r = -pi / sinpi(absx) / absx * exp(y) / lanczos_sum(absx);
294 r -= z * r;
295 if (absx < 140.0) {
296 r /= pow(y, absx - 0.5);
297 }
298 else {
299 sqrtpow = pow(y, absx / 2.0 - 0.25);
300 r /= sqrtpow;
301 r /= sqrtpow;
302 }
303 }
304 else {
305 r = lanczos_sum(absx) / exp(y);
306 r += z * r;
307 if (absx < 140.0) {
308 r *= pow(y, absx - 0.5);
309 }
310 else {
311 sqrtpow = pow(y, absx / 2.0 - 0.25);
312 r *= sqrtpow;
313 r *= sqrtpow;
314 }
315 }
316 if (Py_IS_INFINITY(r))
317 errno = ERANGE;
318 return r;
Guido van Rossum8832b621991-12-16 15:44:24 +0000319}
320
Christian Heimes53876d92008-04-19 00:31:39 +0000321/*
Mark Dickinson05d2e082009-12-11 20:17:17 +0000322 lgamma: natural log of the absolute value of the Gamma function.
323 For large arguments, Lanczos' formula works extremely well here.
324*/
325
326static double
327m_lgamma(double x)
328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 double r, absx;
Mark Dickinson05d2e082009-12-11 20:17:17 +0000330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 /* special cases */
332 if (!Py_IS_FINITE(x)) {
333 if (Py_IS_NAN(x))
334 return x; /* lgamma(nan) = nan */
335 else
336 return Py_HUGE_VAL; /* lgamma(+-inf) = +inf */
337 }
Mark Dickinson05d2e082009-12-11 20:17:17 +0000338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 /* integer arguments */
340 if (x == floor(x) && x <= 2.0) {
341 if (x <= 0.0) {
342 errno = EDOM; /* lgamma(n) = inf, divide-by-zero for */
343 return Py_HUGE_VAL; /* integers n <= 0 */
344 }
345 else {
346 return 0.0; /* lgamma(1) = lgamma(2) = 0.0 */
347 }
348 }
Mark Dickinson05d2e082009-12-11 20:17:17 +0000349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 absx = fabs(x);
351 /* tiny arguments: lgamma(x) ~ -log(fabs(x)) for small x */
352 if (absx < 1e-20)
353 return -log(absx);
Mark Dickinson05d2e082009-12-11 20:17:17 +0000354
Mark Dickinson9c91eb82010-07-07 16:17:31 +0000355 /* Lanczos' formula. We could save a fraction of a ulp in accuracy by
356 having a second set of numerator coefficients for lanczos_sum that
357 absorbed the exp(-lanczos_g) term, and throwing out the lanczos_g
358 subtraction below; it's probably not worth it. */
359 r = log(lanczos_sum(absx)) - lanczos_g;
360 r += (absx - 0.5) * (log(absx + lanczos_g - 0.5) - 1);
361 if (x < 0.0)
362 /* Use reflection formula to get value for negative x. */
363 r = logpi - log(fabs(sinpi(absx))) - log(absx) - r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 if (Py_IS_INFINITY(r))
365 errno = ERANGE;
366 return r;
Mark Dickinson05d2e082009-12-11 20:17:17 +0000367}
368
Mark Dickinson45f992a2009-12-19 11:20:49 +0000369/*
370 Implementations of the error function erf(x) and the complementary error
371 function erfc(x).
372
373 Method: following 'Numerical Recipes' by Flannery, Press et. al. (2nd ed.,
374 Cambridge University Press), we use a series approximation for erf for
375 small x, and a continued fraction approximation for erfc(x) for larger x;
376 combined with the relations erf(-x) = -erf(x) and erfc(x) = 1.0 - erf(x),
377 this gives us erf(x) and erfc(x) for all x.
378
379 The series expansion used is:
380
381 erf(x) = x*exp(-x*x)/sqrt(pi) * [
382 2/1 + 4/3 x**2 + 8/15 x**4 + 16/105 x**6 + ...]
383
384 The coefficient of x**(2k-2) here is 4**k*factorial(k)/factorial(2*k).
385 This series converges well for smallish x, but slowly for larger x.
386
387 The continued fraction expansion used is:
388
389 erfc(x) = x*exp(-x*x)/sqrt(pi) * [1/(0.5 + x**2 -) 0.5/(2.5 + x**2 - )
390 3.0/(4.5 + x**2 - ) 7.5/(6.5 + x**2 - ) ...]
391
392 after the first term, the general term has the form:
393
394 k*(k-0.5)/(2*k+0.5 + x**2 - ...).
395
396 This expansion converges fast for larger x, but convergence becomes
397 infinitely slow as x approaches 0.0. The (somewhat naive) continued
398 fraction evaluation algorithm used below also risks overflow for large x;
399 but for large x, erfc(x) == 0.0 to within machine precision. (For
400 example, erfc(30.0) is approximately 2.56e-393).
401
402 Parameters: use series expansion for abs(x) < ERF_SERIES_CUTOFF and
403 continued fraction expansion for ERF_SERIES_CUTOFF <= abs(x) <
404 ERFC_CONTFRAC_CUTOFF. ERFC_SERIES_TERMS and ERFC_CONTFRAC_TERMS are the
405 numbers of terms to use for the relevant expansions. */
406
407#define ERF_SERIES_CUTOFF 1.5
408#define ERF_SERIES_TERMS 25
409#define ERFC_CONTFRAC_CUTOFF 30.0
410#define ERFC_CONTFRAC_TERMS 50
411
412/*
413 Error function, via power series.
414
415 Given a finite float x, return an approximation to erf(x).
416 Converges reasonably fast for small x.
417*/
418
419static double
420m_erf_series(double x)
421{
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000422 double x2, acc, fk, result;
423 int i, saved_errno;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 x2 = x * x;
426 acc = 0.0;
427 fk = (double)ERF_SERIES_TERMS + 0.5;
428 for (i = 0; i < ERF_SERIES_TERMS; i++) {
429 acc = 2.0 + x2 * acc / fk;
430 fk -= 1.0;
431 }
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000432 /* Make sure the exp call doesn't affect errno;
433 see m_erfc_contfrac for more. */
434 saved_errno = errno;
435 result = acc * x * exp(-x2) / sqrtpi;
436 errno = saved_errno;
437 return result;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000438}
439
440/*
441 Complementary error function, via continued fraction expansion.
442
443 Given a positive float x, return an approximation to erfc(x). Converges
444 reasonably fast for x large (say, x > 2.0), and should be safe from
445 overflow if x and nterms are not too large. On an IEEE 754 machine, with x
446 <= 30.0, we're safe up to nterms = 100. For x >= 30.0, erfc(x) is smaller
447 than the smallest representable nonzero float. */
448
449static double
450m_erfc_contfrac(double x)
451{
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000452 double x2, a, da, p, p_last, q, q_last, b, result;
453 int i, saved_errno;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 if (x >= ERFC_CONTFRAC_CUTOFF)
456 return 0.0;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 x2 = x*x;
459 a = 0.0;
460 da = 0.5;
461 p = 1.0; p_last = 0.0;
462 q = da + x2; q_last = 1.0;
463 for (i = 0; i < ERFC_CONTFRAC_TERMS; i++) {
464 double temp;
465 a += da;
466 da += 2.0;
467 b = da + x2;
468 temp = p; p = b*p - a*p_last; p_last = temp;
469 temp = q; q = b*q - a*q_last; q_last = temp;
470 }
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000471 /* Issue #8986: On some platforms, exp sets errno on underflow to zero;
472 save the current errno value so that we can restore it later. */
473 saved_errno = errno;
474 result = p / q * x * exp(-x2) / sqrtpi;
475 errno = saved_errno;
476 return result;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000477}
478
479/* Error function erf(x), for general x */
480
481static double
482m_erf(double x)
483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 double absx, cf;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 if (Py_IS_NAN(x))
487 return x;
488 absx = fabs(x);
489 if (absx < ERF_SERIES_CUTOFF)
490 return m_erf_series(x);
491 else {
492 cf = m_erfc_contfrac(absx);
493 return x > 0.0 ? 1.0 - cf : cf - 1.0;
494 }
Mark Dickinson45f992a2009-12-19 11:20:49 +0000495}
496
497/* Complementary error function erfc(x), for general x. */
498
499static double
500m_erfc(double x)
501{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 double absx, cf;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 if (Py_IS_NAN(x))
505 return x;
506 absx = fabs(x);
507 if (absx < ERF_SERIES_CUTOFF)
508 return 1.0 - m_erf_series(x);
509 else {
510 cf = m_erfc_contfrac(absx);
511 return x > 0.0 ? cf : 2.0 - cf;
512 }
Mark Dickinson45f992a2009-12-19 11:20:49 +0000513}
Mark Dickinson05d2e082009-12-11 20:17:17 +0000514
515/*
Christian Heimese57950f2008-04-21 13:08:03 +0000516 wrapper for atan2 that deals directly with special cases before
517 delegating to the platform libm for the remaining cases. This
518 is necessary to get consistent behaviour across platforms.
519 Windows, FreeBSD and alpha Tru64 are amongst platforms that don't
520 always follow C99.
521*/
522
523static double
524m_atan2(double y, double x)
525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 if (Py_IS_NAN(x) || Py_IS_NAN(y))
527 return Py_NAN;
528 if (Py_IS_INFINITY(y)) {
529 if (Py_IS_INFINITY(x)) {
530 if (copysign(1., x) == 1.)
531 /* atan2(+-inf, +inf) == +-pi/4 */
532 return copysign(0.25*Py_MATH_PI, y);
533 else
534 /* atan2(+-inf, -inf) == +-pi*3/4 */
535 return copysign(0.75*Py_MATH_PI, y);
536 }
537 /* atan2(+-inf, x) == +-pi/2 for finite x */
538 return copysign(0.5*Py_MATH_PI, y);
539 }
540 if (Py_IS_INFINITY(x) || y == 0.) {
541 if (copysign(1., x) == 1.)
542 /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */
543 return copysign(0., y);
544 else
545 /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */
546 return copysign(Py_MATH_PI, y);
547 }
548 return atan2(y, x);
Christian Heimese57950f2008-04-21 13:08:03 +0000549}
550
551/*
Mark Dickinsone675f082008-12-11 21:56:00 +0000552 Various platforms (Solaris, OpenBSD) do nonstandard things for log(0),
553 log(-ve), log(NaN). Here are wrappers for log and log10 that deal with
554 special values directly, passing positive non-special values through to
555 the system log/log10.
556 */
557
558static double
559m_log(double x)
560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 if (Py_IS_FINITE(x)) {
562 if (x > 0.0)
563 return log(x);
564 errno = EDOM;
565 if (x == 0.0)
566 return -Py_HUGE_VAL; /* log(0) = -inf */
567 else
568 return Py_NAN; /* log(-ve) = nan */
569 }
570 else if (Py_IS_NAN(x))
571 return x; /* log(nan) = nan */
572 else if (x > 0.0)
573 return x; /* log(inf) = inf */
574 else {
575 errno = EDOM;
576 return Py_NAN; /* log(-inf) = nan */
577 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000578}
579
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200580/*
581 log2: log to base 2.
582
583 Uses an algorithm that should:
584 (a) produce exact results for powers of 2, and
585 (b) be monotonic, assuming that the system log is monotonic.
586*/
587
588static double
589m_log2(double x)
590{
591 if (!Py_IS_FINITE(x)) {
592 if (Py_IS_NAN(x))
593 return x; /* log2(nan) = nan */
594 else if (x > 0.0)
595 return x; /* log2(+inf) = +inf */
596 else {
597 errno = EDOM;
598 return Py_NAN; /* log2(-inf) = nan, invalid-operation */
599 }
600 }
601
602 if (x > 0.0) {
603 double m;
604 int e;
605 m = frexp(x, &e);
606 /* We want log2(m * 2**e) == log(m) / log(2) + e. Care is needed when
607 * x is just greater than 1.0: in that case e is 1, log(m) is negative,
608 * and we get significant cancellation error from the addition of
609 * log(m) / log(2) to e. The slight rewrite of the expression below
610 * avoids this problem.
611 */
612 if (x >= 1.0) {
613 return log(2.0 * m) / log(2.0) + (e - 1);
614 }
615 else {
616 return log(m) / log(2.0) + e;
617 }
618 }
619 else if (x == 0.0) {
620 errno = EDOM;
621 return -Py_HUGE_VAL; /* log2(0) = -inf, divide-by-zero */
622 }
623 else {
624 errno = EDOM;
Mark Dickinson23442582011-05-09 08:05:00 +0100625 return Py_NAN; /* log2(-inf) = nan, invalid-operation */
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200626 }
627}
628
Mark Dickinsone675f082008-12-11 21:56:00 +0000629static double
630m_log10(double x)
631{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 if (Py_IS_FINITE(x)) {
633 if (x > 0.0)
634 return log10(x);
635 errno = EDOM;
636 if (x == 0.0)
637 return -Py_HUGE_VAL; /* log10(0) = -inf */
638 else
639 return Py_NAN; /* log10(-ve) = nan */
640 }
641 else if (Py_IS_NAN(x))
642 return x; /* log10(nan) = nan */
643 else if (x > 0.0)
644 return x; /* log10(inf) = inf */
645 else {
646 errno = EDOM;
647 return Py_NAN; /* log10(-inf) = nan */
648 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000649}
650
651
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000652/* Call is_error when errno != 0, and where x is the result libm
653 * returned. is_error will usually set up an exception and return
654 * true (1), but may return false (0) without setting up an exception.
655 */
656static int
657is_error(double x)
658{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 int result = 1; /* presumption of guilt */
660 assert(errno); /* non-zero errno is a precondition for calling */
661 if (errno == EDOM)
662 PyErr_SetString(PyExc_ValueError, "math domain error");
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 else if (errno == ERANGE) {
665 /* ANSI C generally requires libm functions to set ERANGE
666 * on overflow, but also generally *allows* them to set
667 * ERANGE on underflow too. There's no consistency about
668 * the latter across platforms.
669 * Alas, C99 never requires that errno be set.
670 * Here we suppress the underflow errors (libm functions
671 * should return a zero on underflow, and +- HUGE_VAL on
672 * overflow, so testing the result for zero suffices to
673 * distinguish the cases).
674 *
675 * On some platforms (Ubuntu/ia64) it seems that errno can be
676 * set to ERANGE for subnormal results that do *not* underflow
677 * to zero. So to be safe, we'll ignore ERANGE whenever the
678 * function result is less than one in absolute value.
679 */
680 if (fabs(x) < 1.0)
681 result = 0;
682 else
683 PyErr_SetString(PyExc_OverflowError,
684 "math range error");
685 }
686 else
687 /* Unexpected math error */
688 PyErr_SetFromErrno(PyExc_ValueError);
689 return result;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000690}
691
Mark Dickinsone675f082008-12-11 21:56:00 +0000692/*
Christian Heimes53876d92008-04-19 00:31:39 +0000693 math_1 is used to wrap a libm function f that takes a double
694 arguments and returns a double.
695
696 The error reporting follows these rules, which are designed to do
697 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
698 platforms.
699
700 - a NaN result from non-NaN inputs causes ValueError to be raised
701 - an infinite result from finite inputs causes OverflowError to be
702 raised if can_overflow is 1, or raises ValueError if can_overflow
703 is 0.
704 - if the result is finite and errno == EDOM then ValueError is
705 raised
706 - if the result is finite and nonzero and errno == ERANGE then
707 OverflowError is raised
708
709 The last rule is used to catch overflow on platforms which follow
710 C89 but for which HUGE_VAL is not an infinity.
711
712 For the majority of one-argument functions these rules are enough
713 to ensure that Python's functions behave as specified in 'Annex F'
714 of the C99 standard, with the 'invalid' and 'divide-by-zero'
715 floating-point exceptions mapping to Python's ValueError and the
716 'overflow' floating-point exception mapping to OverflowError.
717 math_1 only works for functions that don't have singularities *and*
718 the possibility of overflow; fortunately, that covers everything we
719 care about right now.
720*/
721
Barry Warsaw8b43b191996-12-09 22:32:36 +0000722static PyObject *
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000723math_1_to_whatever(PyObject *arg, double (*func) (double),
Christian Heimes53876d92008-04-19 00:31:39 +0000724 PyObject *(*from_double_func) (double),
725 int can_overflow)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000726{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 double x, r;
728 x = PyFloat_AsDouble(arg);
729 if (x == -1.0 && PyErr_Occurred())
730 return NULL;
731 errno = 0;
732 PyFPE_START_PROTECT("in math_1", return 0);
733 r = (*func)(x);
734 PyFPE_END_PROTECT(r);
735 if (Py_IS_NAN(r) && !Py_IS_NAN(x)) {
736 PyErr_SetString(PyExc_ValueError,
737 "math domain error"); /* invalid arg */
738 return NULL;
739 }
740 if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) {
741 if (can_overflow)
742 PyErr_SetString(PyExc_OverflowError,
743 "math range error"); /* overflow */
744 else
745 PyErr_SetString(PyExc_ValueError,
746 "math domain error"); /* singularity */
747 return NULL;
748 }
749 if (Py_IS_FINITE(r) && errno && is_error(r))
750 /* this branch unnecessary on most platforms */
751 return NULL;
Mark Dickinsonde429622008-05-01 00:19:23 +0000752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 return (*from_double_func)(r);
Christian Heimes53876d92008-04-19 00:31:39 +0000754}
755
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000756/* variant of math_1, to be used when the function being wrapped is known to
757 set errno properly (that is, errno = EDOM for invalid or divide-by-zero,
758 errno = ERANGE for overflow). */
759
760static PyObject *
761math_1a(PyObject *arg, double (*func) (double))
762{
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_1a", return 0);
769 r = (*func)(x);
770 PyFPE_END_PROTECT(r);
771 if (errno && is_error(r))
772 return NULL;
773 return PyFloat_FromDouble(r);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000774}
775
Christian Heimes53876d92008-04-19 00:31:39 +0000776/*
777 math_2 is used to wrap a libm function f that takes two double
778 arguments and returns a double.
779
780 The error reporting follows these rules, which are designed to do
781 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
782 platforms.
783
784 - a NaN result from non-NaN inputs causes ValueError to be raised
785 - an infinite result from finite inputs causes OverflowError to be
786 raised.
787 - if the result is finite and errno == EDOM then ValueError is
788 raised
789 - if the result is finite and nonzero and errno == ERANGE then
790 OverflowError is raised
791
792 The last rule is used to catch overflow on platforms which follow
793 C89 but for which HUGE_VAL is not an infinity.
794
795 For most two-argument functions (copysign, fmod, hypot, atan2)
796 these rules are enough to ensure that Python's functions behave as
797 specified in 'Annex F' of the C99 standard, with the 'invalid' and
798 'divide-by-zero' floating-point exceptions mapping to Python's
799 ValueError and the 'overflow' floating-point exception mapping to
800 OverflowError.
801*/
802
803static PyObject *
804math_1(PyObject *arg, double (*func) (double), int can_overflow)
805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow);
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000807}
808
809static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000810math_1_to_int(PyObject *arg, double (*func) (double), int can_overflow)
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 return math_1_to_whatever(arg, func, PyLong_FromDouble, can_overflow);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000813}
814
Barry Warsaw8b43b191996-12-09 22:32:36 +0000815static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +0000816math_2(PyObject *args, double (*func) (double, double), char *funcname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000817{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 PyObject *ox, *oy;
819 double x, y, r;
820 if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy))
821 return NULL;
822 x = PyFloat_AsDouble(ox);
823 y = PyFloat_AsDouble(oy);
824 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
825 return NULL;
826 errno = 0;
827 PyFPE_START_PROTECT("in math_2", return 0);
828 r = (*func)(x, y);
829 PyFPE_END_PROTECT(r);
830 if (Py_IS_NAN(r)) {
831 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
832 errno = EDOM;
833 else
834 errno = 0;
835 }
836 else if (Py_IS_INFINITY(r)) {
837 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
838 errno = ERANGE;
839 else
840 errno = 0;
841 }
842 if (errno && is_error(r))
843 return NULL;
844 else
845 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000846}
847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848#define FUNC1(funcname, func, can_overflow, docstring) \
849 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
850 return math_1(args, func, can_overflow); \
851 }\
852 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854#define FUNC1A(funcname, func, docstring) \
855 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
856 return math_1a(args, func); \
857 }\
858 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000859
Fred Drake40c48682000-07-03 18:11:56 +0000860#define FUNC2(funcname, func, docstring) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
862 return math_2(args, func, #funcname); \
863 }\
864 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000865
Christian Heimes53876d92008-04-19 00:31:39 +0000866FUNC1(acos, acos, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000867 "acos(x)\n\nReturn the arc cosine (measured in radians) of x.")
Mark Dickinsonf3718592009-12-21 15:27:41 +0000868FUNC1(acosh, m_acosh, 0,
Christian Heimes53876d92008-04-19 00:31:39 +0000869 "acosh(x)\n\nReturn the hyperbolic arc cosine (measured in radians) of x.")
870FUNC1(asin, asin, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000871 "asin(x)\n\nReturn the arc sine (measured in radians) of x.")
Mark Dickinsonf3718592009-12-21 15:27:41 +0000872FUNC1(asinh, m_asinh, 0,
Christian Heimes53876d92008-04-19 00:31:39 +0000873 "asinh(x)\n\nReturn the hyperbolic arc sine (measured in radians) of x.")
874FUNC1(atan, atan, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000875 "atan(x)\n\nReturn the arc tangent (measured in radians) of x.")
Christian Heimese57950f2008-04-21 13:08:03 +0000876FUNC2(atan2, m_atan2,
Tim Petersfe71f812001-08-07 22:10:00 +0000877 "atan2(y, x)\n\nReturn the arc tangent (measured in radians) of y/x.\n"
878 "Unlike atan(y/x), the signs of both x and y are considered.")
Mark Dickinsonf3718592009-12-21 15:27:41 +0000879FUNC1(atanh, m_atanh, 0,
Christian Heimes53876d92008-04-19 00:31:39 +0000880 "atanh(x)\n\nReturn the hyperbolic arc tangent (measured in radians) of x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +0000881
882static PyObject * math_ceil(PyObject *self, PyObject *number) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 static PyObject *ceil_str = NULL;
Mark Dickinson6d02d9c2010-07-02 16:05:15 +0000884 PyObject *method, *result;
Guido van Rossum13e05de2007-08-23 22:56:55 +0000885
Benjamin Petersonf751bc92010-07-02 13:46:42 +0000886 method = _PyObject_LookupSpecial(number, "__ceil__", &ceil_str);
887 if (method == NULL) {
888 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 return math_1_to_int(number, ceil, 0);
Benjamin Petersonf751bc92010-07-02 13:46:42 +0000891 }
Mark Dickinson6d02d9c2010-07-02 16:05:15 +0000892 result = PyObject_CallFunctionObjArgs(method, NULL);
893 Py_DECREF(method);
894 return result;
Guido van Rossum13e05de2007-08-23 22:56:55 +0000895}
896
897PyDoc_STRVAR(math_ceil_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 "ceil(x)\n\nReturn the ceiling of x as an int.\n"
899 "This is the smallest integral value >= x.");
Guido van Rossum13e05de2007-08-23 22:56:55 +0000900
Christian Heimes072c0f12008-01-03 23:01:04 +0000901FUNC2(copysign, copysign,
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000902 "copysign(x, y)\n\nReturn x with the sign of y.")
Christian Heimes53876d92008-04-19 00:31:39 +0000903FUNC1(cos, cos, 0,
904 "cos(x)\n\nReturn the cosine of x (measured in radians).")
905FUNC1(cosh, cosh, 1,
906 "cosh(x)\n\nReturn the hyperbolic cosine of x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +0000907FUNC1A(erf, m_erf,
908 "erf(x)\n\nError function at x.")
909FUNC1A(erfc, m_erfc,
910 "erfc(x)\n\nComplementary error function at x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000911FUNC1(exp, exp, 1,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000912 "exp(x)\n\nReturn e raised to the power of x.")
Mark Dickinson664b5112009-12-16 20:23:42 +0000913FUNC1(expm1, m_expm1, 1,
914 "expm1(x)\n\nReturn exp(x)-1.\n"
915 "This function avoids the loss of precision involved in the direct "
916 "evaluation of exp(x)-1 for small x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000917FUNC1(fabs, fabs, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000918 "fabs(x)\n\nReturn the absolute value of the float x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +0000919
920static PyObject * math_floor(PyObject *self, PyObject *number) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 static PyObject *floor_str = NULL;
Benjamin Petersonb0125892010-07-02 13:35:17 +0000922 PyObject *method, *result;
Guido van Rossum13e05de2007-08-23 22:56:55 +0000923
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +0000924 method = _PyObject_LookupSpecial(number, "__floor__", &floor_str);
925 if (method == NULL) {
926 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 return math_1_to_int(number, floor, 0);
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +0000929 }
Benjamin Petersonb0125892010-07-02 13:35:17 +0000930 result = PyObject_CallFunctionObjArgs(method, NULL);
931 Py_DECREF(method);
932 return result;
Guido van Rossum13e05de2007-08-23 22:56:55 +0000933}
934
935PyDoc_STRVAR(math_floor_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 "floor(x)\n\nReturn the floor of x as an int.\n"
937 "This is the largest integral value <= x.");
Guido van Rossum13e05de2007-08-23 22:56:55 +0000938
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000939FUNC1A(gamma, m_tgamma,
940 "gamma(x)\n\nGamma function at x.")
Mark Dickinson05d2e082009-12-11 20:17:17 +0000941FUNC1A(lgamma, m_lgamma,
942 "lgamma(x)\n\nNatural logarithm of absolute value of Gamma function at x.")
Mark Dickinsonbe64d952010-07-07 16:21:29 +0000943FUNC1(log1p, m_log1p, 0,
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000944 "log1p(x)\n\nReturn the natural logarithm of 1+x (base e).\n"
945 "The result is computed in a way which is accurate for x near zero.")
Christian Heimes53876d92008-04-19 00:31:39 +0000946FUNC1(sin, sin, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000947 "sin(x)\n\nReturn the sine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +0000948FUNC1(sinh, sinh, 1,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000949 "sinh(x)\n\nReturn the hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000950FUNC1(sqrt, sqrt, 0,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000951 "sqrt(x)\n\nReturn the square root of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000952FUNC1(tan, tan, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000953 "tan(x)\n\nReturn the tangent of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +0000954FUNC1(tanh, tanh, 0,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000955 "tanh(x)\n\nReturn the hyperbolic tangent of x.")
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000956
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000957/* Precision summation function as msum() by Raymond Hettinger in
958 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
959 enhanced with the exact partials sum and roundoff from Mark
960 Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
961 See those links for more details, proofs and other references.
962
963 Note 1: IEEE 754R floating point semantics are assumed,
964 but the current implementation does not re-establish special
965 value semantics across iterations (i.e. handling -Inf + Inf).
966
967 Note 2: No provision is made for intermediate overflow handling;
Georg Brandlf78e02b2008-06-10 17:40:04 +0000968 therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000969 sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
970 overflow of the first partial sum.
971
Benjamin Petersonfea6a942008-07-02 16:11:42 +0000972 Note 3: The intermediate values lo, yr, and hi are declared volatile so
973 aggressive compilers won't algebraically reduce lo to always be exactly 0.0.
Georg Brandlf78e02b2008-06-10 17:40:04 +0000974 Also, the volatile declaration forces the values to be stored in memory as
975 regular doubles instead of extended long precision (80-bit) values. This
Benjamin Petersonfea6a942008-07-02 16:11:42 +0000976 prevents double rounding because any addition or subtraction of two doubles
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 can be resolved exactly into double-sized hi and lo values. As long as the
Georg Brandlf78e02b2008-06-10 17:40:04 +0000978 hi value gets forced into a double before yr and lo are computed, the extra
979 bits in downstream extended precision operations (x87 for example) will be
980 exactly zero and therefore can be losslessly stored back into a double,
981 thereby preventing double rounding.
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000982
983 Note 4: A similar implementation is in Modules/cmathmodule.c.
984 Be sure to update both when making changes.
985
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000986 Note 5: The signature of math.fsum() differs from __builtin__.sum()
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000987 because the start argument doesn't make sense in the context of
988 accurate summation. Since the partials table is collapsed before
989 returning a result, sum(seq2, start=sum(seq1)) may not equal the
990 accurate result returned by sum(itertools.chain(seq1, seq2)).
991*/
992
993#define NUM_PARTIALS 32 /* initial partials array size, on stack */
994
995/* Extend the partials array p[] by doubling its size. */
996static int /* non-zero on error */
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000997_fsum_realloc(double **p_ptr, Py_ssize_t n,
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000998 double *ps, Py_ssize_t *m_ptr)
999{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 void *v = NULL;
1001 Py_ssize_t m = *m_ptr;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 m += m; /* double */
1004 if (n < m && m < (PY_SSIZE_T_MAX / sizeof(double))) {
1005 double *p = *p_ptr;
1006 if (p == ps) {
1007 v = PyMem_Malloc(sizeof(double) * m);
1008 if (v != NULL)
1009 memcpy(v, ps, sizeof(double) * n);
1010 }
1011 else
1012 v = PyMem_Realloc(p, sizeof(double) * m);
1013 }
1014 if (v == NULL) { /* size overflow or no memory */
1015 PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
1016 return 1;
1017 }
1018 *p_ptr = (double*) v;
1019 *m_ptr = m;
1020 return 0;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001021}
1022
1023/* Full precision summation of a sequence of floats.
1024
1025 def msum(iterable):
1026 partials = [] # sorted, non-overlapping partial sums
1027 for x in iterable:
Mark Dickinsonfdb0acc2010-06-25 20:22:24 +00001028 i = 0
1029 for y in partials:
1030 if abs(x) < abs(y):
1031 x, y = y, x
1032 hi = x + y
1033 lo = y - (hi - x)
1034 if lo:
1035 partials[i] = lo
1036 i += 1
1037 x = hi
1038 partials[i:] = [x]
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001039 return sum_exact(partials)
1040
1041 Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
1042 are exactly equal to x+y. The inner loop applies hi/lo summation to each
1043 partial so that the list of partial sums remains exact.
1044
1045 Sum_exact() adds the partial sums exactly and correctly rounds the final
1046 result (using the round-half-to-even rule). The items in partials remain
1047 non-zero, non-special, non-overlapping and strictly increasing in
1048 magnitude, but possibly not all having the same sign.
1049
1050 Depends on IEEE 754 arithmetic guarantees and half-even rounding.
1051*/
1052
1053static PyObject*
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001054math_fsum(PyObject *self, PyObject *seq)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001055{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 PyObject *item, *iter, *sum = NULL;
1057 Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
1058 double x, y, t, ps[NUM_PARTIALS], *p = ps;
1059 double xsave, special_sum = 0.0, inf_sum = 0.0;
1060 volatile double hi, yr, lo;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 iter = PyObject_GetIter(seq);
1063 if (iter == NULL)
1064 return NULL;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 for(;;) { /* for x in iterable */
1069 assert(0 <= n && n <= m);
1070 assert((m == NUM_PARTIALS && p == ps) ||
1071 (m > NUM_PARTIALS && p != NULL));
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 item = PyIter_Next(iter);
1074 if (item == NULL) {
1075 if (PyErr_Occurred())
1076 goto _fsum_error;
1077 break;
1078 }
1079 x = PyFloat_AsDouble(item);
1080 Py_DECREF(item);
1081 if (PyErr_Occurred())
1082 goto _fsum_error;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 xsave = x;
1085 for (i = j = 0; j < n; j++) { /* for y in partials */
1086 y = p[j];
1087 if (fabs(x) < fabs(y)) {
1088 t = x; x = y; y = t;
1089 }
1090 hi = x + y;
1091 yr = hi - x;
1092 lo = y - yr;
1093 if (lo != 0.0)
1094 p[i++] = lo;
1095 x = hi;
1096 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 n = i; /* ps[i:] = [x] */
1099 if (x != 0.0) {
1100 if (! Py_IS_FINITE(x)) {
1101 /* a nonfinite x could arise either as
1102 a result of intermediate overflow, or
1103 as a result of a nan or inf in the
1104 summands */
1105 if (Py_IS_FINITE(xsave)) {
1106 PyErr_SetString(PyExc_OverflowError,
1107 "intermediate overflow in fsum");
1108 goto _fsum_error;
1109 }
1110 if (Py_IS_INFINITY(xsave))
1111 inf_sum += xsave;
1112 special_sum += xsave;
1113 /* reset partials */
1114 n = 0;
1115 }
1116 else if (n >= m && _fsum_realloc(&p, n, ps, &m))
1117 goto _fsum_error;
1118 else
1119 p[n++] = x;
1120 }
1121 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 if (special_sum != 0.0) {
1124 if (Py_IS_NAN(inf_sum))
1125 PyErr_SetString(PyExc_ValueError,
1126 "-inf + inf in fsum");
1127 else
1128 sum = PyFloat_FromDouble(special_sum);
1129 goto _fsum_error;
1130 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 hi = 0.0;
1133 if (n > 0) {
1134 hi = p[--n];
1135 /* sum_exact(ps, hi) from the top, stop when the sum becomes
1136 inexact. */
1137 while (n > 0) {
1138 x = hi;
1139 y = p[--n];
1140 assert(fabs(y) < fabs(x));
1141 hi = x + y;
1142 yr = hi - x;
1143 lo = y - yr;
1144 if (lo != 0.0)
1145 break;
1146 }
1147 /* Make half-even rounding work across multiple partials.
1148 Needed so that sum([1e-16, 1, 1e16]) will round-up the last
1149 digit to two instead of down to zero (the 1e-16 makes the 1
1150 slightly closer to two). With a potential 1 ULP rounding
1151 error fixed-up, math.fsum() can guarantee commutativity. */
1152 if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
1153 (lo > 0.0 && p[n-1] > 0.0))) {
1154 y = lo * 2.0;
1155 x = hi + y;
1156 yr = x - hi;
1157 if (y == yr)
1158 hi = x;
1159 }
1160 }
1161 sum = PyFloat_FromDouble(hi);
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001162
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001163_fsum_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 PyFPE_END_PROTECT(hi)
1165 Py_DECREF(iter);
1166 if (p != ps)
1167 PyMem_Free(p);
1168 return sum;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001169}
1170
1171#undef NUM_PARTIALS
1172
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001173PyDoc_STRVAR(math_fsum_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001174"fsum(iterable)\n\n\
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001175Return an accurate floating point sum of values in the iterable.\n\
1176Assumes IEEE-754 floating point arithmetic.");
1177
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001178/* Return the smallest integer k such that n < 2**k, or 0 if n == 0.
1179 * Equivalent to floor(lg(x))+1. Also equivalent to: bitwidth_of_type -
1180 * count_leading_zero_bits(x)
1181 */
1182
1183/* XXX: This routine does more or less the same thing as
1184 * bits_in_digit() in Objects/longobject.c. Someday it would be nice to
1185 * consolidate them. On BSD, there's a library function called fls()
1186 * that we could use, and GCC provides __builtin_clz().
1187 */
1188
1189static unsigned long
1190bit_length(unsigned long n)
1191{
1192 unsigned long len = 0;
1193 while (n != 0) {
1194 ++len;
1195 n >>= 1;
1196 }
1197 return len;
1198}
1199
1200static unsigned long
1201count_set_bits(unsigned long n)
1202{
1203 unsigned long count = 0;
1204 while (n != 0) {
1205 ++count;
1206 n &= n - 1; /* clear least significant bit */
1207 }
1208 return count;
1209}
1210
1211/* Divide-and-conquer factorial algorithm
1212 *
1213 * Based on the formula and psuedo-code provided at:
1214 * http://www.luschny.de/math/factorial/binarysplitfact.html
1215 *
1216 * Faster algorithms exist, but they're more complicated and depend on
Ezio Melotti9527afd2010-07-08 15:03:02 +00001217 * a fast prime factorization algorithm.
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001218 *
1219 * Notes on the algorithm
1220 * ----------------------
1221 *
1222 * factorial(n) is written in the form 2**k * m, with m odd. k and m are
1223 * computed separately, and then combined using a left shift.
1224 *
1225 * The function factorial_odd_part computes the odd part m (i.e., the greatest
1226 * odd divisor) of factorial(n), using the formula:
1227 *
1228 * factorial_odd_part(n) =
1229 *
1230 * product_{i >= 0} product_{0 < j <= n / 2**i, j odd} j
1231 *
1232 * Example: factorial_odd_part(20) =
1233 *
1234 * (1) *
1235 * (1) *
1236 * (1 * 3 * 5) *
1237 * (1 * 3 * 5 * 7 * 9)
1238 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1239 *
1240 * Here i goes from large to small: the first term corresponds to i=4 (any
1241 * larger i gives an empty product), and the last term corresponds to i=0.
1242 * Each term can be computed from the last by multiplying by the extra odd
1243 * numbers required: e.g., to get from the penultimate term to the last one,
1244 * we multiply by (11 * 13 * 15 * 17 * 19).
1245 *
1246 * To see a hint of why this formula works, here are the same numbers as above
1247 * but with the even parts (i.e., the appropriate powers of 2) included. For
1248 * each subterm in the product for i, we multiply that subterm by 2**i:
1249 *
1250 * factorial(20) =
1251 *
1252 * (16) *
1253 * (8) *
1254 * (4 * 12 * 20) *
1255 * (2 * 6 * 10 * 14 * 18) *
1256 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1257 *
1258 * The factorial_partial_product function computes the product of all odd j in
1259 * range(start, stop) for given start and stop. It's used to compute the
1260 * partial products like (11 * 13 * 15 * 17 * 19) in the example above. It
1261 * operates recursively, repeatedly splitting the range into two roughly equal
1262 * pieces until the subranges are small enough to be computed using only C
1263 * integer arithmetic.
1264 *
1265 * The two-valuation k (i.e., the exponent of the largest power of 2 dividing
1266 * the factorial) is computed independently in the main math_factorial
1267 * function. By standard results, its value is:
1268 *
1269 * two_valuation = n//2 + n//4 + n//8 + ....
1270 *
1271 * It can be shown (e.g., by complete induction on n) that two_valuation is
1272 * equal to n - count_set_bits(n), where count_set_bits(n) gives the number of
1273 * '1'-bits in the binary expansion of n.
1274 */
1275
1276/* factorial_partial_product: Compute product(range(start, stop, 2)) using
1277 * divide and conquer. Assumes start and stop are odd and stop > start.
1278 * max_bits must be >= bit_length(stop - 2). */
1279
1280static PyObject *
1281factorial_partial_product(unsigned long start, unsigned long stop,
1282 unsigned long max_bits)
1283{
1284 unsigned long midpoint, num_operands;
1285 PyObject *left = NULL, *right = NULL, *result = NULL;
1286
1287 /* If the return value will fit an unsigned long, then we can
1288 * multiply in a tight, fast loop where each multiply is O(1).
1289 * Compute an upper bound on the number of bits required to store
1290 * the answer.
1291 *
1292 * Storing some integer z requires floor(lg(z))+1 bits, which is
1293 * conveniently the value returned by bit_length(z). The
1294 * product x*y will require at most
1295 * bit_length(x) + bit_length(y) bits to store, based
1296 * on the idea that lg product = lg x + lg y.
1297 *
1298 * We know that stop - 2 is the largest number to be multiplied. From
1299 * there, we have: bit_length(answer) <= num_operands *
1300 * bit_length(stop - 2)
1301 */
1302
1303 num_operands = (stop - start) / 2;
1304 /* The "num_operands <= 8 * SIZEOF_LONG" check guards against the
1305 * unlikely case of an overflow in num_operands * max_bits. */
1306 if (num_operands <= 8 * SIZEOF_LONG &&
1307 num_operands * max_bits <= 8 * SIZEOF_LONG) {
1308 unsigned long j, total;
1309 for (total = start, j = start + 2; j < stop; j += 2)
1310 total *= j;
1311 return PyLong_FromUnsignedLong(total);
1312 }
1313
1314 /* find midpoint of range(start, stop), rounded up to next odd number. */
1315 midpoint = (start + num_operands) | 1;
1316 left = factorial_partial_product(start, midpoint,
1317 bit_length(midpoint - 2));
1318 if (left == NULL)
1319 goto error;
1320 right = factorial_partial_product(midpoint, stop, max_bits);
1321 if (right == NULL)
1322 goto error;
1323 result = PyNumber_Multiply(left, right);
1324
1325 error:
1326 Py_XDECREF(left);
1327 Py_XDECREF(right);
1328 return result;
1329}
1330
1331/* factorial_odd_part: compute the odd part of factorial(n). */
1332
1333static PyObject *
1334factorial_odd_part(unsigned long n)
1335{
1336 long i;
1337 unsigned long v, lower, upper;
1338 PyObject *partial, *tmp, *inner, *outer;
1339
1340 inner = PyLong_FromLong(1);
1341 if (inner == NULL)
1342 return NULL;
1343 outer = inner;
1344 Py_INCREF(outer);
1345
1346 upper = 3;
1347 for (i = bit_length(n) - 2; i >= 0; i--) {
1348 v = n >> i;
1349 if (v <= 2)
1350 continue;
1351 lower = upper;
1352 /* (v + 1) | 1 = least odd integer strictly larger than n / 2**i */
1353 upper = (v + 1) | 1;
1354 /* Here inner is the product of all odd integers j in the range (0,
1355 n/2**(i+1)]. The factorial_partial_product call below gives the
1356 product of all odd integers j in the range (n/2**(i+1), n/2**i]. */
1357 partial = factorial_partial_product(lower, upper, bit_length(upper-2));
1358 /* inner *= partial */
1359 if (partial == NULL)
1360 goto error;
1361 tmp = PyNumber_Multiply(inner, partial);
1362 Py_DECREF(partial);
1363 if (tmp == NULL)
1364 goto error;
1365 Py_DECREF(inner);
1366 inner = tmp;
1367 /* Now inner is the product of all odd integers j in the range (0,
1368 n/2**i], giving the inner product in the formula above. */
1369
1370 /* outer *= inner; */
1371 tmp = PyNumber_Multiply(outer, inner);
1372 if (tmp == NULL)
1373 goto error;
1374 Py_DECREF(outer);
1375 outer = tmp;
1376 }
1377
1378 goto done;
1379
1380 error:
1381 Py_DECREF(outer);
1382 done:
1383 Py_DECREF(inner);
1384 return outer;
1385}
1386
1387/* Lookup table for small factorial values */
1388
1389static const unsigned long SmallFactorials[] = {
1390 1, 1, 2, 6, 24, 120, 720, 5040, 40320,
1391 362880, 3628800, 39916800, 479001600,
1392#if SIZEOF_LONG >= 8
1393 6227020800, 87178291200, 1307674368000,
1394 20922789888000, 355687428096000, 6402373705728000,
1395 121645100408832000, 2432902008176640000
1396#endif
1397};
1398
Barry Warsaw8b43b191996-12-09 22:32:36 +00001399static PyObject *
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001400math_factorial(PyObject *self, PyObject *arg)
1401{
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001402 long x;
1403 PyObject *result, *odd_part, *two_valuation;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 if (PyFloat_Check(arg)) {
1406 PyObject *lx;
1407 double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
1408 if (!(Py_IS_FINITE(dx) && dx == floor(dx))) {
1409 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001410 "factorial() only accepts integral values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 return NULL;
1412 }
1413 lx = PyLong_FromDouble(dx);
1414 if (lx == NULL)
1415 return NULL;
1416 x = PyLong_AsLong(lx);
1417 Py_DECREF(lx);
1418 }
1419 else
1420 x = PyLong_AsLong(arg);
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 if (x == -1 && PyErr_Occurred())
1423 return NULL;
1424 if (x < 0) {
1425 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001426 "factorial() not defined for negative values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 return NULL;
1428 }
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001429
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001430 /* use lookup table if x is small */
1431 if (x < (long)(sizeof(SmallFactorials)/sizeof(SmallFactorials[0])))
1432 return PyLong_FromUnsignedLong(SmallFactorials[x]);
1433
1434 /* else express in the form odd_part * 2**two_valuation, and compute as
1435 odd_part << two_valuation. */
1436 odd_part = factorial_odd_part(x);
1437 if (odd_part == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 return NULL;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001439 two_valuation = PyLong_FromLong(x - count_set_bits(x));
1440 if (two_valuation == NULL) {
1441 Py_DECREF(odd_part);
1442 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 }
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001444 result = PyNumber_Lshift(odd_part, two_valuation);
1445 Py_DECREF(two_valuation);
1446 Py_DECREF(odd_part);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 return result;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001448}
1449
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001450PyDoc_STRVAR(math_factorial_doc,
1451"factorial(x) -> Integral\n"
1452"\n"
1453"Find x!. Raise a ValueError if x is negative or non-integral.");
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001454
1455static PyObject *
Christian Heimes400adb02008-02-01 08:12:03 +00001456math_trunc(PyObject *self, PyObject *number)
1457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 static PyObject *trunc_str = NULL;
Benjamin Petersonb0125892010-07-02 13:35:17 +00001459 PyObject *trunc, *result;
Christian Heimes400adb02008-02-01 08:12:03 +00001460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 if (Py_TYPE(number)->tp_dict == NULL) {
1462 if (PyType_Ready(Py_TYPE(number)) < 0)
1463 return NULL;
1464 }
Christian Heimes400adb02008-02-01 08:12:03 +00001465
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001466 trunc = _PyObject_LookupSpecial(number, "__trunc__", &trunc_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 if (trunc == NULL) {
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001468 if (!PyErr_Occurred())
1469 PyErr_Format(PyExc_TypeError,
1470 "type %.100s doesn't define __trunc__ method",
1471 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 return NULL;
1473 }
Benjamin Petersonb0125892010-07-02 13:35:17 +00001474 result = PyObject_CallFunctionObjArgs(trunc, NULL);
1475 Py_DECREF(trunc);
1476 return result;
Christian Heimes400adb02008-02-01 08:12:03 +00001477}
1478
1479PyDoc_STRVAR(math_trunc_doc,
1480"trunc(x:Real) -> Integral\n"
1481"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001482"Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.");
Christian Heimes400adb02008-02-01 08:12:03 +00001483
1484static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001485math_frexp(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 int i;
1488 double x = PyFloat_AsDouble(arg);
1489 if (x == -1.0 && PyErr_Occurred())
1490 return NULL;
1491 /* deal with special cases directly, to sidestep platform
1492 differences */
1493 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
1494 i = 0;
1495 }
1496 else {
1497 PyFPE_START_PROTECT("in math_frexp", return 0);
1498 x = frexp(x, &i);
1499 PyFPE_END_PROTECT(x);
1500 }
1501 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001502}
1503
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001504PyDoc_STRVAR(math_frexp_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001505"frexp(x)\n"
1506"\n"
1507"Return the mantissa and exponent of x, as pair (m, e).\n"
1508"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 +00001509"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 +00001510
Barry Warsaw8b43b191996-12-09 22:32:36 +00001511static PyObject *
Fred Drake40c48682000-07-03 18:11:56 +00001512math_ldexp(PyObject *self, PyObject *args)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001513{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 double x, r;
1515 PyObject *oexp;
1516 long exp;
1517 int overflow;
1518 if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp))
1519 return NULL;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 if (PyLong_Check(oexp)) {
1522 /* on overflow, replace exponent with either LONG_MAX
1523 or LONG_MIN, depending on the sign. */
1524 exp = PyLong_AsLongAndOverflow(oexp, &overflow);
1525 if (exp == -1 && PyErr_Occurred())
1526 return NULL;
1527 if (overflow)
1528 exp = overflow < 0 ? LONG_MIN : LONG_MAX;
1529 }
1530 else {
1531 PyErr_SetString(PyExc_TypeError,
1532 "Expected an int or long as second argument "
1533 "to ldexp.");
1534 return NULL;
1535 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 if (x == 0. || !Py_IS_FINITE(x)) {
1538 /* NaNs, zeros and infinities are returned unchanged */
1539 r = x;
1540 errno = 0;
1541 } else if (exp > INT_MAX) {
1542 /* overflow */
1543 r = copysign(Py_HUGE_VAL, x);
1544 errno = ERANGE;
1545 } else if (exp < INT_MIN) {
1546 /* underflow to +-0 */
1547 r = copysign(0., x);
1548 errno = 0;
1549 } else {
1550 errno = 0;
1551 PyFPE_START_PROTECT("in math_ldexp", return 0);
1552 r = ldexp(x, (int)exp);
1553 PyFPE_END_PROTECT(r);
1554 if (Py_IS_INFINITY(r))
1555 errno = ERANGE;
1556 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 if (errno && is_error(r))
1559 return NULL;
1560 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001561}
1562
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001563PyDoc_STRVAR(math_ldexp_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001564"ldexp(x, i)\n\n\
1565Return x * (2**i).");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001566
Barry Warsaw8b43b191996-12-09 22:32:36 +00001567static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001568math_modf(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001569{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 double y, x = PyFloat_AsDouble(arg);
1571 if (x == -1.0 && PyErr_Occurred())
1572 return NULL;
1573 /* some platforms don't do the right thing for NaNs and
1574 infinities, so we take care of special cases directly. */
1575 if (!Py_IS_FINITE(x)) {
1576 if (Py_IS_INFINITY(x))
1577 return Py_BuildValue("(dd)", copysign(0., x), x);
1578 else if (Py_IS_NAN(x))
1579 return Py_BuildValue("(dd)", x, x);
1580 }
Christian Heimesa342c012008-04-20 21:01:16 +00001581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 errno = 0;
1583 PyFPE_START_PROTECT("in math_modf", return 0);
1584 x = modf(x, &y);
1585 PyFPE_END_PROTECT(x);
1586 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001587}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001588
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001589PyDoc_STRVAR(math_modf_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001590"modf(x)\n"
1591"\n"
1592"Return the fractional and integer parts of x. Both results carry the sign\n"
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001593"of x and are floats.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001594
Tim Peters78526162001-09-05 00:53:45 +00001595/* A decent logarithm is easy to compute even for huge longs, but libm can't
1596 do that by itself -- loghelper can. func is log or log10, and name is
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00001597 "log" or "log10". Note that overflow of the result isn't possible: a long
1598 can contain no more than INT_MAX * SHIFT bits, so has value certainly less
1599 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 +00001600 small enough to fit in an IEEE single. log and log10 are even smaller.
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00001601 However, intermediate overflow is possible for a long if the number of bits
1602 in that long is larger than PY_SSIZE_T_MAX. */
Tim Peters78526162001-09-05 00:53:45 +00001603
1604static PyObject*
Thomas Wouters89f507f2006-12-13 04:49:30 +00001605loghelper(PyObject* arg, double (*func)(double), char *funcname)
Tim Peters78526162001-09-05 00:53:45 +00001606{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 /* If it is long, do it ourselves. */
1608 if (PyLong_Check(arg)) {
Mark Dickinsonc6037172010-09-29 19:06:36 +00001609 double x, result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 Py_ssize_t e;
Mark Dickinsonc6037172010-09-29 19:06:36 +00001611
1612 /* Negative or zero inputs give a ValueError. */
1613 if (Py_SIZE(arg) <= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 PyErr_SetString(PyExc_ValueError,
1615 "math domain error");
1616 return NULL;
1617 }
Mark Dickinsonfa41e602010-09-28 07:22:27 +00001618
Mark Dickinsonc6037172010-09-29 19:06:36 +00001619 x = PyLong_AsDouble(arg);
1620 if (x == -1.0 && PyErr_Occurred()) {
1621 if (!PyErr_ExceptionMatches(PyExc_OverflowError))
1622 return NULL;
1623 /* Here the conversion to double overflowed, but it's possible
1624 to compute the log anyway. Clear the exception and continue. */
1625 PyErr_Clear();
1626 x = _PyLong_Frexp((PyLongObject *)arg, &e);
1627 if (x == -1.0 && PyErr_Occurred())
1628 return NULL;
1629 /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */
1630 result = func(x) + func(2.0) * e;
1631 }
1632 else
1633 /* Successfully converted x to a double. */
1634 result = func(x);
1635 return PyFloat_FromDouble(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 }
Tim Peters78526162001-09-05 00:53:45 +00001637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 /* Else let libm handle it by itself. */
1639 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +00001640}
1641
1642static PyObject *
1643math_log(PyObject *self, PyObject *args)
1644{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 PyObject *arg;
1646 PyObject *base = NULL;
1647 PyObject *num, *den;
1648 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base))
1651 return NULL;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 num = loghelper(arg, m_log, "log");
1654 if (num == NULL || base == NULL)
1655 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 den = loghelper(base, m_log, "log");
1658 if (den == NULL) {
1659 Py_DECREF(num);
1660 return NULL;
1661 }
Raymond Hettinger866964c2002-12-14 19:51:34 +00001662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 ans = PyNumber_TrueDivide(num, den);
1664 Py_DECREF(num);
1665 Py_DECREF(den);
1666 return ans;
Tim Peters78526162001-09-05 00:53:45 +00001667}
1668
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001669PyDoc_STRVAR(math_log_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001670"log(x[, base])\n\n\
1671Return the logarithm of x to the given base.\n\
Raymond Hettinger866964c2002-12-14 19:51:34 +00001672If the base not specified, returns the natural logarithm (base e) of x.");
Tim Peters78526162001-09-05 00:53:45 +00001673
1674static PyObject *
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001675math_log2(PyObject *self, PyObject *arg)
1676{
1677 return loghelper(arg, m_log2, "log2");
1678}
1679
1680PyDoc_STRVAR(math_log2_doc,
1681"log2(x)\n\nReturn the base 2 logarithm of x.");
1682
1683static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001684math_log10(PyObject *self, PyObject *arg)
Tim Peters78526162001-09-05 00:53:45 +00001685{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 return loghelper(arg, m_log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +00001687}
1688
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001689PyDoc_STRVAR(math_log10_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001690"log10(x)\n\nReturn the base 10 logarithm of x.");
Tim Peters78526162001-09-05 00:53:45 +00001691
Christian Heimes53876d92008-04-19 00:31:39 +00001692static PyObject *
1693math_fmod(PyObject *self, PyObject *args)
1694{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 PyObject *ox, *oy;
1696 double r, x, y;
1697 if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy))
1698 return NULL;
1699 x = PyFloat_AsDouble(ox);
1700 y = PyFloat_AsDouble(oy);
1701 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1702 return NULL;
1703 /* fmod(x, +/-Inf) returns x for finite x. */
1704 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
1705 return PyFloat_FromDouble(x);
1706 errno = 0;
1707 PyFPE_START_PROTECT("in math_fmod", return 0);
1708 r = fmod(x, y);
1709 PyFPE_END_PROTECT(r);
1710 if (Py_IS_NAN(r)) {
1711 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1712 errno = EDOM;
1713 else
1714 errno = 0;
1715 }
1716 if (errno && is_error(r))
1717 return NULL;
1718 else
1719 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00001720}
1721
1722PyDoc_STRVAR(math_fmod_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001723"fmod(x, y)\n\nReturn fmod(x, y), according to platform C."
Christian Heimes53876d92008-04-19 00:31:39 +00001724" x % y may differ.");
1725
1726static PyObject *
1727math_hypot(PyObject *self, PyObject *args)
1728{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 PyObject *ox, *oy;
1730 double r, x, y;
1731 if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy))
1732 return NULL;
1733 x = PyFloat_AsDouble(ox);
1734 y = PyFloat_AsDouble(oy);
1735 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1736 return NULL;
1737 /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */
1738 if (Py_IS_INFINITY(x))
1739 return PyFloat_FromDouble(fabs(x));
1740 if (Py_IS_INFINITY(y))
1741 return PyFloat_FromDouble(fabs(y));
1742 errno = 0;
1743 PyFPE_START_PROTECT("in math_hypot", return 0);
1744 r = hypot(x, y);
1745 PyFPE_END_PROTECT(r);
1746 if (Py_IS_NAN(r)) {
1747 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1748 errno = EDOM;
1749 else
1750 errno = 0;
1751 }
1752 else if (Py_IS_INFINITY(r)) {
1753 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
1754 errno = ERANGE;
1755 else
1756 errno = 0;
1757 }
1758 if (errno && is_error(r))
1759 return NULL;
1760 else
1761 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00001762}
1763
1764PyDoc_STRVAR(math_hypot_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001765"hypot(x, y)\n\nReturn the Euclidean distance, sqrt(x*x + y*y).");
Christian Heimes53876d92008-04-19 00:31:39 +00001766
1767/* pow can't use math_2, but needs its own wrapper: the problem is
1768 that an infinite result can arise either as a result of overflow
1769 (in which case OverflowError should be raised) or as a result of
1770 e.g. 0.**-5. (for which ValueError needs to be raised.)
1771*/
1772
1773static PyObject *
1774math_pow(PyObject *self, PyObject *args)
1775{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 PyObject *ox, *oy;
1777 double r, x, y;
1778 int odd_y;
Christian Heimes53876d92008-04-19 00:31:39 +00001779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy))
1781 return NULL;
1782 x = PyFloat_AsDouble(ox);
1783 y = PyFloat_AsDouble(oy);
1784 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1785 return NULL;
Christian Heimesa342c012008-04-20 21:01:16 +00001786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 /* deal directly with IEEE specials, to cope with problems on various
1788 platforms whose semantics don't exactly match C99 */
1789 r = 0.; /* silence compiler warning */
1790 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
1791 errno = 0;
1792 if (Py_IS_NAN(x))
1793 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
1794 else if (Py_IS_NAN(y))
1795 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
1796 else if (Py_IS_INFINITY(x)) {
1797 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
1798 if (y > 0.)
1799 r = odd_y ? x : fabs(x);
1800 else if (y == 0.)
1801 r = 1.;
1802 else /* y < 0. */
1803 r = odd_y ? copysign(0., x) : 0.;
1804 }
1805 else if (Py_IS_INFINITY(y)) {
1806 if (fabs(x) == 1.0)
1807 r = 1.;
1808 else if (y > 0. && fabs(x) > 1.0)
1809 r = y;
1810 else if (y < 0. && fabs(x) < 1.0) {
1811 r = -y; /* result is +inf */
1812 if (x == 0.) /* 0**-inf: divide-by-zero */
1813 errno = EDOM;
1814 }
1815 else
1816 r = 0.;
1817 }
1818 }
1819 else {
1820 /* let libm handle finite**finite */
1821 errno = 0;
1822 PyFPE_START_PROTECT("in math_pow", return 0);
1823 r = pow(x, y);
1824 PyFPE_END_PROTECT(r);
1825 /* a NaN result should arise only from (-ve)**(finite
1826 non-integer); in this case we want to raise ValueError. */
1827 if (!Py_IS_FINITE(r)) {
1828 if (Py_IS_NAN(r)) {
1829 errno = EDOM;
1830 }
1831 /*
1832 an infinite result here arises either from:
1833 (A) (+/-0.)**negative (-> divide-by-zero)
1834 (B) overflow of x**y with x and y finite
1835 */
1836 else if (Py_IS_INFINITY(r)) {
1837 if (x == 0.)
1838 errno = EDOM;
1839 else
1840 errno = ERANGE;
1841 }
1842 }
1843 }
Christian Heimes53876d92008-04-19 00:31:39 +00001844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 if (errno && is_error(r))
1846 return NULL;
1847 else
1848 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00001849}
1850
1851PyDoc_STRVAR(math_pow_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001852"pow(x, y)\n\nReturn x**y (x to the power of y).");
Christian Heimes53876d92008-04-19 00:31:39 +00001853
Christian Heimes072c0f12008-01-03 23:01:04 +00001854static const double degToRad = Py_MATH_PI / 180.0;
1855static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001856
1857static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001858math_degrees(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001859{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 double x = PyFloat_AsDouble(arg);
1861 if (x == -1.0 && PyErr_Occurred())
1862 return NULL;
1863 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001864}
1865
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001866PyDoc_STRVAR(math_degrees_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001867"degrees(x)\n\n\
1868Convert angle x from radians to degrees.");
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001869
1870static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001871math_radians(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001872{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 double x = PyFloat_AsDouble(arg);
1874 if (x == -1.0 && PyErr_Occurred())
1875 return NULL;
1876 return PyFloat_FromDouble(x * degToRad);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001877}
1878
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001879PyDoc_STRVAR(math_radians_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001880"radians(x)\n\n\
1881Convert angle x from degrees to radians.");
Tim Peters78526162001-09-05 00:53:45 +00001882
Christian Heimes072c0f12008-01-03 23:01:04 +00001883static PyObject *
Mark Dickinson8e0c9962010-07-11 17:38:24 +00001884math_isfinite(PyObject *self, PyObject *arg)
1885{
1886 double x = PyFloat_AsDouble(arg);
1887 if (x == -1.0 && PyErr_Occurred())
1888 return NULL;
1889 return PyBool_FromLong((long)Py_IS_FINITE(x));
1890}
1891
1892PyDoc_STRVAR(math_isfinite_doc,
1893"isfinite(x) -> bool\n\n\
Mark Dickinson226f5442010-07-11 18:13:41 +00001894Return True if x is neither an infinity nor a NaN, and False otherwise.");
Mark Dickinson8e0c9962010-07-11 17:38:24 +00001895
1896static PyObject *
Christian Heimes072c0f12008-01-03 23:01:04 +00001897math_isnan(PyObject *self, PyObject *arg)
1898{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 double x = PyFloat_AsDouble(arg);
1900 if (x == -1.0 && PyErr_Occurred())
1901 return NULL;
1902 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00001903}
1904
1905PyDoc_STRVAR(math_isnan_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001906"isnan(x) -> bool\n\n\
Mark Dickinson226f5442010-07-11 18:13:41 +00001907Return True if x is a NaN (not a number), and False otherwise.");
Christian Heimes072c0f12008-01-03 23:01:04 +00001908
1909static PyObject *
1910math_isinf(PyObject *self, PyObject *arg)
1911{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 double x = PyFloat_AsDouble(arg);
1913 if (x == -1.0 && PyErr_Occurred())
1914 return NULL;
1915 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00001916}
1917
1918PyDoc_STRVAR(math_isinf_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001919"isinf(x) -> bool\n\n\
Mark Dickinson226f5442010-07-11 18:13:41 +00001920Return True if x is a positive or negative infinity, and False otherwise.");
Christian Heimes072c0f12008-01-03 23:01:04 +00001921
Barry Warsaw8b43b191996-12-09 22:32:36 +00001922static PyMethodDef math_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 {"acos", math_acos, METH_O, math_acos_doc},
1924 {"acosh", math_acosh, METH_O, math_acosh_doc},
1925 {"asin", math_asin, METH_O, math_asin_doc},
1926 {"asinh", math_asinh, METH_O, math_asinh_doc},
1927 {"atan", math_atan, METH_O, math_atan_doc},
1928 {"atan2", math_atan2, METH_VARARGS, math_atan2_doc},
1929 {"atanh", math_atanh, METH_O, math_atanh_doc},
1930 {"ceil", math_ceil, METH_O, math_ceil_doc},
1931 {"copysign", math_copysign, METH_VARARGS, math_copysign_doc},
1932 {"cos", math_cos, METH_O, math_cos_doc},
1933 {"cosh", math_cosh, METH_O, math_cosh_doc},
1934 {"degrees", math_degrees, METH_O, math_degrees_doc},
1935 {"erf", math_erf, METH_O, math_erf_doc},
1936 {"erfc", math_erfc, METH_O, math_erfc_doc},
1937 {"exp", math_exp, METH_O, math_exp_doc},
1938 {"expm1", math_expm1, METH_O, math_expm1_doc},
1939 {"fabs", math_fabs, METH_O, math_fabs_doc},
1940 {"factorial", math_factorial, METH_O, math_factorial_doc},
1941 {"floor", math_floor, METH_O, math_floor_doc},
1942 {"fmod", math_fmod, METH_VARARGS, math_fmod_doc},
1943 {"frexp", math_frexp, METH_O, math_frexp_doc},
1944 {"fsum", math_fsum, METH_O, math_fsum_doc},
1945 {"gamma", math_gamma, METH_O, math_gamma_doc},
1946 {"hypot", math_hypot, METH_VARARGS, math_hypot_doc},
Mark Dickinson8e0c9962010-07-11 17:38:24 +00001947 {"isfinite", math_isfinite, METH_O, math_isfinite_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 {"isinf", math_isinf, METH_O, math_isinf_doc},
1949 {"isnan", math_isnan, METH_O, math_isnan_doc},
1950 {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc},
1951 {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
1952 {"log", math_log, METH_VARARGS, math_log_doc},
1953 {"log1p", math_log1p, METH_O, math_log1p_doc},
1954 {"log10", math_log10, METH_O, math_log10_doc},
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001955 {"log2", math_log2, METH_O, math_log2_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 {"modf", math_modf, METH_O, math_modf_doc},
1957 {"pow", math_pow, METH_VARARGS, math_pow_doc},
1958 {"radians", math_radians, METH_O, math_radians_doc},
1959 {"sin", math_sin, METH_O, math_sin_doc},
1960 {"sinh", math_sinh, METH_O, math_sinh_doc},
1961 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
1962 {"tan", math_tan, METH_O, math_tan_doc},
1963 {"tanh", math_tanh, METH_O, math_tanh_doc},
1964 {"trunc", math_trunc, METH_O, math_trunc_doc},
1965 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001966};
1967
Guido van Rossumc6e22901998-12-04 19:26:43 +00001968
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001969PyDoc_STRVAR(module_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001970"This module is always available. It provides access to the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001971"mathematical functions defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001972
Martin v. Löwis1a214512008-06-11 05:26:20 +00001973
1974static struct PyModuleDef mathmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 PyModuleDef_HEAD_INIT,
1976 "math",
1977 module_doc,
1978 -1,
1979 math_methods,
1980 NULL,
1981 NULL,
1982 NULL,
1983 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001984};
1985
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001986PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001987PyInit_math(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001988{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 PyObject *m;
Tim Petersfe71f812001-08-07 22:10:00 +00001990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 m = PyModule_Create(&mathmodule);
1992 if (m == NULL)
1993 goto finally;
Barry Warsawfc93f751996-12-17 00:47:03 +00001994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
1996 PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
Barry Warsawfc93f751996-12-17 00:47:03 +00001997
Christian Heimes53876d92008-04-19 00:31:39 +00001998 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002000}