blob: 4ef10d3d38937c2780f8334a1e7b9d9322925a57 [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
Christian Heimes969fe572008-01-25 11:23:10 +000058#ifdef _OSF_SOURCE
59/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
60extern double copysign(double, double);
61#endif
62
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000063/*
64 sin(pi*x), giving accurate results for all finite x (especially x
65 integral or close to an integer). This is here for use in the
66 reflection formula for the gamma function. It conforms to IEEE
67 754-2008 for finite arguments, but not for infinities or nans.
68*/
Tim Petersa40c7932001-09-05 22:36:56 +000069
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000070static const double pi = 3.141592653589793238462643383279502884197;
Mark Dickinson45f992a2009-12-19 11:20:49 +000071static const double sqrtpi = 1.772453850905516027298167483341145182798;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000072
73static double
74sinpi(double x)
75{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000076 double y, r;
77 int n;
78 /* this function should only ever be called for finite arguments */
79 assert(Py_IS_FINITE(x));
80 y = fmod(fabs(x), 2.0);
81 n = (int)round(2.0*y);
82 assert(0 <= n && n <= 4);
83 switch (n) {
84 case 0:
85 r = sin(pi*y);
86 break;
87 case 1:
88 r = cos(pi*(y-0.5));
89 break;
90 case 2:
91 /* N.B. -sin(pi*(y-1.0)) is *not* equivalent: it would give
92 -0.0 instead of 0.0 when y == 1.0. */
93 r = sin(pi*(1.0-y));
94 break;
95 case 3:
96 r = -cos(pi*(y-1.5));
97 break;
98 case 4:
99 r = sin(pi*(y-2.0));
100 break;
101 default:
102 assert(0); /* should never get here */
103 r = -1.23e200; /* silence gcc warning */
104 }
105 return copysign(1.0, x)*r;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000106}
107
108/* Implementation of the real gamma function. In extensive but non-exhaustive
109 random tests, this function proved accurate to within <= 10 ulps across the
110 entire float domain. Note that accuracy may depend on the quality of the
111 system math functions, the pow function in particular. Special cases
112 follow C99 annex F. The parameters and method are tailored to platforms
113 whose double format is the IEEE 754 binary64 format.
114
115 Method: for x > 0.0 we use the Lanczos approximation with parameters N=13
116 and g=6.024680040776729583740234375; these parameters are amongst those
117 used by the Boost library. Following Boost (again), we re-express the
118 Lanczos sum as a rational function, and compute it that way. The
119 coefficients below were computed independently using MPFR, and have been
120 double-checked against the coefficients in the Boost source code.
121
122 For x < 0.0 we use the reflection formula.
123
124 There's one minor tweak that deserves explanation: Lanczos' formula for
125 Gamma(x) involves computing pow(x+g-0.5, x-0.5) / exp(x+g-0.5). For many x
126 values, x+g-0.5 can be represented exactly. However, in cases where it
127 can't be represented exactly the small error in x+g-0.5 can be magnified
128 significantly by the pow and exp calls, especially for large x. A cheap
129 correction is to multiply by (1 + e*g/(x+g-0.5)), where e is the error
130 involved in the computation of x+g-0.5 (that is, e = computed value of
131 x+g-0.5 - exact value of x+g-0.5). Here's the proof:
132
133 Correction factor
134 -----------------
135 Write x+g-0.5 = y-e, where y is exactly representable as an IEEE 754
136 double, and e is tiny. Then:
137
138 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) = pow(y-e, x-0.5)/exp(y-e)
139 = pow(y, x-0.5)/exp(y) * C,
140
141 where the correction_factor C is given by
142
143 C = pow(1-e/y, x-0.5) * exp(e)
144
145 Since e is tiny, pow(1-e/y, x-0.5) ~ 1-(x-0.5)*e/y, and exp(x) ~ 1+e, so:
146
147 C ~ (1-(x-0.5)*e/y) * (1+e) ~ 1 + e*(y-(x-0.5))/y
148
149 But y-(x-0.5) = g+e, and g+e ~ g. So we get C ~ 1 + e*g/y, and
150
151 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) ~ pow(y, x-0.5)/exp(y) * (1 + e*g/y),
152
153 Note that for accuracy, when computing r*C it's better to do
154
155 r + e*g/y*r;
156
157 than
158
159 r * (1 + e*g/y);
160
161 since the addition in the latter throws away most of the bits of
162 information in e*g/y.
163*/
164
165#define LANCZOS_N 13
166static const double lanczos_g = 6.024680040776729583740234375;
167static const double lanczos_g_minus_half = 5.524680040776729583740234375;
168static const double lanczos_num_coeffs[LANCZOS_N] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 23531376880.410759688572007674451636754734846804940,
170 42919803642.649098768957899047001988850926355848959,
171 35711959237.355668049440185451547166705960488635843,
172 17921034426.037209699919755754458931112671403265390,
173 6039542586.3520280050642916443072979210699388420708,
174 1439720407.3117216736632230727949123939715485786772,
175 248874557.86205415651146038641322942321632125127801,
176 31426415.585400194380614231628318205362874684987640,
177 2876370.6289353724412254090516208496135991145378768,
178 186056.26539522349504029498971604569928220784236328,
179 8071.6720023658162106380029022722506138218516325024,
180 210.82427775157934587250973392071336271166969580291,
181 2.5066282746310002701649081771338373386264310793408
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000182};
183
184/* denominator is x*(x+1)*...*(x+LANCZOS_N-2) */
185static const double lanczos_den_coeffs[LANCZOS_N] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 0.0, 39916800.0, 120543840.0, 150917976.0, 105258076.0, 45995730.0,
187 13339535.0, 2637558.0, 357423.0, 32670.0, 1925.0, 66.0, 1.0};
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000188
189/* gamma values for small positive integers, 1 though NGAMMA_INTEGRAL */
190#define NGAMMA_INTEGRAL 23
191static const double gamma_integral[NGAMMA_INTEGRAL] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0,
193 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0,
194 1307674368000.0, 20922789888000.0, 355687428096000.0,
195 6402373705728000.0, 121645100408832000.0, 2432902008176640000.0,
196 51090942171709440000.0, 1124000727777607680000.0,
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000197};
198
199/* Lanczos' sum L_g(x), for positive x */
200
201static double
202lanczos_sum(double x)
203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 double num = 0.0, den = 0.0;
205 int i;
206 assert(x > 0.0);
207 /* evaluate the rational function lanczos_sum(x). For large
208 x, the obvious algorithm risks overflow, so we instead
209 rescale the denominator and numerator of the rational
210 function by x**(1-LANCZOS_N) and treat this as a
211 rational function in 1/x. This also reduces the error for
212 larger x values. The choice of cutoff point (5.0 below) is
213 somewhat arbitrary; in tests, smaller cutoff values than
214 this resulted in lower accuracy. */
215 if (x < 5.0) {
216 for (i = LANCZOS_N; --i >= 0; ) {
217 num = num * x + lanczos_num_coeffs[i];
218 den = den * x + lanczos_den_coeffs[i];
219 }
220 }
221 else {
222 for (i = 0; i < LANCZOS_N; i++) {
223 num = num / x + lanczos_num_coeffs[i];
224 den = den / x + lanczos_den_coeffs[i];
225 }
226 }
227 return num/den;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000228}
229
230static double
231m_tgamma(double x)
232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 double absx, r, y, z, sqrtpow;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 /* special cases */
236 if (!Py_IS_FINITE(x)) {
237 if (Py_IS_NAN(x) || x > 0.0)
238 return x; /* tgamma(nan) = nan, tgamma(inf) = inf */
239 else {
240 errno = EDOM;
241 return Py_NAN; /* tgamma(-inf) = nan, invalid */
242 }
243 }
244 if (x == 0.0) {
245 errno = EDOM;
246 return 1.0/x; /* tgamma(+-0.0) = +-inf, divide-by-zero */
247 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 /* integer arguments */
250 if (x == floor(x)) {
251 if (x < 0.0) {
252 errno = EDOM; /* tgamma(n) = nan, invalid for */
253 return Py_NAN; /* negative integers n */
254 }
255 if (x <= NGAMMA_INTEGRAL)
256 return gamma_integral[(int)x - 1];
257 }
258 absx = fabs(x);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 /* tiny arguments: tgamma(x) ~ 1/x for x near 0 */
261 if (absx < 1e-20) {
262 r = 1.0/x;
263 if (Py_IS_INFINITY(r))
264 errno = ERANGE;
265 return r;
266 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 /* large arguments: assuming IEEE 754 doubles, tgamma(x) overflows for
269 x > 200, and underflows to +-0.0 for x < -200, not a negative
270 integer. */
271 if (absx > 200.0) {
272 if (x < 0.0) {
273 return 0.0/sinpi(x);
274 }
275 else {
276 errno = ERANGE;
277 return Py_HUGE_VAL;
278 }
279 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 y = absx + lanczos_g_minus_half;
282 /* compute error in sum */
283 if (absx > lanczos_g_minus_half) {
284 /* note: the correction can be foiled by an optimizing
285 compiler that (incorrectly) thinks that an expression like
286 a + b - a - b can be optimized to 0.0. This shouldn't
287 happen in a standards-conforming compiler. */
288 double q = y - absx;
289 z = q - lanczos_g_minus_half;
290 }
291 else {
292 double q = y - lanczos_g_minus_half;
293 z = q - absx;
294 }
295 z = z * lanczos_g / y;
296 if (x < 0.0) {
297 r = -pi / sinpi(absx) / absx * exp(y) / lanczos_sum(absx);
298 r -= z * r;
299 if (absx < 140.0) {
300 r /= pow(y, absx - 0.5);
301 }
302 else {
303 sqrtpow = pow(y, absx / 2.0 - 0.25);
304 r /= sqrtpow;
305 r /= sqrtpow;
306 }
307 }
308 else {
309 r = lanczos_sum(absx) / exp(y);
310 r += z * r;
311 if (absx < 140.0) {
312 r *= pow(y, absx - 0.5);
313 }
314 else {
315 sqrtpow = pow(y, absx / 2.0 - 0.25);
316 r *= sqrtpow;
317 r *= sqrtpow;
318 }
319 }
320 if (Py_IS_INFINITY(r))
321 errno = ERANGE;
322 return r;
Guido van Rossum8832b621991-12-16 15:44:24 +0000323}
324
Christian Heimes53876d92008-04-19 00:31:39 +0000325/*
Mark Dickinson05d2e082009-12-11 20:17:17 +0000326 lgamma: natural log of the absolute value of the Gamma function.
327 For large arguments, Lanczos' formula works extremely well here.
328*/
329
330static double
331m_lgamma(double x)
332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 double r, absx;
Mark Dickinson05d2e082009-12-11 20:17:17 +0000334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 /* special cases */
336 if (!Py_IS_FINITE(x)) {
337 if (Py_IS_NAN(x))
338 return x; /* lgamma(nan) = nan */
339 else
340 return Py_HUGE_VAL; /* lgamma(+-inf) = +inf */
341 }
Mark Dickinson05d2e082009-12-11 20:17:17 +0000342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 /* integer arguments */
344 if (x == floor(x) && x <= 2.0) {
345 if (x <= 0.0) {
346 errno = EDOM; /* lgamma(n) = inf, divide-by-zero for */
347 return Py_HUGE_VAL; /* integers n <= 0 */
348 }
349 else {
350 return 0.0; /* lgamma(1) = lgamma(2) = 0.0 */
351 }
352 }
Mark Dickinson05d2e082009-12-11 20:17:17 +0000353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 absx = fabs(x);
355 /* tiny arguments: lgamma(x) ~ -log(fabs(x)) for small x */
356 if (absx < 1e-20)
357 return -log(absx);
Mark Dickinson05d2e082009-12-11 20:17:17 +0000358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 /* Lanczos' formula */
360 if (x > 0.0) {
361 /* we could save a fraction of a ulp in accuracy by having a
362 second set of numerator coefficients for lanczos_sum that
363 absorbed the exp(-lanczos_g) term, and throwing out the
364 lanczos_g subtraction below; it's probably not worth it. */
365 r = log(lanczos_sum(x)) - lanczos_g +
366 (x-0.5)*(log(x+lanczos_g-0.5)-1);
367 }
368 else {
369 r = log(pi) - log(fabs(sinpi(absx))) - log(absx) -
370 (log(lanczos_sum(absx)) - lanczos_g +
371 (absx-0.5)*(log(absx+lanczos_g-0.5)-1));
372 }
373 if (Py_IS_INFINITY(r))
374 errno = ERANGE;
375 return r;
Mark Dickinson05d2e082009-12-11 20:17:17 +0000376}
377
Mark Dickinson45f992a2009-12-19 11:20:49 +0000378/*
379 Implementations of the error function erf(x) and the complementary error
380 function erfc(x).
381
382 Method: following 'Numerical Recipes' by Flannery, Press et. al. (2nd ed.,
383 Cambridge University Press), we use a series approximation for erf for
384 small x, and a continued fraction approximation for erfc(x) for larger x;
385 combined with the relations erf(-x) = -erf(x) and erfc(x) = 1.0 - erf(x),
386 this gives us erf(x) and erfc(x) for all x.
387
388 The series expansion used is:
389
390 erf(x) = x*exp(-x*x)/sqrt(pi) * [
391 2/1 + 4/3 x**2 + 8/15 x**4 + 16/105 x**6 + ...]
392
393 The coefficient of x**(2k-2) here is 4**k*factorial(k)/factorial(2*k).
394 This series converges well for smallish x, but slowly for larger x.
395
396 The continued fraction expansion used is:
397
398 erfc(x) = x*exp(-x*x)/sqrt(pi) * [1/(0.5 + x**2 -) 0.5/(2.5 + x**2 - )
399 3.0/(4.5 + x**2 - ) 7.5/(6.5 + x**2 - ) ...]
400
401 after the first term, the general term has the form:
402
403 k*(k-0.5)/(2*k+0.5 + x**2 - ...).
404
405 This expansion converges fast for larger x, but convergence becomes
406 infinitely slow as x approaches 0.0. The (somewhat naive) continued
407 fraction evaluation algorithm used below also risks overflow for large x;
408 but for large x, erfc(x) == 0.0 to within machine precision. (For
409 example, erfc(30.0) is approximately 2.56e-393).
410
411 Parameters: use series expansion for abs(x) < ERF_SERIES_CUTOFF and
412 continued fraction expansion for ERF_SERIES_CUTOFF <= abs(x) <
413 ERFC_CONTFRAC_CUTOFF. ERFC_SERIES_TERMS and ERFC_CONTFRAC_TERMS are the
414 numbers of terms to use for the relevant expansions. */
415
416#define ERF_SERIES_CUTOFF 1.5
417#define ERF_SERIES_TERMS 25
418#define ERFC_CONTFRAC_CUTOFF 30.0
419#define ERFC_CONTFRAC_TERMS 50
420
421/*
422 Error function, via power series.
423
424 Given a finite float x, return an approximation to erf(x).
425 Converges reasonably fast for small x.
426*/
427
428static double
429m_erf_series(double x)
430{
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000431 double x2, acc, fk, result;
432 int i, saved_errno;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 x2 = x * x;
435 acc = 0.0;
436 fk = (double)ERF_SERIES_TERMS + 0.5;
437 for (i = 0; i < ERF_SERIES_TERMS; i++) {
438 acc = 2.0 + x2 * acc / fk;
439 fk -= 1.0;
440 }
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000441 /* Make sure the exp call doesn't affect errno;
442 see m_erfc_contfrac for more. */
443 saved_errno = errno;
444 result = acc * x * exp(-x2) / sqrtpi;
445 errno = saved_errno;
446 return result;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000447}
448
449/*
450 Complementary error function, via continued fraction expansion.
451
452 Given a positive float x, return an approximation to erfc(x). Converges
453 reasonably fast for x large (say, x > 2.0), and should be safe from
454 overflow if x and nterms are not too large. On an IEEE 754 machine, with x
455 <= 30.0, we're safe up to nterms = 100. For x >= 30.0, erfc(x) is smaller
456 than the smallest representable nonzero float. */
457
458static double
459m_erfc_contfrac(double x)
460{
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000461 double x2, a, da, p, p_last, q, q_last, b, result;
462 int i, saved_errno;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 if (x >= ERFC_CONTFRAC_CUTOFF)
465 return 0.0;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 x2 = x*x;
468 a = 0.0;
469 da = 0.5;
470 p = 1.0; p_last = 0.0;
471 q = da + x2; q_last = 1.0;
472 for (i = 0; i < ERFC_CONTFRAC_TERMS; i++) {
473 double temp;
474 a += da;
475 da += 2.0;
476 b = da + x2;
477 temp = p; p = b*p - a*p_last; p_last = temp;
478 temp = q; q = b*q - a*q_last; q_last = temp;
479 }
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000480 /* Issue #8986: On some platforms, exp sets errno on underflow to zero;
481 save the current errno value so that we can restore it later. */
482 saved_errno = errno;
483 result = p / q * x * exp(-x2) / sqrtpi;
484 errno = saved_errno;
485 return result;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000486}
487
488/* Error function erf(x), for general x */
489
490static double
491m_erf(double x)
492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 double absx, cf;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 if (Py_IS_NAN(x))
496 return x;
497 absx = fabs(x);
498 if (absx < ERF_SERIES_CUTOFF)
499 return m_erf_series(x);
500 else {
501 cf = m_erfc_contfrac(absx);
502 return x > 0.0 ? 1.0 - cf : cf - 1.0;
503 }
Mark Dickinson45f992a2009-12-19 11:20:49 +0000504}
505
506/* Complementary error function erfc(x), for general x. */
507
508static double
509m_erfc(double x)
510{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 double absx, cf;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 if (Py_IS_NAN(x))
514 return x;
515 absx = fabs(x);
516 if (absx < ERF_SERIES_CUTOFF)
517 return 1.0 - m_erf_series(x);
518 else {
519 cf = m_erfc_contfrac(absx);
520 return x > 0.0 ? cf : 2.0 - cf;
521 }
Mark Dickinson45f992a2009-12-19 11:20:49 +0000522}
Mark Dickinson05d2e082009-12-11 20:17:17 +0000523
524/*
Christian Heimese57950f2008-04-21 13:08:03 +0000525 wrapper for atan2 that deals directly with special cases before
526 delegating to the platform libm for the remaining cases. This
527 is necessary to get consistent behaviour across platforms.
528 Windows, FreeBSD and alpha Tru64 are amongst platforms that don't
529 always follow C99.
530*/
531
532static double
533m_atan2(double y, double x)
534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 if (Py_IS_NAN(x) || Py_IS_NAN(y))
536 return Py_NAN;
537 if (Py_IS_INFINITY(y)) {
538 if (Py_IS_INFINITY(x)) {
539 if (copysign(1., x) == 1.)
540 /* atan2(+-inf, +inf) == +-pi/4 */
541 return copysign(0.25*Py_MATH_PI, y);
542 else
543 /* atan2(+-inf, -inf) == +-pi*3/4 */
544 return copysign(0.75*Py_MATH_PI, y);
545 }
546 /* atan2(+-inf, x) == +-pi/2 for finite x */
547 return copysign(0.5*Py_MATH_PI, y);
548 }
549 if (Py_IS_INFINITY(x) || y == 0.) {
550 if (copysign(1., x) == 1.)
551 /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */
552 return copysign(0., y);
553 else
554 /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */
555 return copysign(Py_MATH_PI, y);
556 }
557 return atan2(y, x);
Christian Heimese57950f2008-04-21 13:08:03 +0000558}
559
560/*
Mark Dickinsone675f082008-12-11 21:56:00 +0000561 Various platforms (Solaris, OpenBSD) do nonstandard things for log(0),
562 log(-ve), log(NaN). Here are wrappers for log and log10 that deal with
563 special values directly, passing positive non-special values through to
564 the system log/log10.
565 */
566
567static double
568m_log(double x)
569{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 if (Py_IS_FINITE(x)) {
571 if (x > 0.0)
572 return log(x);
573 errno = EDOM;
574 if (x == 0.0)
575 return -Py_HUGE_VAL; /* log(0) = -inf */
576 else
577 return Py_NAN; /* log(-ve) = nan */
578 }
579 else if (Py_IS_NAN(x))
580 return x; /* log(nan) = nan */
581 else if (x > 0.0)
582 return x; /* log(inf) = inf */
583 else {
584 errno = EDOM;
585 return Py_NAN; /* log(-inf) = nan */
586 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000587}
588
589static double
590m_log10(double x)
591{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 if (Py_IS_FINITE(x)) {
593 if (x > 0.0)
594 return log10(x);
595 errno = EDOM;
596 if (x == 0.0)
597 return -Py_HUGE_VAL; /* log10(0) = -inf */
598 else
599 return Py_NAN; /* log10(-ve) = nan */
600 }
601 else if (Py_IS_NAN(x))
602 return x; /* log10(nan) = nan */
603 else if (x > 0.0)
604 return x; /* log10(inf) = inf */
605 else {
606 errno = EDOM;
607 return Py_NAN; /* log10(-inf) = nan */
608 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000609}
610
611
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000612/* Call is_error when errno != 0, and where x is the result libm
613 * returned. is_error will usually set up an exception and return
614 * true (1), but may return false (0) without setting up an exception.
615 */
616static int
617is_error(double x)
618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 int result = 1; /* presumption of guilt */
620 assert(errno); /* non-zero errno is a precondition for calling */
621 if (errno == EDOM)
622 PyErr_SetString(PyExc_ValueError, "math domain error");
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 else if (errno == ERANGE) {
625 /* ANSI C generally requires libm functions to set ERANGE
626 * on overflow, but also generally *allows* them to set
627 * ERANGE on underflow too. There's no consistency about
628 * the latter across platforms.
629 * Alas, C99 never requires that errno be set.
630 * Here we suppress the underflow errors (libm functions
631 * should return a zero on underflow, and +- HUGE_VAL on
632 * overflow, so testing the result for zero suffices to
633 * distinguish the cases).
634 *
635 * On some platforms (Ubuntu/ia64) it seems that errno can be
636 * set to ERANGE for subnormal results that do *not* underflow
637 * to zero. So to be safe, we'll ignore ERANGE whenever the
638 * function result is less than one in absolute value.
639 */
640 if (fabs(x) < 1.0)
641 result = 0;
642 else
643 PyErr_SetString(PyExc_OverflowError,
644 "math range error");
645 }
646 else
647 /* Unexpected math error */
648 PyErr_SetFromErrno(PyExc_ValueError);
649 return result;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000650}
651
Mark Dickinsone675f082008-12-11 21:56:00 +0000652/*
Christian Heimes53876d92008-04-19 00:31:39 +0000653 math_1 is used to wrap a libm function f that takes a double
654 arguments and returns a double.
655
656 The error reporting follows these rules, which are designed to do
657 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
658 platforms.
659
660 - a NaN result from non-NaN inputs causes ValueError to be raised
661 - an infinite result from finite inputs causes OverflowError to be
662 raised if can_overflow is 1, or raises ValueError if can_overflow
663 is 0.
664 - if the result is finite and errno == EDOM then ValueError is
665 raised
666 - if the result is finite and nonzero and errno == ERANGE then
667 OverflowError is raised
668
669 The last rule is used to catch overflow on platforms which follow
670 C89 but for which HUGE_VAL is not an infinity.
671
672 For the majority of one-argument functions these rules are enough
673 to ensure that Python's functions behave as specified in 'Annex F'
674 of the C99 standard, with the 'invalid' and 'divide-by-zero'
675 floating-point exceptions mapping to Python's ValueError and the
676 'overflow' floating-point exception mapping to OverflowError.
677 math_1 only works for functions that don't have singularities *and*
678 the possibility of overflow; fortunately, that covers everything we
679 care about right now.
680*/
681
Barry Warsaw8b43b191996-12-09 22:32:36 +0000682static PyObject *
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000683math_1_to_whatever(PyObject *arg, double (*func) (double),
Christian Heimes53876d92008-04-19 00:31:39 +0000684 PyObject *(*from_double_func) (double),
685 int can_overflow)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 double x, r;
688 x = PyFloat_AsDouble(arg);
689 if (x == -1.0 && PyErr_Occurred())
690 return NULL;
691 errno = 0;
692 PyFPE_START_PROTECT("in math_1", return 0);
693 r = (*func)(x);
694 PyFPE_END_PROTECT(r);
695 if (Py_IS_NAN(r) && !Py_IS_NAN(x)) {
696 PyErr_SetString(PyExc_ValueError,
697 "math domain error"); /* invalid arg */
698 return NULL;
699 }
700 if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) {
701 if (can_overflow)
702 PyErr_SetString(PyExc_OverflowError,
703 "math range error"); /* overflow */
704 else
705 PyErr_SetString(PyExc_ValueError,
706 "math domain error"); /* singularity */
707 return NULL;
708 }
709 if (Py_IS_FINITE(r) && errno && is_error(r))
710 /* this branch unnecessary on most platforms */
711 return NULL;
Mark Dickinsonde429622008-05-01 00:19:23 +0000712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 return (*from_double_func)(r);
Christian Heimes53876d92008-04-19 00:31:39 +0000714}
715
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000716/* variant of math_1, to be used when the function being wrapped is known to
717 set errno properly (that is, errno = EDOM for invalid or divide-by-zero,
718 errno = ERANGE for overflow). */
719
720static PyObject *
721math_1a(PyObject *arg, double (*func) (double))
722{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 double x, r;
724 x = PyFloat_AsDouble(arg);
725 if (x == -1.0 && PyErr_Occurred())
726 return NULL;
727 errno = 0;
728 PyFPE_START_PROTECT("in math_1a", return 0);
729 r = (*func)(x);
730 PyFPE_END_PROTECT(r);
731 if (errno && is_error(r))
732 return NULL;
733 return PyFloat_FromDouble(r);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000734}
735
Christian Heimes53876d92008-04-19 00:31:39 +0000736/*
737 math_2 is used to wrap a libm function f that takes two double
738 arguments and returns a double.
739
740 The error reporting follows these rules, which are designed to do
741 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
742 platforms.
743
744 - a NaN result from non-NaN inputs causes ValueError to be raised
745 - an infinite result from finite inputs causes OverflowError to be
746 raised.
747 - if the result is finite and errno == EDOM then ValueError is
748 raised
749 - if the result is finite and nonzero and errno == ERANGE then
750 OverflowError is raised
751
752 The last rule is used to catch overflow on platforms which follow
753 C89 but for which HUGE_VAL is not an infinity.
754
755 For most two-argument functions (copysign, fmod, hypot, atan2)
756 these rules are enough to ensure that Python's functions behave as
757 specified in 'Annex F' of the C99 standard, with the 'invalid' and
758 'divide-by-zero' floating-point exceptions mapping to Python's
759 ValueError and the 'overflow' floating-point exception mapping to
760 OverflowError.
761*/
762
763static PyObject *
764math_1(PyObject *arg, double (*func) (double), int can_overflow)
765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow);
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000767}
768
769static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000770math_1_to_int(PyObject *arg, double (*func) (double), int can_overflow)
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000771{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 return math_1_to_whatever(arg, func, PyLong_FromDouble, can_overflow);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000773}
774
Barry Warsaw8b43b191996-12-09 22:32:36 +0000775static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +0000776math_2(PyObject *args, double (*func) (double, double), char *funcname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 PyObject *ox, *oy;
779 double x, y, r;
780 if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy))
781 return NULL;
782 x = PyFloat_AsDouble(ox);
783 y = PyFloat_AsDouble(oy);
784 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
785 return NULL;
786 errno = 0;
787 PyFPE_START_PROTECT("in math_2", return 0);
788 r = (*func)(x, y);
789 PyFPE_END_PROTECT(r);
790 if (Py_IS_NAN(r)) {
791 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
792 errno = EDOM;
793 else
794 errno = 0;
795 }
796 else if (Py_IS_INFINITY(r)) {
797 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
798 errno = ERANGE;
799 else
800 errno = 0;
801 }
802 if (errno && is_error(r))
803 return NULL;
804 else
805 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000806}
807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808#define FUNC1(funcname, func, can_overflow, docstring) \
809 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
810 return math_1(args, func, can_overflow); \
811 }\
812 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814#define FUNC1A(funcname, func, docstring) \
815 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
816 return math_1a(args, func); \
817 }\
818 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000819
Fred Drake40c48682000-07-03 18:11:56 +0000820#define FUNC2(funcname, func, docstring) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
822 return math_2(args, func, #funcname); \
823 }\
824 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000825
Christian Heimes53876d92008-04-19 00:31:39 +0000826FUNC1(acos, acos, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000827 "acos(x)\n\nReturn the arc cosine (measured in radians) of x.")
Mark Dickinsonf3718592009-12-21 15:27:41 +0000828FUNC1(acosh, m_acosh, 0,
Christian Heimes53876d92008-04-19 00:31:39 +0000829 "acosh(x)\n\nReturn the hyperbolic arc cosine (measured in radians) of x.")
830FUNC1(asin, asin, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000831 "asin(x)\n\nReturn the arc sine (measured in radians) of x.")
Mark Dickinsonf3718592009-12-21 15:27:41 +0000832FUNC1(asinh, m_asinh, 0,
Christian Heimes53876d92008-04-19 00:31:39 +0000833 "asinh(x)\n\nReturn the hyperbolic arc sine (measured in radians) of x.")
834FUNC1(atan, atan, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000835 "atan(x)\n\nReturn the arc tangent (measured in radians) of x.")
Christian Heimese57950f2008-04-21 13:08:03 +0000836FUNC2(atan2, m_atan2,
Tim Petersfe71f812001-08-07 22:10:00 +0000837 "atan2(y, x)\n\nReturn the arc tangent (measured in radians) of y/x.\n"
838 "Unlike atan(y/x), the signs of both x and y are considered.")
Mark Dickinsonf3718592009-12-21 15:27:41 +0000839FUNC1(atanh, m_atanh, 0,
Christian Heimes53876d92008-04-19 00:31:39 +0000840 "atanh(x)\n\nReturn the hyperbolic arc tangent (measured in radians) of x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +0000841
842static PyObject * math_ceil(PyObject *self, PyObject *number) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 static PyObject *ceil_str = NULL;
Mark Dickinson6d02d9c2010-07-02 16:05:15 +0000844 PyObject *method, *result;
Guido van Rossum13e05de2007-08-23 22:56:55 +0000845
Benjamin Petersonf751bc92010-07-02 13:46:42 +0000846 method = _PyObject_LookupSpecial(number, "__ceil__", &ceil_str);
847 if (method == NULL) {
848 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 return math_1_to_int(number, ceil, 0);
Benjamin Petersonf751bc92010-07-02 13:46:42 +0000851 }
Mark Dickinson6d02d9c2010-07-02 16:05:15 +0000852 result = PyObject_CallFunctionObjArgs(method, NULL);
853 Py_DECREF(method);
854 return result;
Guido van Rossum13e05de2007-08-23 22:56:55 +0000855}
856
857PyDoc_STRVAR(math_ceil_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 "ceil(x)\n\nReturn the ceiling of x as an int.\n"
859 "This is the smallest integral value >= x.");
Guido van Rossum13e05de2007-08-23 22:56:55 +0000860
Christian Heimes072c0f12008-01-03 23:01:04 +0000861FUNC2(copysign, copysign,
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000862 "copysign(x, y)\n\nReturn x with the sign of y.")
Christian Heimes53876d92008-04-19 00:31:39 +0000863FUNC1(cos, cos, 0,
864 "cos(x)\n\nReturn the cosine of x (measured in radians).")
865FUNC1(cosh, cosh, 1,
866 "cosh(x)\n\nReturn the hyperbolic cosine of x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +0000867FUNC1A(erf, m_erf,
868 "erf(x)\n\nError function at x.")
869FUNC1A(erfc, m_erfc,
870 "erfc(x)\n\nComplementary error function at x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000871FUNC1(exp, exp, 1,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000872 "exp(x)\n\nReturn e raised to the power of x.")
Mark Dickinson664b5112009-12-16 20:23:42 +0000873FUNC1(expm1, m_expm1, 1,
874 "expm1(x)\n\nReturn exp(x)-1.\n"
875 "This function avoids the loss of precision involved in the direct "
876 "evaluation of exp(x)-1 for small x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000877FUNC1(fabs, fabs, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000878 "fabs(x)\n\nReturn the absolute value of the float x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +0000879
880static PyObject * math_floor(PyObject *self, PyObject *number) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 static PyObject *floor_str = NULL;
Benjamin Petersonb0125892010-07-02 13:35:17 +0000882 PyObject *method, *result;
Guido van Rossum13e05de2007-08-23 22:56:55 +0000883
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +0000884 method = _PyObject_LookupSpecial(number, "__floor__", &floor_str);
885 if (method == NULL) {
886 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 return math_1_to_int(number, floor, 0);
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +0000889 }
Benjamin Petersonb0125892010-07-02 13:35:17 +0000890 result = PyObject_CallFunctionObjArgs(method, NULL);
891 Py_DECREF(method);
892 return result;
Guido van Rossum13e05de2007-08-23 22:56:55 +0000893}
894
895PyDoc_STRVAR(math_floor_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 "floor(x)\n\nReturn the floor of x as an int.\n"
897 "This is the largest integral value <= x.");
Guido van Rossum13e05de2007-08-23 22:56:55 +0000898
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000899FUNC1A(gamma, m_tgamma,
900 "gamma(x)\n\nGamma function at x.")
Mark Dickinson05d2e082009-12-11 20:17:17 +0000901FUNC1A(lgamma, m_lgamma,
902 "lgamma(x)\n\nNatural logarithm of absolute value of Gamma function at x.")
Mark Dickinsonf3718592009-12-21 15:27:41 +0000903FUNC1(log1p, m_log1p, 1,
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000904 "log1p(x)\n\nReturn the natural logarithm of 1+x (base e).\n"
905 "The result is computed in a way which is accurate for x near zero.")
Christian Heimes53876d92008-04-19 00:31:39 +0000906FUNC1(sin, sin, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000907 "sin(x)\n\nReturn the sine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +0000908FUNC1(sinh, sinh, 1,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000909 "sinh(x)\n\nReturn the hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000910FUNC1(sqrt, sqrt, 0,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000911 "sqrt(x)\n\nReturn the square root of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000912FUNC1(tan, tan, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000913 "tan(x)\n\nReturn the tangent of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +0000914FUNC1(tanh, tanh, 0,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000915 "tanh(x)\n\nReturn the hyperbolic tangent of x.")
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000916
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000917/* Precision summation function as msum() by Raymond Hettinger in
918 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
919 enhanced with the exact partials sum and roundoff from Mark
920 Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
921 See those links for more details, proofs and other references.
922
923 Note 1: IEEE 754R floating point semantics are assumed,
924 but the current implementation does not re-establish special
925 value semantics across iterations (i.e. handling -Inf + Inf).
926
927 Note 2: No provision is made for intermediate overflow handling;
Georg Brandlf78e02b2008-06-10 17:40:04 +0000928 therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000929 sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
930 overflow of the first partial sum.
931
Benjamin Petersonfea6a942008-07-02 16:11:42 +0000932 Note 3: The intermediate values lo, yr, and hi are declared volatile so
933 aggressive compilers won't algebraically reduce lo to always be exactly 0.0.
Georg Brandlf78e02b2008-06-10 17:40:04 +0000934 Also, the volatile declaration forces the values to be stored in memory as
935 regular doubles instead of extended long precision (80-bit) values. This
Benjamin Petersonfea6a942008-07-02 16:11:42 +0000936 prevents double rounding because any addition or subtraction of two doubles
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 can be resolved exactly into double-sized hi and lo values. As long as the
Georg Brandlf78e02b2008-06-10 17:40:04 +0000938 hi value gets forced into a double before yr and lo are computed, the extra
939 bits in downstream extended precision operations (x87 for example) will be
940 exactly zero and therefore can be losslessly stored back into a double,
941 thereby preventing double rounding.
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000942
943 Note 4: A similar implementation is in Modules/cmathmodule.c.
944 Be sure to update both when making changes.
945
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000946 Note 5: The signature of math.fsum() differs from __builtin__.sum()
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000947 because the start argument doesn't make sense in the context of
948 accurate summation. Since the partials table is collapsed before
949 returning a result, sum(seq2, start=sum(seq1)) may not equal the
950 accurate result returned by sum(itertools.chain(seq1, seq2)).
951*/
952
953#define NUM_PARTIALS 32 /* initial partials array size, on stack */
954
955/* Extend the partials array p[] by doubling its size. */
956static int /* non-zero on error */
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000957_fsum_realloc(double **p_ptr, Py_ssize_t n,
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000958 double *ps, Py_ssize_t *m_ptr)
959{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 void *v = NULL;
961 Py_ssize_t m = *m_ptr;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 m += m; /* double */
964 if (n < m && m < (PY_SSIZE_T_MAX / sizeof(double))) {
965 double *p = *p_ptr;
966 if (p == ps) {
967 v = PyMem_Malloc(sizeof(double) * m);
968 if (v != NULL)
969 memcpy(v, ps, sizeof(double) * n);
970 }
971 else
972 v = PyMem_Realloc(p, sizeof(double) * m);
973 }
974 if (v == NULL) { /* size overflow or no memory */
975 PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
976 return 1;
977 }
978 *p_ptr = (double*) v;
979 *m_ptr = m;
980 return 0;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000981}
982
983/* Full precision summation of a sequence of floats.
984
985 def msum(iterable):
986 partials = [] # sorted, non-overlapping partial sums
987 for x in iterable:
Mark Dickinsonfdb0acc2010-06-25 20:22:24 +0000988 i = 0
989 for y in partials:
990 if abs(x) < abs(y):
991 x, y = y, x
992 hi = x + y
993 lo = y - (hi - x)
994 if lo:
995 partials[i] = lo
996 i += 1
997 x = hi
998 partials[i:] = [x]
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000999 return sum_exact(partials)
1000
1001 Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
1002 are exactly equal to x+y. The inner loop applies hi/lo summation to each
1003 partial so that the list of partial sums remains exact.
1004
1005 Sum_exact() adds the partial sums exactly and correctly rounds the final
1006 result (using the round-half-to-even rule). The items in partials remain
1007 non-zero, non-special, non-overlapping and strictly increasing in
1008 magnitude, but possibly not all having the same sign.
1009
1010 Depends on IEEE 754 arithmetic guarantees and half-even rounding.
1011*/
1012
1013static PyObject*
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001014math_fsum(PyObject *self, PyObject *seq)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001015{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 PyObject *item, *iter, *sum = NULL;
1017 Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
1018 double x, y, t, ps[NUM_PARTIALS], *p = ps;
1019 double xsave, special_sum = 0.0, inf_sum = 0.0;
1020 volatile double hi, yr, lo;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 iter = PyObject_GetIter(seq);
1023 if (iter == NULL)
1024 return NULL;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 for(;;) { /* for x in iterable */
1029 assert(0 <= n && n <= m);
1030 assert((m == NUM_PARTIALS && p == ps) ||
1031 (m > NUM_PARTIALS && p != NULL));
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 item = PyIter_Next(iter);
1034 if (item == NULL) {
1035 if (PyErr_Occurred())
1036 goto _fsum_error;
1037 break;
1038 }
1039 x = PyFloat_AsDouble(item);
1040 Py_DECREF(item);
1041 if (PyErr_Occurred())
1042 goto _fsum_error;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 xsave = x;
1045 for (i = j = 0; j < n; j++) { /* for y in partials */
1046 y = p[j];
1047 if (fabs(x) < fabs(y)) {
1048 t = x; x = y; y = t;
1049 }
1050 hi = x + y;
1051 yr = hi - x;
1052 lo = y - yr;
1053 if (lo != 0.0)
1054 p[i++] = lo;
1055 x = hi;
1056 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 n = i; /* ps[i:] = [x] */
1059 if (x != 0.0) {
1060 if (! Py_IS_FINITE(x)) {
1061 /* a nonfinite x could arise either as
1062 a result of intermediate overflow, or
1063 as a result of a nan or inf in the
1064 summands */
1065 if (Py_IS_FINITE(xsave)) {
1066 PyErr_SetString(PyExc_OverflowError,
1067 "intermediate overflow in fsum");
1068 goto _fsum_error;
1069 }
1070 if (Py_IS_INFINITY(xsave))
1071 inf_sum += xsave;
1072 special_sum += xsave;
1073 /* reset partials */
1074 n = 0;
1075 }
1076 else if (n >= m && _fsum_realloc(&p, n, ps, &m))
1077 goto _fsum_error;
1078 else
1079 p[n++] = x;
1080 }
1081 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 if (special_sum != 0.0) {
1084 if (Py_IS_NAN(inf_sum))
1085 PyErr_SetString(PyExc_ValueError,
1086 "-inf + inf in fsum");
1087 else
1088 sum = PyFloat_FromDouble(special_sum);
1089 goto _fsum_error;
1090 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 hi = 0.0;
1093 if (n > 0) {
1094 hi = p[--n];
1095 /* sum_exact(ps, hi) from the top, stop when the sum becomes
1096 inexact. */
1097 while (n > 0) {
1098 x = hi;
1099 y = p[--n];
1100 assert(fabs(y) < fabs(x));
1101 hi = x + y;
1102 yr = hi - x;
1103 lo = y - yr;
1104 if (lo != 0.0)
1105 break;
1106 }
1107 /* Make half-even rounding work across multiple partials.
1108 Needed so that sum([1e-16, 1, 1e16]) will round-up the last
1109 digit to two instead of down to zero (the 1e-16 makes the 1
1110 slightly closer to two). With a potential 1 ULP rounding
1111 error fixed-up, math.fsum() can guarantee commutativity. */
1112 if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
1113 (lo > 0.0 && p[n-1] > 0.0))) {
1114 y = lo * 2.0;
1115 x = hi + y;
1116 yr = x - hi;
1117 if (y == yr)
1118 hi = x;
1119 }
1120 }
1121 sum = PyFloat_FromDouble(hi);
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001122
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001123_fsum_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 PyFPE_END_PROTECT(hi)
1125 Py_DECREF(iter);
1126 if (p != ps)
1127 PyMem_Free(p);
1128 return sum;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001129}
1130
1131#undef NUM_PARTIALS
1132
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001133PyDoc_STRVAR(math_fsum_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001134"fsum(iterable)\n\n\
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001135Return an accurate floating point sum of values in the iterable.\n\
1136Assumes IEEE-754 floating point arithmetic.");
1137
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001138/* Return the smallest integer k such that n < 2**k, or 0 if n == 0.
1139 * Equivalent to floor(lg(x))+1. Also equivalent to: bitwidth_of_type -
1140 * count_leading_zero_bits(x)
1141 */
1142
1143/* XXX: This routine does more or less the same thing as
1144 * bits_in_digit() in Objects/longobject.c. Someday it would be nice to
1145 * consolidate them. On BSD, there's a library function called fls()
1146 * that we could use, and GCC provides __builtin_clz().
1147 */
1148
1149static unsigned long
1150bit_length(unsigned long n)
1151{
1152 unsigned long len = 0;
1153 while (n != 0) {
1154 ++len;
1155 n >>= 1;
1156 }
1157 return len;
1158}
1159
1160static unsigned long
1161count_set_bits(unsigned long n)
1162{
1163 unsigned long count = 0;
1164 while (n != 0) {
1165 ++count;
1166 n &= n - 1; /* clear least significant bit */
1167 }
1168 return count;
1169}
1170
1171/* Divide-and-conquer factorial algorithm
1172 *
1173 * Based on the formula and psuedo-code provided at:
1174 * http://www.luschny.de/math/factorial/binarysplitfact.html
1175 *
1176 * Faster algorithms exist, but they're more complicated and depend on
1177 * a fast prime factoriazation algorithm.
1178 *
1179 * Notes on the algorithm
1180 * ----------------------
1181 *
1182 * factorial(n) is written in the form 2**k * m, with m odd. k and m are
1183 * computed separately, and then combined using a left shift.
1184 *
1185 * The function factorial_odd_part computes the odd part m (i.e., the greatest
1186 * odd divisor) of factorial(n), using the formula:
1187 *
1188 * factorial_odd_part(n) =
1189 *
1190 * product_{i >= 0} product_{0 < j <= n / 2**i, j odd} j
1191 *
1192 * Example: factorial_odd_part(20) =
1193 *
1194 * (1) *
1195 * (1) *
1196 * (1 * 3 * 5) *
1197 * (1 * 3 * 5 * 7 * 9)
1198 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1199 *
1200 * Here i goes from large to small: the first term corresponds to i=4 (any
1201 * larger i gives an empty product), and the last term corresponds to i=0.
1202 * Each term can be computed from the last by multiplying by the extra odd
1203 * numbers required: e.g., to get from the penultimate term to the last one,
1204 * we multiply by (11 * 13 * 15 * 17 * 19).
1205 *
1206 * To see a hint of why this formula works, here are the same numbers as above
1207 * but with the even parts (i.e., the appropriate powers of 2) included. For
1208 * each subterm in the product for i, we multiply that subterm by 2**i:
1209 *
1210 * factorial(20) =
1211 *
1212 * (16) *
1213 * (8) *
1214 * (4 * 12 * 20) *
1215 * (2 * 6 * 10 * 14 * 18) *
1216 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1217 *
1218 * The factorial_partial_product function computes the product of all odd j in
1219 * range(start, stop) for given start and stop. It's used to compute the
1220 * partial products like (11 * 13 * 15 * 17 * 19) in the example above. It
1221 * operates recursively, repeatedly splitting the range into two roughly equal
1222 * pieces until the subranges are small enough to be computed using only C
1223 * integer arithmetic.
1224 *
1225 * The two-valuation k (i.e., the exponent of the largest power of 2 dividing
1226 * the factorial) is computed independently in the main math_factorial
1227 * function. By standard results, its value is:
1228 *
1229 * two_valuation = n//2 + n//4 + n//8 + ....
1230 *
1231 * It can be shown (e.g., by complete induction on n) that two_valuation is
1232 * equal to n - count_set_bits(n), where count_set_bits(n) gives the number of
1233 * '1'-bits in the binary expansion of n.
1234 */
1235
1236/* factorial_partial_product: Compute product(range(start, stop, 2)) using
1237 * divide and conquer. Assumes start and stop are odd and stop > start.
1238 * max_bits must be >= bit_length(stop - 2). */
1239
1240static PyObject *
1241factorial_partial_product(unsigned long start, unsigned long stop,
1242 unsigned long max_bits)
1243{
1244 unsigned long midpoint, num_operands;
1245 PyObject *left = NULL, *right = NULL, *result = NULL;
1246
1247 /* If the return value will fit an unsigned long, then we can
1248 * multiply in a tight, fast loop where each multiply is O(1).
1249 * Compute an upper bound on the number of bits required to store
1250 * the answer.
1251 *
1252 * Storing some integer z requires floor(lg(z))+1 bits, which is
1253 * conveniently the value returned by bit_length(z). The
1254 * product x*y will require at most
1255 * bit_length(x) + bit_length(y) bits to store, based
1256 * on the idea that lg product = lg x + lg y.
1257 *
1258 * We know that stop - 2 is the largest number to be multiplied. From
1259 * there, we have: bit_length(answer) <= num_operands *
1260 * bit_length(stop - 2)
1261 */
1262
1263 num_operands = (stop - start) / 2;
1264 /* The "num_operands <= 8 * SIZEOF_LONG" check guards against the
1265 * unlikely case of an overflow in num_operands * max_bits. */
1266 if (num_operands <= 8 * SIZEOF_LONG &&
1267 num_operands * max_bits <= 8 * SIZEOF_LONG) {
1268 unsigned long j, total;
1269 for (total = start, j = start + 2; j < stop; j += 2)
1270 total *= j;
1271 return PyLong_FromUnsignedLong(total);
1272 }
1273
1274 /* find midpoint of range(start, stop), rounded up to next odd number. */
1275 midpoint = (start + num_operands) | 1;
1276 left = factorial_partial_product(start, midpoint,
1277 bit_length(midpoint - 2));
1278 if (left == NULL)
1279 goto error;
1280 right = factorial_partial_product(midpoint, stop, max_bits);
1281 if (right == NULL)
1282 goto error;
1283 result = PyNumber_Multiply(left, right);
1284
1285 error:
1286 Py_XDECREF(left);
1287 Py_XDECREF(right);
1288 return result;
1289}
1290
1291/* factorial_odd_part: compute the odd part of factorial(n). */
1292
1293static PyObject *
1294factorial_odd_part(unsigned long n)
1295{
1296 long i;
1297 unsigned long v, lower, upper;
1298 PyObject *partial, *tmp, *inner, *outer;
1299
1300 inner = PyLong_FromLong(1);
1301 if (inner == NULL)
1302 return NULL;
1303 outer = inner;
1304 Py_INCREF(outer);
1305
1306 upper = 3;
1307 for (i = bit_length(n) - 2; i >= 0; i--) {
1308 v = n >> i;
1309 if (v <= 2)
1310 continue;
1311 lower = upper;
1312 /* (v + 1) | 1 = least odd integer strictly larger than n / 2**i */
1313 upper = (v + 1) | 1;
1314 /* Here inner is the product of all odd integers j in the range (0,
1315 n/2**(i+1)]. The factorial_partial_product call below gives the
1316 product of all odd integers j in the range (n/2**(i+1), n/2**i]. */
1317 partial = factorial_partial_product(lower, upper, bit_length(upper-2));
1318 /* inner *= partial */
1319 if (partial == NULL)
1320 goto error;
1321 tmp = PyNumber_Multiply(inner, partial);
1322 Py_DECREF(partial);
1323 if (tmp == NULL)
1324 goto error;
1325 Py_DECREF(inner);
1326 inner = tmp;
1327 /* Now inner is the product of all odd integers j in the range (0,
1328 n/2**i], giving the inner product in the formula above. */
1329
1330 /* outer *= inner; */
1331 tmp = PyNumber_Multiply(outer, inner);
1332 if (tmp == NULL)
1333 goto error;
1334 Py_DECREF(outer);
1335 outer = tmp;
1336 }
1337
1338 goto done;
1339
1340 error:
1341 Py_DECREF(outer);
1342 done:
1343 Py_DECREF(inner);
1344 return outer;
1345}
1346
1347/* Lookup table for small factorial values */
1348
1349static const unsigned long SmallFactorials[] = {
1350 1, 1, 2, 6, 24, 120, 720, 5040, 40320,
1351 362880, 3628800, 39916800, 479001600,
1352#if SIZEOF_LONG >= 8
1353 6227020800, 87178291200, 1307674368000,
1354 20922789888000, 355687428096000, 6402373705728000,
1355 121645100408832000, 2432902008176640000
1356#endif
1357};
1358
Barry Warsaw8b43b191996-12-09 22:32:36 +00001359static PyObject *
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001360math_factorial(PyObject *self, PyObject *arg)
1361{
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001362 long x;
1363 PyObject *result, *odd_part, *two_valuation;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 if (PyFloat_Check(arg)) {
1366 PyObject *lx;
1367 double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
1368 if (!(Py_IS_FINITE(dx) && dx == floor(dx))) {
1369 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001370 "factorial() only accepts integral values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 return NULL;
1372 }
1373 lx = PyLong_FromDouble(dx);
1374 if (lx == NULL)
1375 return NULL;
1376 x = PyLong_AsLong(lx);
1377 Py_DECREF(lx);
1378 }
1379 else
1380 x = PyLong_AsLong(arg);
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 if (x == -1 && PyErr_Occurred())
1383 return NULL;
1384 if (x < 0) {
1385 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001386 "factorial() not defined for negative values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 return NULL;
1388 }
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001389
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001390 /* use lookup table if x is small */
1391 if (x < (long)(sizeof(SmallFactorials)/sizeof(SmallFactorials[0])))
1392 return PyLong_FromUnsignedLong(SmallFactorials[x]);
1393
1394 /* else express in the form odd_part * 2**two_valuation, and compute as
1395 odd_part << two_valuation. */
1396 odd_part = factorial_odd_part(x);
1397 if (odd_part == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 return NULL;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001399 two_valuation = PyLong_FromLong(x - count_set_bits(x));
1400 if (two_valuation == NULL) {
1401 Py_DECREF(odd_part);
1402 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 }
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001404 result = PyNumber_Lshift(odd_part, two_valuation);
1405 Py_DECREF(two_valuation);
1406 Py_DECREF(odd_part);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 return result;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001408}
1409
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001410PyDoc_STRVAR(math_factorial_doc,
1411"factorial(x) -> Integral\n"
1412"\n"
1413"Find x!. Raise a ValueError if x is negative or non-integral.");
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001414
1415static PyObject *
Christian Heimes400adb02008-02-01 08:12:03 +00001416math_trunc(PyObject *self, PyObject *number)
1417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 static PyObject *trunc_str = NULL;
Benjamin Petersonb0125892010-07-02 13:35:17 +00001419 PyObject *trunc, *result;
Christian Heimes400adb02008-02-01 08:12:03 +00001420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 if (Py_TYPE(number)->tp_dict == NULL) {
1422 if (PyType_Ready(Py_TYPE(number)) < 0)
1423 return NULL;
1424 }
Christian Heimes400adb02008-02-01 08:12:03 +00001425
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001426 trunc = _PyObject_LookupSpecial(number, "__trunc__", &trunc_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 if (trunc == NULL) {
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001428 if (!PyErr_Occurred())
1429 PyErr_Format(PyExc_TypeError,
1430 "type %.100s doesn't define __trunc__ method",
1431 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 return NULL;
1433 }
Benjamin Petersonb0125892010-07-02 13:35:17 +00001434 result = PyObject_CallFunctionObjArgs(trunc, NULL);
1435 Py_DECREF(trunc);
1436 return result;
Christian Heimes400adb02008-02-01 08:12:03 +00001437}
1438
1439PyDoc_STRVAR(math_trunc_doc,
1440"trunc(x:Real) -> Integral\n"
1441"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001442"Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.");
Christian Heimes400adb02008-02-01 08:12:03 +00001443
1444static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001445math_frexp(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001446{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 int i;
1448 double x = PyFloat_AsDouble(arg);
1449 if (x == -1.0 && PyErr_Occurred())
1450 return NULL;
1451 /* deal with special cases directly, to sidestep platform
1452 differences */
1453 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
1454 i = 0;
1455 }
1456 else {
1457 PyFPE_START_PROTECT("in math_frexp", return 0);
1458 x = frexp(x, &i);
1459 PyFPE_END_PROTECT(x);
1460 }
1461 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001462}
1463
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001464PyDoc_STRVAR(math_frexp_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001465"frexp(x)\n"
1466"\n"
1467"Return the mantissa and exponent of x, as pair (m, e).\n"
1468"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 +00001469"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 +00001470
Barry Warsaw8b43b191996-12-09 22:32:36 +00001471static PyObject *
Fred Drake40c48682000-07-03 18:11:56 +00001472math_ldexp(PyObject *self, PyObject *args)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001473{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 double x, r;
1475 PyObject *oexp;
1476 long exp;
1477 int overflow;
1478 if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp))
1479 return NULL;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 if (PyLong_Check(oexp)) {
1482 /* on overflow, replace exponent with either LONG_MAX
1483 or LONG_MIN, depending on the sign. */
1484 exp = PyLong_AsLongAndOverflow(oexp, &overflow);
1485 if (exp == -1 && PyErr_Occurred())
1486 return NULL;
1487 if (overflow)
1488 exp = overflow < 0 ? LONG_MIN : LONG_MAX;
1489 }
1490 else {
1491 PyErr_SetString(PyExc_TypeError,
1492 "Expected an int or long as second argument "
1493 "to ldexp.");
1494 return NULL;
1495 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 if (x == 0. || !Py_IS_FINITE(x)) {
1498 /* NaNs, zeros and infinities are returned unchanged */
1499 r = x;
1500 errno = 0;
1501 } else if (exp > INT_MAX) {
1502 /* overflow */
1503 r = copysign(Py_HUGE_VAL, x);
1504 errno = ERANGE;
1505 } else if (exp < INT_MIN) {
1506 /* underflow to +-0 */
1507 r = copysign(0., x);
1508 errno = 0;
1509 } else {
1510 errno = 0;
1511 PyFPE_START_PROTECT("in math_ldexp", return 0);
1512 r = ldexp(x, (int)exp);
1513 PyFPE_END_PROTECT(r);
1514 if (Py_IS_INFINITY(r))
1515 errno = ERANGE;
1516 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 if (errno && is_error(r))
1519 return NULL;
1520 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001521}
1522
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001523PyDoc_STRVAR(math_ldexp_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001524"ldexp(x, i)\n\n\
1525Return x * (2**i).");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001526
Barry Warsaw8b43b191996-12-09 22:32:36 +00001527static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001528math_modf(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 double y, x = PyFloat_AsDouble(arg);
1531 if (x == -1.0 && PyErr_Occurred())
1532 return NULL;
1533 /* some platforms don't do the right thing for NaNs and
1534 infinities, so we take care of special cases directly. */
1535 if (!Py_IS_FINITE(x)) {
1536 if (Py_IS_INFINITY(x))
1537 return Py_BuildValue("(dd)", copysign(0., x), x);
1538 else if (Py_IS_NAN(x))
1539 return Py_BuildValue("(dd)", x, x);
1540 }
Christian Heimesa342c012008-04-20 21:01:16 +00001541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 errno = 0;
1543 PyFPE_START_PROTECT("in math_modf", return 0);
1544 x = modf(x, &y);
1545 PyFPE_END_PROTECT(x);
1546 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001547}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001548
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001549PyDoc_STRVAR(math_modf_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001550"modf(x)\n"
1551"\n"
1552"Return the fractional and integer parts of x. Both results carry the sign\n"
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001553"of x and are floats.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001554
Tim Peters78526162001-09-05 00:53:45 +00001555/* A decent logarithm is easy to compute even for huge longs, but libm can't
1556 do that by itself -- loghelper can. func is log or log10, and name is
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00001557 "log" or "log10". Note that overflow of the result isn't possible: a long
1558 can contain no more than INT_MAX * SHIFT bits, so has value certainly less
1559 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 +00001560 small enough to fit in an IEEE single. log and log10 are even smaller.
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00001561 However, intermediate overflow is possible for a long if the number of bits
1562 in that long is larger than PY_SSIZE_T_MAX. */
Tim Peters78526162001-09-05 00:53:45 +00001563
1564static PyObject*
Thomas Wouters89f507f2006-12-13 04:49:30 +00001565loghelper(PyObject* arg, double (*func)(double), char *funcname)
Tim Peters78526162001-09-05 00:53:45 +00001566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 /* If it is long, do it ourselves. */
1568 if (PyLong_Check(arg)) {
1569 double x;
1570 Py_ssize_t e;
1571 x = _PyLong_Frexp((PyLongObject *)arg, &e);
1572 if (x == -1.0 && PyErr_Occurred())
1573 return NULL;
1574 if (x <= 0.0) {
1575 PyErr_SetString(PyExc_ValueError,
1576 "math domain error");
1577 return NULL;
1578 }
1579 /* Special case for log(1), to make sure we get an
1580 exact result there. */
1581 if (e == 1 && x == 0.5)
1582 return PyFloat_FromDouble(0.0);
1583 /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */
1584 x = func(x) + func(2.0) * e;
1585 return PyFloat_FromDouble(x);
1586 }
Tim Peters78526162001-09-05 00:53:45 +00001587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 /* Else let libm handle it by itself. */
1589 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +00001590}
1591
1592static PyObject *
1593math_log(PyObject *self, PyObject *args)
1594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 PyObject *arg;
1596 PyObject *base = NULL;
1597 PyObject *num, *den;
1598 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base))
1601 return NULL;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 num = loghelper(arg, m_log, "log");
1604 if (num == NULL || base == NULL)
1605 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 den = loghelper(base, m_log, "log");
1608 if (den == NULL) {
1609 Py_DECREF(num);
1610 return NULL;
1611 }
Raymond Hettinger866964c2002-12-14 19:51:34 +00001612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 ans = PyNumber_TrueDivide(num, den);
1614 Py_DECREF(num);
1615 Py_DECREF(den);
1616 return ans;
Tim Peters78526162001-09-05 00:53:45 +00001617}
1618
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001619PyDoc_STRVAR(math_log_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001620"log(x[, base])\n\n\
1621Return the logarithm of x to the given base.\n\
Raymond Hettinger866964c2002-12-14 19:51:34 +00001622If the base not specified, returns the natural logarithm (base e) of x.");
Tim Peters78526162001-09-05 00:53:45 +00001623
1624static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001625math_log10(PyObject *self, PyObject *arg)
Tim Peters78526162001-09-05 00:53:45 +00001626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 return loghelper(arg, m_log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +00001628}
1629
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001630PyDoc_STRVAR(math_log10_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001631"log10(x)\n\nReturn the base 10 logarithm of x.");
Tim Peters78526162001-09-05 00:53:45 +00001632
Christian Heimes53876d92008-04-19 00:31:39 +00001633static PyObject *
1634math_fmod(PyObject *self, PyObject *args)
1635{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 PyObject *ox, *oy;
1637 double r, x, y;
1638 if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy))
1639 return NULL;
1640 x = PyFloat_AsDouble(ox);
1641 y = PyFloat_AsDouble(oy);
1642 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1643 return NULL;
1644 /* fmod(x, +/-Inf) returns x for finite x. */
1645 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
1646 return PyFloat_FromDouble(x);
1647 errno = 0;
1648 PyFPE_START_PROTECT("in math_fmod", return 0);
1649 r = fmod(x, y);
1650 PyFPE_END_PROTECT(r);
1651 if (Py_IS_NAN(r)) {
1652 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1653 errno = EDOM;
1654 else
1655 errno = 0;
1656 }
1657 if (errno && is_error(r))
1658 return NULL;
1659 else
1660 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00001661}
1662
1663PyDoc_STRVAR(math_fmod_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001664"fmod(x, y)\n\nReturn fmod(x, y), according to platform C."
Christian Heimes53876d92008-04-19 00:31:39 +00001665" x % y may differ.");
1666
1667static PyObject *
1668math_hypot(PyObject *self, PyObject *args)
1669{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 PyObject *ox, *oy;
1671 double r, x, y;
1672 if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy))
1673 return NULL;
1674 x = PyFloat_AsDouble(ox);
1675 y = PyFloat_AsDouble(oy);
1676 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1677 return NULL;
1678 /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */
1679 if (Py_IS_INFINITY(x))
1680 return PyFloat_FromDouble(fabs(x));
1681 if (Py_IS_INFINITY(y))
1682 return PyFloat_FromDouble(fabs(y));
1683 errno = 0;
1684 PyFPE_START_PROTECT("in math_hypot", return 0);
1685 r = hypot(x, y);
1686 PyFPE_END_PROTECT(r);
1687 if (Py_IS_NAN(r)) {
1688 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1689 errno = EDOM;
1690 else
1691 errno = 0;
1692 }
1693 else if (Py_IS_INFINITY(r)) {
1694 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
1695 errno = ERANGE;
1696 else
1697 errno = 0;
1698 }
1699 if (errno && is_error(r))
1700 return NULL;
1701 else
1702 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00001703}
1704
1705PyDoc_STRVAR(math_hypot_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001706"hypot(x, y)\n\nReturn the Euclidean distance, sqrt(x*x + y*y).");
Christian Heimes53876d92008-04-19 00:31:39 +00001707
1708/* pow can't use math_2, but needs its own wrapper: the problem is
1709 that an infinite result can arise either as a result of overflow
1710 (in which case OverflowError should be raised) or as a result of
1711 e.g. 0.**-5. (for which ValueError needs to be raised.)
1712*/
1713
1714static PyObject *
1715math_pow(PyObject *self, PyObject *args)
1716{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 PyObject *ox, *oy;
1718 double r, x, y;
1719 int odd_y;
Christian Heimes53876d92008-04-19 00:31:39 +00001720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy))
1722 return NULL;
1723 x = PyFloat_AsDouble(ox);
1724 y = PyFloat_AsDouble(oy);
1725 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1726 return NULL;
Christian Heimesa342c012008-04-20 21:01:16 +00001727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 /* deal directly with IEEE specials, to cope with problems on various
1729 platforms whose semantics don't exactly match C99 */
1730 r = 0.; /* silence compiler warning */
1731 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
1732 errno = 0;
1733 if (Py_IS_NAN(x))
1734 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
1735 else if (Py_IS_NAN(y))
1736 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
1737 else if (Py_IS_INFINITY(x)) {
1738 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
1739 if (y > 0.)
1740 r = odd_y ? x : fabs(x);
1741 else if (y == 0.)
1742 r = 1.;
1743 else /* y < 0. */
1744 r = odd_y ? copysign(0., x) : 0.;
1745 }
1746 else if (Py_IS_INFINITY(y)) {
1747 if (fabs(x) == 1.0)
1748 r = 1.;
1749 else if (y > 0. && fabs(x) > 1.0)
1750 r = y;
1751 else if (y < 0. && fabs(x) < 1.0) {
1752 r = -y; /* result is +inf */
1753 if (x == 0.) /* 0**-inf: divide-by-zero */
1754 errno = EDOM;
1755 }
1756 else
1757 r = 0.;
1758 }
1759 }
1760 else {
1761 /* let libm handle finite**finite */
1762 errno = 0;
1763 PyFPE_START_PROTECT("in math_pow", return 0);
1764 r = pow(x, y);
1765 PyFPE_END_PROTECT(r);
1766 /* a NaN result should arise only from (-ve)**(finite
1767 non-integer); in this case we want to raise ValueError. */
1768 if (!Py_IS_FINITE(r)) {
1769 if (Py_IS_NAN(r)) {
1770 errno = EDOM;
1771 }
1772 /*
1773 an infinite result here arises either from:
1774 (A) (+/-0.)**negative (-> divide-by-zero)
1775 (B) overflow of x**y with x and y finite
1776 */
1777 else if (Py_IS_INFINITY(r)) {
1778 if (x == 0.)
1779 errno = EDOM;
1780 else
1781 errno = ERANGE;
1782 }
1783 }
1784 }
Christian Heimes53876d92008-04-19 00:31:39 +00001785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 if (errno && is_error(r))
1787 return NULL;
1788 else
1789 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00001790}
1791
1792PyDoc_STRVAR(math_pow_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001793"pow(x, y)\n\nReturn x**y (x to the power of y).");
Christian Heimes53876d92008-04-19 00:31:39 +00001794
Christian Heimes072c0f12008-01-03 23:01:04 +00001795static const double degToRad = Py_MATH_PI / 180.0;
1796static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001797
1798static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001799math_degrees(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001800{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 double x = PyFloat_AsDouble(arg);
1802 if (x == -1.0 && PyErr_Occurred())
1803 return NULL;
1804 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001805}
1806
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001807PyDoc_STRVAR(math_degrees_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001808"degrees(x)\n\n\
1809Convert angle x from radians to degrees.");
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001810
1811static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001812math_radians(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001813{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 double x = PyFloat_AsDouble(arg);
1815 if (x == -1.0 && PyErr_Occurred())
1816 return NULL;
1817 return PyFloat_FromDouble(x * degToRad);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001818}
1819
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001820PyDoc_STRVAR(math_radians_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001821"radians(x)\n\n\
1822Convert angle x from degrees to radians.");
Tim Peters78526162001-09-05 00:53:45 +00001823
Christian Heimes072c0f12008-01-03 23:01:04 +00001824static PyObject *
1825math_isnan(PyObject *self, PyObject *arg)
1826{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 double x = PyFloat_AsDouble(arg);
1828 if (x == -1.0 && PyErr_Occurred())
1829 return NULL;
1830 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00001831}
1832
1833PyDoc_STRVAR(math_isnan_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001834"isnan(x) -> bool\n\n\
1835Check if float x is not a number (NaN).");
Christian Heimes072c0f12008-01-03 23:01:04 +00001836
1837static PyObject *
1838math_isinf(PyObject *self, PyObject *arg)
1839{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 double x = PyFloat_AsDouble(arg);
1841 if (x == -1.0 && PyErr_Occurred())
1842 return NULL;
1843 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00001844}
1845
1846PyDoc_STRVAR(math_isinf_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001847"isinf(x) -> bool\n\n\
1848Check if float x is infinite (positive or negative).");
Christian Heimes072c0f12008-01-03 23:01:04 +00001849
Barry Warsaw8b43b191996-12-09 22:32:36 +00001850static PyMethodDef math_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 {"acos", math_acos, METH_O, math_acos_doc},
1852 {"acosh", math_acosh, METH_O, math_acosh_doc},
1853 {"asin", math_asin, METH_O, math_asin_doc},
1854 {"asinh", math_asinh, METH_O, math_asinh_doc},
1855 {"atan", math_atan, METH_O, math_atan_doc},
1856 {"atan2", math_atan2, METH_VARARGS, math_atan2_doc},
1857 {"atanh", math_atanh, METH_O, math_atanh_doc},
1858 {"ceil", math_ceil, METH_O, math_ceil_doc},
1859 {"copysign", math_copysign, METH_VARARGS, math_copysign_doc},
1860 {"cos", math_cos, METH_O, math_cos_doc},
1861 {"cosh", math_cosh, METH_O, math_cosh_doc},
1862 {"degrees", math_degrees, METH_O, math_degrees_doc},
1863 {"erf", math_erf, METH_O, math_erf_doc},
1864 {"erfc", math_erfc, METH_O, math_erfc_doc},
1865 {"exp", math_exp, METH_O, math_exp_doc},
1866 {"expm1", math_expm1, METH_O, math_expm1_doc},
1867 {"fabs", math_fabs, METH_O, math_fabs_doc},
1868 {"factorial", math_factorial, METH_O, math_factorial_doc},
1869 {"floor", math_floor, METH_O, math_floor_doc},
1870 {"fmod", math_fmod, METH_VARARGS, math_fmod_doc},
1871 {"frexp", math_frexp, METH_O, math_frexp_doc},
1872 {"fsum", math_fsum, METH_O, math_fsum_doc},
1873 {"gamma", math_gamma, METH_O, math_gamma_doc},
1874 {"hypot", math_hypot, METH_VARARGS, math_hypot_doc},
1875 {"isinf", math_isinf, METH_O, math_isinf_doc},
1876 {"isnan", math_isnan, METH_O, math_isnan_doc},
1877 {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc},
1878 {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
1879 {"log", math_log, METH_VARARGS, math_log_doc},
1880 {"log1p", math_log1p, METH_O, math_log1p_doc},
1881 {"log10", math_log10, METH_O, math_log10_doc},
1882 {"modf", math_modf, METH_O, math_modf_doc},
1883 {"pow", math_pow, METH_VARARGS, math_pow_doc},
1884 {"radians", math_radians, METH_O, math_radians_doc},
1885 {"sin", math_sin, METH_O, math_sin_doc},
1886 {"sinh", math_sinh, METH_O, math_sinh_doc},
1887 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
1888 {"tan", math_tan, METH_O, math_tan_doc},
1889 {"tanh", math_tanh, METH_O, math_tanh_doc},
1890 {"trunc", math_trunc, METH_O, math_trunc_doc},
1891 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001892};
1893
Guido van Rossumc6e22901998-12-04 19:26:43 +00001894
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001895PyDoc_STRVAR(module_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001896"This module is always available. It provides access to the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001897"mathematical functions defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001898
Martin v. Löwis1a214512008-06-11 05:26:20 +00001899
1900static struct PyModuleDef mathmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 PyModuleDef_HEAD_INIT,
1902 "math",
1903 module_doc,
1904 -1,
1905 math_methods,
1906 NULL,
1907 NULL,
1908 NULL,
1909 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001910};
1911
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001912PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001913PyInit_math(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001914{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 PyObject *m;
Tim Petersfe71f812001-08-07 22:10:00 +00001916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001917 m = PyModule_Create(&mathmodule);
1918 if (m == NULL)
1919 goto finally;
Barry Warsawfc93f751996-12-17 00:47:03 +00001920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
1922 PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
Barry Warsawfc93f751996-12-17 00:47:03 +00001923
Christian Heimes53876d92008-04-19 00:31:39 +00001924 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001926}