blob: 14d008af13cc6e21c7df395db35c035deb819989 [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:
Mark Dickinson83b8c0b2011-05-09 08:40:20 +0100584
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200585 (a) produce exact results for powers of 2, and
Mark Dickinson83b8c0b2011-05-09 08:40:20 +0100586 (b) give a monotonic log2 (for positive finite floats),
587 assuming that the system log is monotonic.
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200588*/
589
590static double
591m_log2(double x)
592{
593 if (!Py_IS_FINITE(x)) {
594 if (Py_IS_NAN(x))
595 return x; /* log2(nan) = nan */
596 else if (x > 0.0)
597 return x; /* log2(+inf) = +inf */
598 else {
599 errno = EDOM;
600 return Py_NAN; /* log2(-inf) = nan, invalid-operation */
601 }
602 }
603
604 if (x > 0.0) {
605 double m;
606 int e;
607 m = frexp(x, &e);
608 /* We want log2(m * 2**e) == log(m) / log(2) + e. Care is needed when
609 * x is just greater than 1.0: in that case e is 1, log(m) is negative,
610 * and we get significant cancellation error from the addition of
611 * log(m) / log(2) to e. The slight rewrite of the expression below
612 * avoids this problem.
613 */
614 if (x >= 1.0) {
615 return log(2.0 * m) / log(2.0) + (e - 1);
616 }
617 else {
618 return log(m) / log(2.0) + e;
619 }
620 }
621 else if (x == 0.0) {
622 errno = EDOM;
623 return -Py_HUGE_VAL; /* log2(0) = -inf, divide-by-zero */
624 }
625 else {
626 errno = EDOM;
Mark Dickinson23442582011-05-09 08:05:00 +0100627 return Py_NAN; /* log2(-inf) = nan, invalid-operation */
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200628 }
629}
630
Mark Dickinsone675f082008-12-11 21:56:00 +0000631static double
632m_log10(double x)
633{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 if (Py_IS_FINITE(x)) {
635 if (x > 0.0)
636 return log10(x);
637 errno = EDOM;
638 if (x == 0.0)
639 return -Py_HUGE_VAL; /* log10(0) = -inf */
640 else
641 return Py_NAN; /* log10(-ve) = nan */
642 }
643 else if (Py_IS_NAN(x))
644 return x; /* log10(nan) = nan */
645 else if (x > 0.0)
646 return x; /* log10(inf) = inf */
647 else {
648 errno = EDOM;
649 return Py_NAN; /* log10(-inf) = nan */
650 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000651}
652
653
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000654/* Call is_error when errno != 0, and where x is the result libm
655 * returned. is_error will usually set up an exception and return
656 * true (1), but may return false (0) without setting up an exception.
657 */
658static int
659is_error(double x)
660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 int result = 1; /* presumption of guilt */
662 assert(errno); /* non-zero errno is a precondition for calling */
663 if (errno == EDOM)
664 PyErr_SetString(PyExc_ValueError, "math domain error");
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 else if (errno == ERANGE) {
667 /* ANSI C generally requires libm functions to set ERANGE
668 * on overflow, but also generally *allows* them to set
669 * ERANGE on underflow too. There's no consistency about
670 * the latter across platforms.
671 * Alas, C99 never requires that errno be set.
672 * Here we suppress the underflow errors (libm functions
673 * should return a zero on underflow, and +- HUGE_VAL on
674 * overflow, so testing the result for zero suffices to
675 * distinguish the cases).
676 *
677 * On some platforms (Ubuntu/ia64) it seems that errno can be
678 * set to ERANGE for subnormal results that do *not* underflow
679 * to zero. So to be safe, we'll ignore ERANGE whenever the
680 * function result is less than one in absolute value.
681 */
682 if (fabs(x) < 1.0)
683 result = 0;
684 else
685 PyErr_SetString(PyExc_OverflowError,
686 "math range error");
687 }
688 else
689 /* Unexpected math error */
690 PyErr_SetFromErrno(PyExc_ValueError);
691 return result;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000692}
693
Mark Dickinsone675f082008-12-11 21:56:00 +0000694/*
Christian Heimes53876d92008-04-19 00:31:39 +0000695 math_1 is used to wrap a libm function f that takes a double
696 arguments and returns a double.
697
698 The error reporting follows these rules, which are designed to do
699 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
700 platforms.
701
702 - a NaN result from non-NaN inputs causes ValueError to be raised
703 - an infinite result from finite inputs causes OverflowError to be
704 raised if can_overflow is 1, or raises ValueError if can_overflow
705 is 0.
706 - if the result is finite and errno == EDOM then ValueError is
707 raised
708 - if the result is finite and nonzero and errno == ERANGE then
709 OverflowError is raised
710
711 The last rule is used to catch overflow on platforms which follow
712 C89 but for which HUGE_VAL is not an infinity.
713
714 For the majority of one-argument functions these rules are enough
715 to ensure that Python's functions behave as specified in 'Annex F'
716 of the C99 standard, with the 'invalid' and 'divide-by-zero'
717 floating-point exceptions mapping to Python's ValueError and the
718 'overflow' floating-point exception mapping to OverflowError.
719 math_1 only works for functions that don't have singularities *and*
720 the possibility of overflow; fortunately, that covers everything we
721 care about right now.
722*/
723
Barry Warsaw8b43b191996-12-09 22:32:36 +0000724static PyObject *
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000725math_1_to_whatever(PyObject *arg, double (*func) (double),
Christian Heimes53876d92008-04-19 00:31:39 +0000726 PyObject *(*from_double_func) (double),
727 int can_overflow)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000728{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 double x, r;
730 x = PyFloat_AsDouble(arg);
731 if (x == -1.0 && PyErr_Occurred())
732 return NULL;
733 errno = 0;
734 PyFPE_START_PROTECT("in math_1", return 0);
735 r = (*func)(x);
736 PyFPE_END_PROTECT(r);
737 if (Py_IS_NAN(r) && !Py_IS_NAN(x)) {
738 PyErr_SetString(PyExc_ValueError,
739 "math domain error"); /* invalid arg */
740 return NULL;
741 }
742 if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) {
743 if (can_overflow)
744 PyErr_SetString(PyExc_OverflowError,
745 "math range error"); /* overflow */
746 else
747 PyErr_SetString(PyExc_ValueError,
748 "math domain error"); /* singularity */
749 return NULL;
750 }
751 if (Py_IS_FINITE(r) && errno && is_error(r))
752 /* this branch unnecessary on most platforms */
753 return NULL;
Mark Dickinsonde429622008-05-01 00:19:23 +0000754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 return (*from_double_func)(r);
Christian Heimes53876d92008-04-19 00:31:39 +0000756}
757
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000758/* variant of math_1, to be used when the function being wrapped is known to
759 set errno properly (that is, errno = EDOM for invalid or divide-by-zero,
760 errno = ERANGE for overflow). */
761
762static PyObject *
763math_1a(PyObject *arg, double (*func) (double))
764{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 double x, r;
766 x = PyFloat_AsDouble(arg);
767 if (x == -1.0 && PyErr_Occurred())
768 return NULL;
769 errno = 0;
770 PyFPE_START_PROTECT("in math_1a", return 0);
771 r = (*func)(x);
772 PyFPE_END_PROTECT(r);
773 if (errno && is_error(r))
774 return NULL;
775 return PyFloat_FromDouble(r);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000776}
777
Christian Heimes53876d92008-04-19 00:31:39 +0000778/*
779 math_2 is used to wrap a libm function f that takes two double
780 arguments and returns a double.
781
782 The error reporting follows these rules, which are designed to do
783 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
784 platforms.
785
786 - a NaN result from non-NaN inputs causes ValueError to be raised
787 - an infinite result from finite inputs causes OverflowError to be
788 raised.
789 - if the result is finite and errno == EDOM then ValueError is
790 raised
791 - if the result is finite and nonzero and errno == ERANGE then
792 OverflowError is raised
793
794 The last rule is used to catch overflow on platforms which follow
795 C89 but for which HUGE_VAL is not an infinity.
796
797 For most two-argument functions (copysign, fmod, hypot, atan2)
798 these rules are enough to ensure that Python's functions behave as
799 specified in 'Annex F' of the C99 standard, with the 'invalid' and
800 'divide-by-zero' floating-point exceptions mapping to Python's
801 ValueError and the 'overflow' floating-point exception mapping to
802 OverflowError.
803*/
804
805static PyObject *
806math_1(PyObject *arg, double (*func) (double), int can_overflow)
807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow);
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000809}
810
811static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000812math_1_to_int(PyObject *arg, double (*func) (double), int can_overflow)
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000813{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 return math_1_to_whatever(arg, func, PyLong_FromDouble, can_overflow);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000815}
816
Barry Warsaw8b43b191996-12-09 22:32:36 +0000817static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +0000818math_2(PyObject *args, double (*func) (double, double), char *funcname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 PyObject *ox, *oy;
821 double x, y, r;
822 if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy))
823 return NULL;
824 x = PyFloat_AsDouble(ox);
825 y = PyFloat_AsDouble(oy);
826 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
827 return NULL;
828 errno = 0;
829 PyFPE_START_PROTECT("in math_2", return 0);
830 r = (*func)(x, y);
831 PyFPE_END_PROTECT(r);
832 if (Py_IS_NAN(r)) {
833 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
834 errno = EDOM;
835 else
836 errno = 0;
837 }
838 else if (Py_IS_INFINITY(r)) {
839 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
840 errno = ERANGE;
841 else
842 errno = 0;
843 }
844 if (errno && is_error(r))
845 return NULL;
846 else
847 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000848}
849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850#define FUNC1(funcname, func, can_overflow, docstring) \
851 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
852 return math_1(args, func, can_overflow); \
853 }\
854 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856#define FUNC1A(funcname, func, docstring) \
857 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
858 return math_1a(args, func); \
859 }\
860 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000861
Fred Drake40c48682000-07-03 18:11:56 +0000862#define FUNC2(funcname, func, docstring) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
864 return math_2(args, func, #funcname); \
865 }\
866 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000867
Christian Heimes53876d92008-04-19 00:31:39 +0000868FUNC1(acos, acos, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000869 "acos(x)\n\nReturn the arc cosine (measured in radians) of x.")
Mark Dickinsonf3718592009-12-21 15:27:41 +0000870FUNC1(acosh, m_acosh, 0,
Christian Heimes53876d92008-04-19 00:31:39 +0000871 "acosh(x)\n\nReturn the hyperbolic arc cosine (measured in radians) of x.")
872FUNC1(asin, asin, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000873 "asin(x)\n\nReturn the arc sine (measured in radians) of x.")
Mark Dickinsonf3718592009-12-21 15:27:41 +0000874FUNC1(asinh, m_asinh, 0,
Christian Heimes53876d92008-04-19 00:31:39 +0000875 "asinh(x)\n\nReturn the hyperbolic arc sine (measured in radians) of x.")
876FUNC1(atan, atan, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000877 "atan(x)\n\nReturn the arc tangent (measured in radians) of x.")
Christian Heimese57950f2008-04-21 13:08:03 +0000878FUNC2(atan2, m_atan2,
Tim Petersfe71f812001-08-07 22:10:00 +0000879 "atan2(y, x)\n\nReturn the arc tangent (measured in radians) of y/x.\n"
880 "Unlike atan(y/x), the signs of both x and y are considered.")
Mark Dickinsonf3718592009-12-21 15:27:41 +0000881FUNC1(atanh, m_atanh, 0,
Christian Heimes53876d92008-04-19 00:31:39 +0000882 "atanh(x)\n\nReturn the hyperbolic arc tangent (measured in radians) of x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +0000883
884static PyObject * math_ceil(PyObject *self, PyObject *number) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 static PyObject *ceil_str = NULL;
Mark Dickinson6d02d9c2010-07-02 16:05:15 +0000886 PyObject *method, *result;
Guido van Rossum13e05de2007-08-23 22:56:55 +0000887
Benjamin Petersonf751bc92010-07-02 13:46:42 +0000888 method = _PyObject_LookupSpecial(number, "__ceil__", &ceil_str);
889 if (method == NULL) {
890 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 return math_1_to_int(number, ceil, 0);
Benjamin Petersonf751bc92010-07-02 13:46:42 +0000893 }
Mark Dickinson6d02d9c2010-07-02 16:05:15 +0000894 result = PyObject_CallFunctionObjArgs(method, NULL);
895 Py_DECREF(method);
896 return result;
Guido van Rossum13e05de2007-08-23 22:56:55 +0000897}
898
899PyDoc_STRVAR(math_ceil_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 "ceil(x)\n\nReturn the ceiling of x as an int.\n"
901 "This is the smallest integral value >= x.");
Guido van Rossum13e05de2007-08-23 22:56:55 +0000902
Christian Heimes072c0f12008-01-03 23:01:04 +0000903FUNC2(copysign, copysign,
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000904 "copysign(x, y)\n\nReturn x with the sign of y.")
Christian Heimes53876d92008-04-19 00:31:39 +0000905FUNC1(cos, cos, 0,
906 "cos(x)\n\nReturn the cosine of x (measured in radians).")
907FUNC1(cosh, cosh, 1,
908 "cosh(x)\n\nReturn the hyperbolic cosine of x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +0000909FUNC1A(erf, m_erf,
910 "erf(x)\n\nError function at x.")
911FUNC1A(erfc, m_erfc,
912 "erfc(x)\n\nComplementary error function at x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000913FUNC1(exp, exp, 1,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000914 "exp(x)\n\nReturn e raised to the power of x.")
Mark Dickinson664b5112009-12-16 20:23:42 +0000915FUNC1(expm1, m_expm1, 1,
916 "expm1(x)\n\nReturn exp(x)-1.\n"
917 "This function avoids the loss of precision involved in the direct "
918 "evaluation of exp(x)-1 for small x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000919FUNC1(fabs, fabs, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000920 "fabs(x)\n\nReturn the absolute value of the float x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +0000921
922static PyObject * math_floor(PyObject *self, PyObject *number) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 static PyObject *floor_str = NULL;
Benjamin Petersonb0125892010-07-02 13:35:17 +0000924 PyObject *method, *result;
Guido van Rossum13e05de2007-08-23 22:56:55 +0000925
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +0000926 method = _PyObject_LookupSpecial(number, "__floor__", &floor_str);
927 if (method == NULL) {
928 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 return math_1_to_int(number, floor, 0);
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +0000931 }
Benjamin Petersonb0125892010-07-02 13:35:17 +0000932 result = PyObject_CallFunctionObjArgs(method, NULL);
933 Py_DECREF(method);
934 return result;
Guido van Rossum13e05de2007-08-23 22:56:55 +0000935}
936
937PyDoc_STRVAR(math_floor_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 "floor(x)\n\nReturn the floor of x as an int.\n"
939 "This is the largest integral value <= x.");
Guido van Rossum13e05de2007-08-23 22:56:55 +0000940
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000941FUNC1A(gamma, m_tgamma,
942 "gamma(x)\n\nGamma function at x.")
Mark Dickinson05d2e082009-12-11 20:17:17 +0000943FUNC1A(lgamma, m_lgamma,
944 "lgamma(x)\n\nNatural logarithm of absolute value of Gamma function at x.")
Mark Dickinsonbe64d952010-07-07 16:21:29 +0000945FUNC1(log1p, m_log1p, 0,
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000946 "log1p(x)\n\nReturn the natural logarithm of 1+x (base e).\n"
947 "The result is computed in a way which is accurate for x near zero.")
Christian Heimes53876d92008-04-19 00:31:39 +0000948FUNC1(sin, sin, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000949 "sin(x)\n\nReturn the sine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +0000950FUNC1(sinh, sinh, 1,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000951 "sinh(x)\n\nReturn the hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000952FUNC1(sqrt, sqrt, 0,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000953 "sqrt(x)\n\nReturn the square root of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000954FUNC1(tan, tan, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000955 "tan(x)\n\nReturn the tangent of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +0000956FUNC1(tanh, tanh, 0,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000957 "tanh(x)\n\nReturn the hyperbolic tangent of x.")
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000958
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000959/* Precision summation function as msum() by Raymond Hettinger in
960 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
961 enhanced with the exact partials sum and roundoff from Mark
962 Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
963 See those links for more details, proofs and other references.
964
965 Note 1: IEEE 754R floating point semantics are assumed,
966 but the current implementation does not re-establish special
967 value semantics across iterations (i.e. handling -Inf + Inf).
968
969 Note 2: No provision is made for intermediate overflow handling;
Georg Brandlf78e02b2008-06-10 17:40:04 +0000970 therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000971 sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
972 overflow of the first partial sum.
973
Benjamin Petersonfea6a942008-07-02 16:11:42 +0000974 Note 3: The intermediate values lo, yr, and hi are declared volatile so
975 aggressive compilers won't algebraically reduce lo to always be exactly 0.0.
Georg Brandlf78e02b2008-06-10 17:40:04 +0000976 Also, the volatile declaration forces the values to be stored in memory as
977 regular doubles instead of extended long precision (80-bit) values. This
Benjamin Petersonfea6a942008-07-02 16:11:42 +0000978 prevents double rounding because any addition or subtraction of two doubles
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 can be resolved exactly into double-sized hi and lo values. As long as the
Georg Brandlf78e02b2008-06-10 17:40:04 +0000980 hi value gets forced into a double before yr and lo are computed, the extra
981 bits in downstream extended precision operations (x87 for example) will be
982 exactly zero and therefore can be losslessly stored back into a double,
983 thereby preventing double rounding.
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000984
985 Note 4: A similar implementation is in Modules/cmathmodule.c.
986 Be sure to update both when making changes.
987
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000988 Note 5: The signature of math.fsum() differs from __builtin__.sum()
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000989 because the start argument doesn't make sense in the context of
990 accurate summation. Since the partials table is collapsed before
991 returning a result, sum(seq2, start=sum(seq1)) may not equal the
992 accurate result returned by sum(itertools.chain(seq1, seq2)).
993*/
994
995#define NUM_PARTIALS 32 /* initial partials array size, on stack */
996
997/* Extend the partials array p[] by doubling its size. */
998static int /* non-zero on error */
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000999_fsum_realloc(double **p_ptr, Py_ssize_t n,
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001000 double *ps, Py_ssize_t *m_ptr)
1001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 void *v = NULL;
1003 Py_ssize_t m = *m_ptr;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 m += m; /* double */
1006 if (n < m && m < (PY_SSIZE_T_MAX / sizeof(double))) {
1007 double *p = *p_ptr;
1008 if (p == ps) {
1009 v = PyMem_Malloc(sizeof(double) * m);
1010 if (v != NULL)
1011 memcpy(v, ps, sizeof(double) * n);
1012 }
1013 else
1014 v = PyMem_Realloc(p, sizeof(double) * m);
1015 }
1016 if (v == NULL) { /* size overflow or no memory */
1017 PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
1018 return 1;
1019 }
1020 *p_ptr = (double*) v;
1021 *m_ptr = m;
1022 return 0;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001023}
1024
1025/* Full precision summation of a sequence of floats.
1026
1027 def msum(iterable):
1028 partials = [] # sorted, non-overlapping partial sums
1029 for x in iterable:
Mark Dickinsonfdb0acc2010-06-25 20:22:24 +00001030 i = 0
1031 for y in partials:
1032 if abs(x) < abs(y):
1033 x, y = y, x
1034 hi = x + y
1035 lo = y - (hi - x)
1036 if lo:
1037 partials[i] = lo
1038 i += 1
1039 x = hi
1040 partials[i:] = [x]
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001041 return sum_exact(partials)
1042
1043 Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
1044 are exactly equal to x+y. The inner loop applies hi/lo summation to each
1045 partial so that the list of partial sums remains exact.
1046
1047 Sum_exact() adds the partial sums exactly and correctly rounds the final
1048 result (using the round-half-to-even rule). The items in partials remain
1049 non-zero, non-special, non-overlapping and strictly increasing in
1050 magnitude, but possibly not all having the same sign.
1051
1052 Depends on IEEE 754 arithmetic guarantees and half-even rounding.
1053*/
1054
1055static PyObject*
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001056math_fsum(PyObject *self, PyObject *seq)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001057{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 PyObject *item, *iter, *sum = NULL;
1059 Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
1060 double x, y, t, ps[NUM_PARTIALS], *p = ps;
1061 double xsave, special_sum = 0.0, inf_sum = 0.0;
1062 volatile double hi, yr, lo;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 iter = PyObject_GetIter(seq);
1065 if (iter == NULL)
1066 return NULL;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 for(;;) { /* for x in iterable */
1071 assert(0 <= n && n <= m);
1072 assert((m == NUM_PARTIALS && p == ps) ||
1073 (m > NUM_PARTIALS && p != NULL));
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 item = PyIter_Next(iter);
1076 if (item == NULL) {
1077 if (PyErr_Occurred())
1078 goto _fsum_error;
1079 break;
1080 }
1081 x = PyFloat_AsDouble(item);
1082 Py_DECREF(item);
1083 if (PyErr_Occurred())
1084 goto _fsum_error;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 xsave = x;
1087 for (i = j = 0; j < n; j++) { /* for y in partials */
1088 y = p[j];
1089 if (fabs(x) < fabs(y)) {
1090 t = x; x = y; y = t;
1091 }
1092 hi = x + y;
1093 yr = hi - x;
1094 lo = y - yr;
1095 if (lo != 0.0)
1096 p[i++] = lo;
1097 x = hi;
1098 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 n = i; /* ps[i:] = [x] */
1101 if (x != 0.0) {
1102 if (! Py_IS_FINITE(x)) {
1103 /* a nonfinite x could arise either as
1104 a result of intermediate overflow, or
1105 as a result of a nan or inf in the
1106 summands */
1107 if (Py_IS_FINITE(xsave)) {
1108 PyErr_SetString(PyExc_OverflowError,
1109 "intermediate overflow in fsum");
1110 goto _fsum_error;
1111 }
1112 if (Py_IS_INFINITY(xsave))
1113 inf_sum += xsave;
1114 special_sum += xsave;
1115 /* reset partials */
1116 n = 0;
1117 }
1118 else if (n >= m && _fsum_realloc(&p, n, ps, &m))
1119 goto _fsum_error;
1120 else
1121 p[n++] = x;
1122 }
1123 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 if (special_sum != 0.0) {
1126 if (Py_IS_NAN(inf_sum))
1127 PyErr_SetString(PyExc_ValueError,
1128 "-inf + inf in fsum");
1129 else
1130 sum = PyFloat_FromDouble(special_sum);
1131 goto _fsum_error;
1132 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 hi = 0.0;
1135 if (n > 0) {
1136 hi = p[--n];
1137 /* sum_exact(ps, hi) from the top, stop when the sum becomes
1138 inexact. */
1139 while (n > 0) {
1140 x = hi;
1141 y = p[--n];
1142 assert(fabs(y) < fabs(x));
1143 hi = x + y;
1144 yr = hi - x;
1145 lo = y - yr;
1146 if (lo != 0.0)
1147 break;
1148 }
1149 /* Make half-even rounding work across multiple partials.
1150 Needed so that sum([1e-16, 1, 1e16]) will round-up the last
1151 digit to two instead of down to zero (the 1e-16 makes the 1
1152 slightly closer to two). With a potential 1 ULP rounding
1153 error fixed-up, math.fsum() can guarantee commutativity. */
1154 if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
1155 (lo > 0.0 && p[n-1] > 0.0))) {
1156 y = lo * 2.0;
1157 x = hi + y;
1158 yr = x - hi;
1159 if (y == yr)
1160 hi = x;
1161 }
1162 }
1163 sum = PyFloat_FromDouble(hi);
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001164
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001165_fsum_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 PyFPE_END_PROTECT(hi)
1167 Py_DECREF(iter);
1168 if (p != ps)
1169 PyMem_Free(p);
1170 return sum;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001171}
1172
1173#undef NUM_PARTIALS
1174
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001175PyDoc_STRVAR(math_fsum_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001176"fsum(iterable)\n\n\
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001177Return an accurate floating point sum of values in the iterable.\n\
1178Assumes IEEE-754 floating point arithmetic.");
1179
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001180/* Return the smallest integer k such that n < 2**k, or 0 if n == 0.
1181 * Equivalent to floor(lg(x))+1. Also equivalent to: bitwidth_of_type -
1182 * count_leading_zero_bits(x)
1183 */
1184
1185/* XXX: This routine does more or less the same thing as
1186 * bits_in_digit() in Objects/longobject.c. Someday it would be nice to
1187 * consolidate them. On BSD, there's a library function called fls()
1188 * that we could use, and GCC provides __builtin_clz().
1189 */
1190
1191static unsigned long
1192bit_length(unsigned long n)
1193{
1194 unsigned long len = 0;
1195 while (n != 0) {
1196 ++len;
1197 n >>= 1;
1198 }
1199 return len;
1200}
1201
1202static unsigned long
1203count_set_bits(unsigned long n)
1204{
1205 unsigned long count = 0;
1206 while (n != 0) {
1207 ++count;
1208 n &= n - 1; /* clear least significant bit */
1209 }
1210 return count;
1211}
1212
1213/* Divide-and-conquer factorial algorithm
1214 *
1215 * Based on the formula and psuedo-code provided at:
1216 * http://www.luschny.de/math/factorial/binarysplitfact.html
1217 *
1218 * Faster algorithms exist, but they're more complicated and depend on
Ezio Melotti9527afd2010-07-08 15:03:02 +00001219 * a fast prime factorization algorithm.
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001220 *
1221 * Notes on the algorithm
1222 * ----------------------
1223 *
1224 * factorial(n) is written in the form 2**k * m, with m odd. k and m are
1225 * computed separately, and then combined using a left shift.
1226 *
1227 * The function factorial_odd_part computes the odd part m (i.e., the greatest
1228 * odd divisor) of factorial(n), using the formula:
1229 *
1230 * factorial_odd_part(n) =
1231 *
1232 * product_{i >= 0} product_{0 < j <= n / 2**i, j odd} j
1233 *
1234 * Example: factorial_odd_part(20) =
1235 *
1236 * (1) *
1237 * (1) *
1238 * (1 * 3 * 5) *
1239 * (1 * 3 * 5 * 7 * 9)
1240 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1241 *
1242 * Here i goes from large to small: the first term corresponds to i=4 (any
1243 * larger i gives an empty product), and the last term corresponds to i=0.
1244 * Each term can be computed from the last by multiplying by the extra odd
1245 * numbers required: e.g., to get from the penultimate term to the last one,
1246 * we multiply by (11 * 13 * 15 * 17 * 19).
1247 *
1248 * To see a hint of why this formula works, here are the same numbers as above
1249 * but with the even parts (i.e., the appropriate powers of 2) included. For
1250 * each subterm in the product for i, we multiply that subterm by 2**i:
1251 *
1252 * factorial(20) =
1253 *
1254 * (16) *
1255 * (8) *
1256 * (4 * 12 * 20) *
1257 * (2 * 6 * 10 * 14 * 18) *
1258 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1259 *
1260 * The factorial_partial_product function computes the product of all odd j in
1261 * range(start, stop) for given start and stop. It's used to compute the
1262 * partial products like (11 * 13 * 15 * 17 * 19) in the example above. It
1263 * operates recursively, repeatedly splitting the range into two roughly equal
1264 * pieces until the subranges are small enough to be computed using only C
1265 * integer arithmetic.
1266 *
1267 * The two-valuation k (i.e., the exponent of the largest power of 2 dividing
1268 * the factorial) is computed independently in the main math_factorial
1269 * function. By standard results, its value is:
1270 *
1271 * two_valuation = n//2 + n//4 + n//8 + ....
1272 *
1273 * It can be shown (e.g., by complete induction on n) that two_valuation is
1274 * equal to n - count_set_bits(n), where count_set_bits(n) gives the number of
1275 * '1'-bits in the binary expansion of n.
1276 */
1277
1278/* factorial_partial_product: Compute product(range(start, stop, 2)) using
1279 * divide and conquer. Assumes start and stop are odd and stop > start.
1280 * max_bits must be >= bit_length(stop - 2). */
1281
1282static PyObject *
1283factorial_partial_product(unsigned long start, unsigned long stop,
1284 unsigned long max_bits)
1285{
1286 unsigned long midpoint, num_operands;
1287 PyObject *left = NULL, *right = NULL, *result = NULL;
1288
1289 /* If the return value will fit an unsigned long, then we can
1290 * multiply in a tight, fast loop where each multiply is O(1).
1291 * Compute an upper bound on the number of bits required to store
1292 * the answer.
1293 *
1294 * Storing some integer z requires floor(lg(z))+1 bits, which is
1295 * conveniently the value returned by bit_length(z). The
1296 * product x*y will require at most
1297 * bit_length(x) + bit_length(y) bits to store, based
1298 * on the idea that lg product = lg x + lg y.
1299 *
1300 * We know that stop - 2 is the largest number to be multiplied. From
1301 * there, we have: bit_length(answer) <= num_operands *
1302 * bit_length(stop - 2)
1303 */
1304
1305 num_operands = (stop - start) / 2;
1306 /* The "num_operands <= 8 * SIZEOF_LONG" check guards against the
1307 * unlikely case of an overflow in num_operands * max_bits. */
1308 if (num_operands <= 8 * SIZEOF_LONG &&
1309 num_operands * max_bits <= 8 * SIZEOF_LONG) {
1310 unsigned long j, total;
1311 for (total = start, j = start + 2; j < stop; j += 2)
1312 total *= j;
1313 return PyLong_FromUnsignedLong(total);
1314 }
1315
1316 /* find midpoint of range(start, stop), rounded up to next odd number. */
1317 midpoint = (start + num_operands) | 1;
1318 left = factorial_partial_product(start, midpoint,
1319 bit_length(midpoint - 2));
1320 if (left == NULL)
1321 goto error;
1322 right = factorial_partial_product(midpoint, stop, max_bits);
1323 if (right == NULL)
1324 goto error;
1325 result = PyNumber_Multiply(left, right);
1326
1327 error:
1328 Py_XDECREF(left);
1329 Py_XDECREF(right);
1330 return result;
1331}
1332
1333/* factorial_odd_part: compute the odd part of factorial(n). */
1334
1335static PyObject *
1336factorial_odd_part(unsigned long n)
1337{
1338 long i;
1339 unsigned long v, lower, upper;
1340 PyObject *partial, *tmp, *inner, *outer;
1341
1342 inner = PyLong_FromLong(1);
1343 if (inner == NULL)
1344 return NULL;
1345 outer = inner;
1346 Py_INCREF(outer);
1347
1348 upper = 3;
1349 for (i = bit_length(n) - 2; i >= 0; i--) {
1350 v = n >> i;
1351 if (v <= 2)
1352 continue;
1353 lower = upper;
1354 /* (v + 1) | 1 = least odd integer strictly larger than n / 2**i */
1355 upper = (v + 1) | 1;
1356 /* Here inner is the product of all odd integers j in the range (0,
1357 n/2**(i+1)]. The factorial_partial_product call below gives the
1358 product of all odd integers j in the range (n/2**(i+1), n/2**i]. */
1359 partial = factorial_partial_product(lower, upper, bit_length(upper-2));
1360 /* inner *= partial */
1361 if (partial == NULL)
1362 goto error;
1363 tmp = PyNumber_Multiply(inner, partial);
1364 Py_DECREF(partial);
1365 if (tmp == NULL)
1366 goto error;
1367 Py_DECREF(inner);
1368 inner = tmp;
1369 /* Now inner is the product of all odd integers j in the range (0,
1370 n/2**i], giving the inner product in the formula above. */
1371
1372 /* outer *= inner; */
1373 tmp = PyNumber_Multiply(outer, inner);
1374 if (tmp == NULL)
1375 goto error;
1376 Py_DECREF(outer);
1377 outer = tmp;
1378 }
1379
1380 goto done;
1381
1382 error:
1383 Py_DECREF(outer);
1384 done:
1385 Py_DECREF(inner);
1386 return outer;
1387}
1388
1389/* Lookup table for small factorial values */
1390
1391static const unsigned long SmallFactorials[] = {
1392 1, 1, 2, 6, 24, 120, 720, 5040, 40320,
1393 362880, 3628800, 39916800, 479001600,
1394#if SIZEOF_LONG >= 8
1395 6227020800, 87178291200, 1307674368000,
1396 20922789888000, 355687428096000, 6402373705728000,
1397 121645100408832000, 2432902008176640000
1398#endif
1399};
1400
Barry Warsaw8b43b191996-12-09 22:32:36 +00001401static PyObject *
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001402math_factorial(PyObject *self, PyObject *arg)
1403{
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001404 long x;
1405 PyObject *result, *odd_part, *two_valuation;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 if (PyFloat_Check(arg)) {
1408 PyObject *lx;
1409 double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
1410 if (!(Py_IS_FINITE(dx) && dx == floor(dx))) {
1411 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001412 "factorial() only accepts integral values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 return NULL;
1414 }
1415 lx = PyLong_FromDouble(dx);
1416 if (lx == NULL)
1417 return NULL;
1418 x = PyLong_AsLong(lx);
1419 Py_DECREF(lx);
1420 }
1421 else
1422 x = PyLong_AsLong(arg);
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 if (x == -1 && PyErr_Occurred())
1425 return NULL;
1426 if (x < 0) {
1427 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001428 "factorial() not defined for negative values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 return NULL;
1430 }
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001431
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001432 /* use lookup table if x is small */
1433 if (x < (long)(sizeof(SmallFactorials)/sizeof(SmallFactorials[0])))
1434 return PyLong_FromUnsignedLong(SmallFactorials[x]);
1435
1436 /* else express in the form odd_part * 2**two_valuation, and compute as
1437 odd_part << two_valuation. */
1438 odd_part = factorial_odd_part(x);
1439 if (odd_part == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 return NULL;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001441 two_valuation = PyLong_FromLong(x - count_set_bits(x));
1442 if (two_valuation == NULL) {
1443 Py_DECREF(odd_part);
1444 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 }
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001446 result = PyNumber_Lshift(odd_part, two_valuation);
1447 Py_DECREF(two_valuation);
1448 Py_DECREF(odd_part);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 return result;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001450}
1451
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001452PyDoc_STRVAR(math_factorial_doc,
1453"factorial(x) -> Integral\n"
1454"\n"
1455"Find x!. Raise a ValueError if x is negative or non-integral.");
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001456
1457static PyObject *
Christian Heimes400adb02008-02-01 08:12:03 +00001458math_trunc(PyObject *self, PyObject *number)
1459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 static PyObject *trunc_str = NULL;
Benjamin Petersonb0125892010-07-02 13:35:17 +00001461 PyObject *trunc, *result;
Christian Heimes400adb02008-02-01 08:12:03 +00001462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 if (Py_TYPE(number)->tp_dict == NULL) {
1464 if (PyType_Ready(Py_TYPE(number)) < 0)
1465 return NULL;
1466 }
Christian Heimes400adb02008-02-01 08:12:03 +00001467
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001468 trunc = _PyObject_LookupSpecial(number, "__trunc__", &trunc_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 if (trunc == NULL) {
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001470 if (!PyErr_Occurred())
1471 PyErr_Format(PyExc_TypeError,
1472 "type %.100s doesn't define __trunc__ method",
1473 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 return NULL;
1475 }
Benjamin Petersonb0125892010-07-02 13:35:17 +00001476 result = PyObject_CallFunctionObjArgs(trunc, NULL);
1477 Py_DECREF(trunc);
1478 return result;
Christian Heimes400adb02008-02-01 08:12:03 +00001479}
1480
1481PyDoc_STRVAR(math_trunc_doc,
1482"trunc(x:Real) -> Integral\n"
1483"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001484"Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.");
Christian Heimes400adb02008-02-01 08:12:03 +00001485
1486static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001487math_frexp(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 int i;
1490 double x = PyFloat_AsDouble(arg);
1491 if (x == -1.0 && PyErr_Occurred())
1492 return NULL;
1493 /* deal with special cases directly, to sidestep platform
1494 differences */
1495 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
1496 i = 0;
1497 }
1498 else {
1499 PyFPE_START_PROTECT("in math_frexp", return 0);
1500 x = frexp(x, &i);
1501 PyFPE_END_PROTECT(x);
1502 }
1503 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001504}
1505
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001506PyDoc_STRVAR(math_frexp_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001507"frexp(x)\n"
1508"\n"
1509"Return the mantissa and exponent of x, as pair (m, e).\n"
1510"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 +00001511"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 +00001512
Barry Warsaw8b43b191996-12-09 22:32:36 +00001513static PyObject *
Fred Drake40c48682000-07-03 18:11:56 +00001514math_ldexp(PyObject *self, PyObject *args)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 double x, r;
1517 PyObject *oexp;
1518 long exp;
1519 int overflow;
1520 if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp))
1521 return NULL;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 if (PyLong_Check(oexp)) {
1524 /* on overflow, replace exponent with either LONG_MAX
1525 or LONG_MIN, depending on the sign. */
1526 exp = PyLong_AsLongAndOverflow(oexp, &overflow);
1527 if (exp == -1 && PyErr_Occurred())
1528 return NULL;
1529 if (overflow)
1530 exp = overflow < 0 ? LONG_MIN : LONG_MAX;
1531 }
1532 else {
1533 PyErr_SetString(PyExc_TypeError,
1534 "Expected an int or long as second argument "
1535 "to ldexp.");
1536 return NULL;
1537 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 if (x == 0. || !Py_IS_FINITE(x)) {
1540 /* NaNs, zeros and infinities are returned unchanged */
1541 r = x;
1542 errno = 0;
1543 } else if (exp > INT_MAX) {
1544 /* overflow */
1545 r = copysign(Py_HUGE_VAL, x);
1546 errno = ERANGE;
1547 } else if (exp < INT_MIN) {
1548 /* underflow to +-0 */
1549 r = copysign(0., x);
1550 errno = 0;
1551 } else {
1552 errno = 0;
1553 PyFPE_START_PROTECT("in math_ldexp", return 0);
1554 r = ldexp(x, (int)exp);
1555 PyFPE_END_PROTECT(r);
1556 if (Py_IS_INFINITY(r))
1557 errno = ERANGE;
1558 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 if (errno && is_error(r))
1561 return NULL;
1562 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001563}
1564
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001565PyDoc_STRVAR(math_ldexp_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001566"ldexp(x, i)\n\n\
1567Return x * (2**i).");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001568
Barry Warsaw8b43b191996-12-09 22:32:36 +00001569static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001570math_modf(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 double y, x = PyFloat_AsDouble(arg);
1573 if (x == -1.0 && PyErr_Occurred())
1574 return NULL;
1575 /* some platforms don't do the right thing for NaNs and
1576 infinities, so we take care of special cases directly. */
1577 if (!Py_IS_FINITE(x)) {
1578 if (Py_IS_INFINITY(x))
1579 return Py_BuildValue("(dd)", copysign(0., x), x);
1580 else if (Py_IS_NAN(x))
1581 return Py_BuildValue("(dd)", x, x);
1582 }
Christian Heimesa342c012008-04-20 21:01:16 +00001583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 errno = 0;
1585 PyFPE_START_PROTECT("in math_modf", return 0);
1586 x = modf(x, &y);
1587 PyFPE_END_PROTECT(x);
1588 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001589}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001590
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001591PyDoc_STRVAR(math_modf_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001592"modf(x)\n"
1593"\n"
1594"Return the fractional and integer parts of x. Both results carry the sign\n"
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001595"of x and are floats.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001596
Tim Peters78526162001-09-05 00:53:45 +00001597/* A decent logarithm is easy to compute even for huge longs, but libm can't
1598 do that by itself -- loghelper can. func is log or log10, and name is
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00001599 "log" or "log10". Note that overflow of the result isn't possible: a long
1600 can contain no more than INT_MAX * SHIFT bits, so has value certainly less
1601 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 +00001602 small enough to fit in an IEEE single. log and log10 are even smaller.
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00001603 However, intermediate overflow is possible for a long if the number of bits
1604 in that long is larger than PY_SSIZE_T_MAX. */
Tim Peters78526162001-09-05 00:53:45 +00001605
1606static PyObject*
Thomas Wouters89f507f2006-12-13 04:49:30 +00001607loghelper(PyObject* arg, double (*func)(double), char *funcname)
Tim Peters78526162001-09-05 00:53:45 +00001608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 /* If it is long, do it ourselves. */
1610 if (PyLong_Check(arg)) {
Mark Dickinsonc6037172010-09-29 19:06:36 +00001611 double x, result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 Py_ssize_t e;
Mark Dickinsonc6037172010-09-29 19:06:36 +00001613
1614 /* Negative or zero inputs give a ValueError. */
1615 if (Py_SIZE(arg) <= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 PyErr_SetString(PyExc_ValueError,
1617 "math domain error");
1618 return NULL;
1619 }
Mark Dickinsonfa41e602010-09-28 07:22:27 +00001620
Mark Dickinsonc6037172010-09-29 19:06:36 +00001621 x = PyLong_AsDouble(arg);
1622 if (x == -1.0 && PyErr_Occurred()) {
1623 if (!PyErr_ExceptionMatches(PyExc_OverflowError))
1624 return NULL;
1625 /* Here the conversion to double overflowed, but it's possible
1626 to compute the log anyway. Clear the exception and continue. */
1627 PyErr_Clear();
1628 x = _PyLong_Frexp((PyLongObject *)arg, &e);
1629 if (x == -1.0 && PyErr_Occurred())
1630 return NULL;
1631 /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */
1632 result = func(x) + func(2.0) * e;
1633 }
1634 else
1635 /* Successfully converted x to a double. */
1636 result = func(x);
1637 return PyFloat_FromDouble(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 }
Tim Peters78526162001-09-05 00:53:45 +00001639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 /* Else let libm handle it by itself. */
1641 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +00001642}
1643
1644static PyObject *
1645math_log(PyObject *self, PyObject *args)
1646{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 PyObject *arg;
1648 PyObject *base = NULL;
1649 PyObject *num, *den;
1650 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base))
1653 return NULL;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 num = loghelper(arg, m_log, "log");
1656 if (num == NULL || base == NULL)
1657 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 den = loghelper(base, m_log, "log");
1660 if (den == NULL) {
1661 Py_DECREF(num);
1662 return NULL;
1663 }
Raymond Hettinger866964c2002-12-14 19:51:34 +00001664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 ans = PyNumber_TrueDivide(num, den);
1666 Py_DECREF(num);
1667 Py_DECREF(den);
1668 return ans;
Tim Peters78526162001-09-05 00:53:45 +00001669}
1670
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001671PyDoc_STRVAR(math_log_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001672"log(x[, base])\n\n\
1673Return the logarithm of x to the given base.\n\
Raymond Hettinger866964c2002-12-14 19:51:34 +00001674If the base not specified, returns the natural logarithm (base e) of x.");
Tim Peters78526162001-09-05 00:53:45 +00001675
1676static PyObject *
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001677math_log2(PyObject *self, PyObject *arg)
1678{
1679 return loghelper(arg, m_log2, "log2");
1680}
1681
1682PyDoc_STRVAR(math_log2_doc,
1683"log2(x)\n\nReturn the base 2 logarithm of x.");
1684
1685static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001686math_log10(PyObject *self, PyObject *arg)
Tim Peters78526162001-09-05 00:53:45 +00001687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 return loghelper(arg, m_log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +00001689}
1690
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001691PyDoc_STRVAR(math_log10_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001692"log10(x)\n\nReturn the base 10 logarithm of x.");
Tim Peters78526162001-09-05 00:53:45 +00001693
Christian Heimes53876d92008-04-19 00:31:39 +00001694static PyObject *
1695math_fmod(PyObject *self, PyObject *args)
1696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 PyObject *ox, *oy;
1698 double r, x, y;
1699 if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy))
1700 return NULL;
1701 x = PyFloat_AsDouble(ox);
1702 y = PyFloat_AsDouble(oy);
1703 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1704 return NULL;
1705 /* fmod(x, +/-Inf) returns x for finite x. */
1706 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
1707 return PyFloat_FromDouble(x);
1708 errno = 0;
1709 PyFPE_START_PROTECT("in math_fmod", return 0);
1710 r = fmod(x, y);
1711 PyFPE_END_PROTECT(r);
1712 if (Py_IS_NAN(r)) {
1713 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1714 errno = EDOM;
1715 else
1716 errno = 0;
1717 }
1718 if (errno && is_error(r))
1719 return NULL;
1720 else
1721 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00001722}
1723
1724PyDoc_STRVAR(math_fmod_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001725"fmod(x, y)\n\nReturn fmod(x, y), according to platform C."
Christian Heimes53876d92008-04-19 00:31:39 +00001726" x % y may differ.");
1727
1728static PyObject *
1729math_hypot(PyObject *self, PyObject *args)
1730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 PyObject *ox, *oy;
1732 double r, x, y;
1733 if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy))
1734 return NULL;
1735 x = PyFloat_AsDouble(ox);
1736 y = PyFloat_AsDouble(oy);
1737 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1738 return NULL;
1739 /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */
1740 if (Py_IS_INFINITY(x))
1741 return PyFloat_FromDouble(fabs(x));
1742 if (Py_IS_INFINITY(y))
1743 return PyFloat_FromDouble(fabs(y));
1744 errno = 0;
1745 PyFPE_START_PROTECT("in math_hypot", return 0);
1746 r = hypot(x, y);
1747 PyFPE_END_PROTECT(r);
1748 if (Py_IS_NAN(r)) {
1749 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1750 errno = EDOM;
1751 else
1752 errno = 0;
1753 }
1754 else if (Py_IS_INFINITY(r)) {
1755 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
1756 errno = ERANGE;
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_hypot_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001767"hypot(x, y)\n\nReturn the Euclidean distance, sqrt(x*x + y*y).");
Christian Heimes53876d92008-04-19 00:31:39 +00001768
1769/* pow can't use math_2, but needs its own wrapper: the problem is
1770 that an infinite result can arise either as a result of overflow
1771 (in which case OverflowError should be raised) or as a result of
1772 e.g. 0.**-5. (for which ValueError needs to be raised.)
1773*/
1774
1775static PyObject *
1776math_pow(PyObject *self, PyObject *args)
1777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 PyObject *ox, *oy;
1779 double r, x, y;
1780 int odd_y;
Christian Heimes53876d92008-04-19 00:31:39 +00001781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy))
1783 return NULL;
1784 x = PyFloat_AsDouble(ox);
1785 y = PyFloat_AsDouble(oy);
1786 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1787 return NULL;
Christian Heimesa342c012008-04-20 21:01:16 +00001788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 /* deal directly with IEEE specials, to cope with problems on various
1790 platforms whose semantics don't exactly match C99 */
1791 r = 0.; /* silence compiler warning */
1792 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
1793 errno = 0;
1794 if (Py_IS_NAN(x))
1795 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
1796 else if (Py_IS_NAN(y))
1797 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
1798 else if (Py_IS_INFINITY(x)) {
1799 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
1800 if (y > 0.)
1801 r = odd_y ? x : fabs(x);
1802 else if (y == 0.)
1803 r = 1.;
1804 else /* y < 0. */
1805 r = odd_y ? copysign(0., x) : 0.;
1806 }
1807 else if (Py_IS_INFINITY(y)) {
1808 if (fabs(x) == 1.0)
1809 r = 1.;
1810 else if (y > 0. && fabs(x) > 1.0)
1811 r = y;
1812 else if (y < 0. && fabs(x) < 1.0) {
1813 r = -y; /* result is +inf */
1814 if (x == 0.) /* 0**-inf: divide-by-zero */
1815 errno = EDOM;
1816 }
1817 else
1818 r = 0.;
1819 }
1820 }
1821 else {
1822 /* let libm handle finite**finite */
1823 errno = 0;
1824 PyFPE_START_PROTECT("in math_pow", return 0);
1825 r = pow(x, y);
1826 PyFPE_END_PROTECT(r);
1827 /* a NaN result should arise only from (-ve)**(finite
1828 non-integer); in this case we want to raise ValueError. */
1829 if (!Py_IS_FINITE(r)) {
1830 if (Py_IS_NAN(r)) {
1831 errno = EDOM;
1832 }
1833 /*
1834 an infinite result here arises either from:
1835 (A) (+/-0.)**negative (-> divide-by-zero)
1836 (B) overflow of x**y with x and y finite
1837 */
1838 else if (Py_IS_INFINITY(r)) {
1839 if (x == 0.)
1840 errno = EDOM;
1841 else
1842 errno = ERANGE;
1843 }
1844 }
1845 }
Christian Heimes53876d92008-04-19 00:31:39 +00001846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 if (errno && is_error(r))
1848 return NULL;
1849 else
1850 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00001851}
1852
1853PyDoc_STRVAR(math_pow_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001854"pow(x, y)\n\nReturn x**y (x to the power of y).");
Christian Heimes53876d92008-04-19 00:31:39 +00001855
Christian Heimes072c0f12008-01-03 23:01:04 +00001856static const double degToRad = Py_MATH_PI / 180.0;
1857static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001858
1859static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001860math_degrees(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 double x = PyFloat_AsDouble(arg);
1863 if (x == -1.0 && PyErr_Occurred())
1864 return NULL;
1865 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001866}
1867
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001868PyDoc_STRVAR(math_degrees_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001869"degrees(x)\n\n\
1870Convert angle x from radians to degrees.");
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001871
1872static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001873math_radians(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001874{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 double x = PyFloat_AsDouble(arg);
1876 if (x == -1.0 && PyErr_Occurred())
1877 return NULL;
1878 return PyFloat_FromDouble(x * degToRad);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001879}
1880
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001881PyDoc_STRVAR(math_radians_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001882"radians(x)\n\n\
1883Convert angle x from degrees to radians.");
Tim Peters78526162001-09-05 00:53:45 +00001884
Christian Heimes072c0f12008-01-03 23:01:04 +00001885static PyObject *
Mark Dickinson8e0c9962010-07-11 17:38:24 +00001886math_isfinite(PyObject *self, PyObject *arg)
1887{
1888 double x = PyFloat_AsDouble(arg);
1889 if (x == -1.0 && PyErr_Occurred())
1890 return NULL;
1891 return PyBool_FromLong((long)Py_IS_FINITE(x));
1892}
1893
1894PyDoc_STRVAR(math_isfinite_doc,
1895"isfinite(x) -> bool\n\n\
Mark Dickinson226f5442010-07-11 18:13:41 +00001896Return True if x is neither an infinity nor a NaN, and False otherwise.");
Mark Dickinson8e0c9962010-07-11 17:38:24 +00001897
1898static PyObject *
Christian Heimes072c0f12008-01-03 23:01:04 +00001899math_isnan(PyObject *self, PyObject *arg)
1900{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 double x = PyFloat_AsDouble(arg);
1902 if (x == -1.0 && PyErr_Occurred())
1903 return NULL;
1904 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00001905}
1906
1907PyDoc_STRVAR(math_isnan_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001908"isnan(x) -> bool\n\n\
Mark Dickinson226f5442010-07-11 18:13:41 +00001909Return True if x is a NaN (not a number), and False otherwise.");
Christian Heimes072c0f12008-01-03 23:01:04 +00001910
1911static PyObject *
1912math_isinf(PyObject *self, PyObject *arg)
1913{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 double x = PyFloat_AsDouble(arg);
1915 if (x == -1.0 && PyErr_Occurred())
1916 return NULL;
1917 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00001918}
1919
1920PyDoc_STRVAR(math_isinf_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001921"isinf(x) -> bool\n\n\
Mark Dickinson226f5442010-07-11 18:13:41 +00001922Return True if x is a positive or negative infinity, and False otherwise.");
Christian Heimes072c0f12008-01-03 23:01:04 +00001923
Barry Warsaw8b43b191996-12-09 22:32:36 +00001924static PyMethodDef math_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 {"acos", math_acos, METH_O, math_acos_doc},
1926 {"acosh", math_acosh, METH_O, math_acosh_doc},
1927 {"asin", math_asin, METH_O, math_asin_doc},
1928 {"asinh", math_asinh, METH_O, math_asinh_doc},
1929 {"atan", math_atan, METH_O, math_atan_doc},
1930 {"atan2", math_atan2, METH_VARARGS, math_atan2_doc},
1931 {"atanh", math_atanh, METH_O, math_atanh_doc},
1932 {"ceil", math_ceil, METH_O, math_ceil_doc},
1933 {"copysign", math_copysign, METH_VARARGS, math_copysign_doc},
1934 {"cos", math_cos, METH_O, math_cos_doc},
1935 {"cosh", math_cosh, METH_O, math_cosh_doc},
1936 {"degrees", math_degrees, METH_O, math_degrees_doc},
1937 {"erf", math_erf, METH_O, math_erf_doc},
1938 {"erfc", math_erfc, METH_O, math_erfc_doc},
1939 {"exp", math_exp, METH_O, math_exp_doc},
1940 {"expm1", math_expm1, METH_O, math_expm1_doc},
1941 {"fabs", math_fabs, METH_O, math_fabs_doc},
1942 {"factorial", math_factorial, METH_O, math_factorial_doc},
1943 {"floor", math_floor, METH_O, math_floor_doc},
1944 {"fmod", math_fmod, METH_VARARGS, math_fmod_doc},
1945 {"frexp", math_frexp, METH_O, math_frexp_doc},
1946 {"fsum", math_fsum, METH_O, math_fsum_doc},
1947 {"gamma", math_gamma, METH_O, math_gamma_doc},
1948 {"hypot", math_hypot, METH_VARARGS, math_hypot_doc},
Mark Dickinson8e0c9962010-07-11 17:38:24 +00001949 {"isfinite", math_isfinite, METH_O, math_isfinite_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 {"isinf", math_isinf, METH_O, math_isinf_doc},
1951 {"isnan", math_isnan, METH_O, math_isnan_doc},
1952 {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc},
1953 {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
1954 {"log", math_log, METH_VARARGS, math_log_doc},
1955 {"log1p", math_log1p, METH_O, math_log1p_doc},
1956 {"log10", math_log10, METH_O, math_log10_doc},
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001957 {"log2", math_log2, METH_O, math_log2_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 {"modf", math_modf, METH_O, math_modf_doc},
1959 {"pow", math_pow, METH_VARARGS, math_pow_doc},
1960 {"radians", math_radians, METH_O, math_radians_doc},
1961 {"sin", math_sin, METH_O, math_sin_doc},
1962 {"sinh", math_sinh, METH_O, math_sinh_doc},
1963 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
1964 {"tan", math_tan, METH_O, math_tan_doc},
1965 {"tanh", math_tanh, METH_O, math_tanh_doc},
1966 {"trunc", math_trunc, METH_O, math_trunc_doc},
1967 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001968};
1969
Guido van Rossumc6e22901998-12-04 19:26:43 +00001970
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001971PyDoc_STRVAR(module_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001972"This module is always available. It provides access to the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001973"mathematical functions defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001974
Martin v. Löwis1a214512008-06-11 05:26:20 +00001975
1976static struct PyModuleDef mathmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 PyModuleDef_HEAD_INIT,
1978 "math",
1979 module_doc,
1980 -1,
1981 math_methods,
1982 NULL,
1983 NULL,
1984 NULL,
1985 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001986};
1987
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001988PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001989PyInit_math(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001990{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 PyObject *m;
Tim Petersfe71f812001-08-07 22:10:00 +00001992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 m = PyModule_Create(&mathmodule);
1994 if (m == NULL)
1995 goto finally;
Barry Warsawfc93f751996-12-17 00:47:03 +00001996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
1998 PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
Barry Warsawfc93f751996-12-17 00:47:03 +00001999
Christian Heimes53876d92008-04-19 00:31:39 +00002000 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002002}