blob: d173bff5c613cf192e99eb0bee44d85d599ec9b2 [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
580static double
581m_log10(double x)
582{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 if (Py_IS_FINITE(x)) {
584 if (x > 0.0)
585 return log10(x);
586 errno = EDOM;
587 if (x == 0.0)
588 return -Py_HUGE_VAL; /* log10(0) = -inf */
589 else
590 return Py_NAN; /* log10(-ve) = nan */
591 }
592 else if (Py_IS_NAN(x))
593 return x; /* log10(nan) = nan */
594 else if (x > 0.0)
595 return x; /* log10(inf) = inf */
596 else {
597 errno = EDOM;
598 return Py_NAN; /* log10(-inf) = nan */
599 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000600}
601
602
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000603/* Call is_error when errno != 0, and where x is the result libm
604 * returned. is_error will usually set up an exception and return
605 * true (1), but may return false (0) without setting up an exception.
606 */
607static int
608is_error(double x)
609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 int result = 1; /* presumption of guilt */
611 assert(errno); /* non-zero errno is a precondition for calling */
612 if (errno == EDOM)
613 PyErr_SetString(PyExc_ValueError, "math domain error");
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 else if (errno == ERANGE) {
616 /* ANSI C generally requires libm functions to set ERANGE
617 * on overflow, but also generally *allows* them to set
618 * ERANGE on underflow too. There's no consistency about
619 * the latter across platforms.
620 * Alas, C99 never requires that errno be set.
621 * Here we suppress the underflow errors (libm functions
622 * should return a zero on underflow, and +- HUGE_VAL on
623 * overflow, so testing the result for zero suffices to
624 * distinguish the cases).
625 *
626 * On some platforms (Ubuntu/ia64) it seems that errno can be
627 * set to ERANGE for subnormal results that do *not* underflow
628 * to zero. So to be safe, we'll ignore ERANGE whenever the
629 * function result is less than one in absolute value.
630 */
631 if (fabs(x) < 1.0)
632 result = 0;
633 else
634 PyErr_SetString(PyExc_OverflowError,
635 "math range error");
636 }
637 else
638 /* Unexpected math error */
639 PyErr_SetFromErrno(PyExc_ValueError);
640 return result;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000641}
642
Mark Dickinsone675f082008-12-11 21:56:00 +0000643/*
Christian Heimes53876d92008-04-19 00:31:39 +0000644 math_1 is used to wrap a libm function f that takes a double
645 arguments and returns a double.
646
647 The error reporting follows these rules, which are designed to do
648 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
649 platforms.
650
651 - a NaN result from non-NaN inputs causes ValueError to be raised
652 - an infinite result from finite inputs causes OverflowError to be
653 raised if can_overflow is 1, or raises ValueError if can_overflow
654 is 0.
655 - if the result is finite and errno == EDOM then ValueError is
656 raised
657 - if the result is finite and nonzero and errno == ERANGE then
658 OverflowError is raised
659
660 The last rule is used to catch overflow on platforms which follow
661 C89 but for which HUGE_VAL is not an infinity.
662
663 For the majority of one-argument functions these rules are enough
664 to ensure that Python's functions behave as specified in 'Annex F'
665 of the C99 standard, with the 'invalid' and 'divide-by-zero'
666 floating-point exceptions mapping to Python's ValueError and the
667 'overflow' floating-point exception mapping to OverflowError.
668 math_1 only works for functions that don't have singularities *and*
669 the possibility of overflow; fortunately, that covers everything we
670 care about right now.
671*/
672
Barry Warsaw8b43b191996-12-09 22:32:36 +0000673static PyObject *
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000674math_1_to_whatever(PyObject *arg, double (*func) (double),
Christian Heimes53876d92008-04-19 00:31:39 +0000675 PyObject *(*from_double_func) (double),
676 int can_overflow)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000677{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 double x, r;
679 x = PyFloat_AsDouble(arg);
680 if (x == -1.0 && PyErr_Occurred())
681 return NULL;
682 errno = 0;
683 PyFPE_START_PROTECT("in math_1", return 0);
684 r = (*func)(x);
685 PyFPE_END_PROTECT(r);
686 if (Py_IS_NAN(r) && !Py_IS_NAN(x)) {
687 PyErr_SetString(PyExc_ValueError,
688 "math domain error"); /* invalid arg */
689 return NULL;
690 }
691 if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) {
692 if (can_overflow)
693 PyErr_SetString(PyExc_OverflowError,
694 "math range error"); /* overflow */
695 else
696 PyErr_SetString(PyExc_ValueError,
697 "math domain error"); /* singularity */
698 return NULL;
699 }
700 if (Py_IS_FINITE(r) && errno && is_error(r))
701 /* this branch unnecessary on most platforms */
702 return NULL;
Mark Dickinsonde429622008-05-01 00:19:23 +0000703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 return (*from_double_func)(r);
Christian Heimes53876d92008-04-19 00:31:39 +0000705}
706
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000707/* variant of math_1, to be used when the function being wrapped is known to
708 set errno properly (that is, errno = EDOM for invalid or divide-by-zero,
709 errno = ERANGE for overflow). */
710
711static PyObject *
712math_1a(PyObject *arg, double (*func) (double))
713{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 double x, r;
715 x = PyFloat_AsDouble(arg);
716 if (x == -1.0 && PyErr_Occurred())
717 return NULL;
718 errno = 0;
719 PyFPE_START_PROTECT("in math_1a", return 0);
720 r = (*func)(x);
721 PyFPE_END_PROTECT(r);
722 if (errno && is_error(r))
723 return NULL;
724 return PyFloat_FromDouble(r);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000725}
726
Christian Heimes53876d92008-04-19 00:31:39 +0000727/*
728 math_2 is used to wrap a libm function f that takes two double
729 arguments and returns a double.
730
731 The error reporting follows these rules, which are designed to do
732 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
733 platforms.
734
735 - a NaN result from non-NaN inputs causes ValueError to be raised
736 - an infinite result from finite inputs causes OverflowError to be
737 raised.
738 - if the result is finite and errno == EDOM then ValueError is
739 raised
740 - if the result is finite and nonzero and errno == ERANGE then
741 OverflowError is raised
742
743 The last rule is used to catch overflow on platforms which follow
744 C89 but for which HUGE_VAL is not an infinity.
745
746 For most two-argument functions (copysign, fmod, hypot, atan2)
747 these rules are enough to ensure that Python's functions behave as
748 specified in 'Annex F' of the C99 standard, with the 'invalid' and
749 'divide-by-zero' floating-point exceptions mapping to Python's
750 ValueError and the 'overflow' floating-point exception mapping to
751 OverflowError.
752*/
753
754static PyObject *
755math_1(PyObject *arg, double (*func) (double), int can_overflow)
756{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow);
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000758}
759
760static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000761math_1_to_int(PyObject *arg, double (*func) (double), int can_overflow)
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 return math_1_to_whatever(arg, func, PyLong_FromDouble, can_overflow);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000764}
765
Barry Warsaw8b43b191996-12-09 22:32:36 +0000766static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +0000767math_2(PyObject *args, double (*func) (double, double), char *funcname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000768{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 PyObject *ox, *oy;
770 double x, y, r;
771 if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy))
772 return NULL;
773 x = PyFloat_AsDouble(ox);
774 y = PyFloat_AsDouble(oy);
775 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
776 return NULL;
777 errno = 0;
778 PyFPE_START_PROTECT("in math_2", return 0);
779 r = (*func)(x, y);
780 PyFPE_END_PROTECT(r);
781 if (Py_IS_NAN(r)) {
782 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
783 errno = EDOM;
784 else
785 errno = 0;
786 }
787 else if (Py_IS_INFINITY(r)) {
788 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
789 errno = ERANGE;
790 else
791 errno = 0;
792 }
793 if (errno && is_error(r))
794 return NULL;
795 else
796 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000797}
798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799#define FUNC1(funcname, func, can_overflow, docstring) \
800 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
801 return math_1(args, func, can_overflow); \
802 }\
803 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805#define FUNC1A(funcname, func, docstring) \
806 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
807 return math_1a(args, func); \
808 }\
809 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000810
Fred Drake40c48682000-07-03 18:11:56 +0000811#define FUNC2(funcname, func, docstring) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
813 return math_2(args, func, #funcname); \
814 }\
815 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000816
Christian Heimes53876d92008-04-19 00:31:39 +0000817FUNC1(acos, acos, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000818 "acos(x)\n\nReturn the arc cosine (measured in radians) of x.")
Mark Dickinsonf3718592009-12-21 15:27:41 +0000819FUNC1(acosh, m_acosh, 0,
Christian Heimes53876d92008-04-19 00:31:39 +0000820 "acosh(x)\n\nReturn the hyperbolic arc cosine (measured in radians) of x.")
821FUNC1(asin, asin, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000822 "asin(x)\n\nReturn the arc sine (measured in radians) of x.")
Mark Dickinsonf3718592009-12-21 15:27:41 +0000823FUNC1(asinh, m_asinh, 0,
Christian Heimes53876d92008-04-19 00:31:39 +0000824 "asinh(x)\n\nReturn the hyperbolic arc sine (measured in radians) of x.")
825FUNC1(atan, atan, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000826 "atan(x)\n\nReturn the arc tangent (measured in radians) of x.")
Christian Heimese57950f2008-04-21 13:08:03 +0000827FUNC2(atan2, m_atan2,
Tim Petersfe71f812001-08-07 22:10:00 +0000828 "atan2(y, x)\n\nReturn the arc tangent (measured in radians) of y/x.\n"
829 "Unlike atan(y/x), the signs of both x and y are considered.")
Mark Dickinsonf3718592009-12-21 15:27:41 +0000830FUNC1(atanh, m_atanh, 0,
Christian Heimes53876d92008-04-19 00:31:39 +0000831 "atanh(x)\n\nReturn the hyperbolic arc tangent (measured in radians) of x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +0000832
833static PyObject * math_ceil(PyObject *self, PyObject *number) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 static PyObject *ceil_str = NULL;
Mark Dickinson6d02d9c2010-07-02 16:05:15 +0000835 PyObject *method, *result;
Guido van Rossum13e05de2007-08-23 22:56:55 +0000836
Benjamin Petersonf751bc92010-07-02 13:46:42 +0000837 method = _PyObject_LookupSpecial(number, "__ceil__", &ceil_str);
838 if (method == NULL) {
839 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 return math_1_to_int(number, ceil, 0);
Benjamin Petersonf751bc92010-07-02 13:46:42 +0000842 }
Mark Dickinson6d02d9c2010-07-02 16:05:15 +0000843 result = PyObject_CallFunctionObjArgs(method, NULL);
844 Py_DECREF(method);
845 return result;
Guido van Rossum13e05de2007-08-23 22:56:55 +0000846}
847
848PyDoc_STRVAR(math_ceil_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 "ceil(x)\n\nReturn the ceiling of x as an int.\n"
850 "This is the smallest integral value >= x.");
Guido van Rossum13e05de2007-08-23 22:56:55 +0000851
Christian Heimes072c0f12008-01-03 23:01:04 +0000852FUNC2(copysign, copysign,
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000853 "copysign(x, y)\n\nReturn x with the sign of y.")
Christian Heimes53876d92008-04-19 00:31:39 +0000854FUNC1(cos, cos, 0,
855 "cos(x)\n\nReturn the cosine of x (measured in radians).")
856FUNC1(cosh, cosh, 1,
857 "cosh(x)\n\nReturn the hyperbolic cosine of x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +0000858FUNC1A(erf, m_erf,
859 "erf(x)\n\nError function at x.")
860FUNC1A(erfc, m_erfc,
861 "erfc(x)\n\nComplementary error function at x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000862FUNC1(exp, exp, 1,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000863 "exp(x)\n\nReturn e raised to the power of x.")
Mark Dickinson664b5112009-12-16 20:23:42 +0000864FUNC1(expm1, m_expm1, 1,
865 "expm1(x)\n\nReturn exp(x)-1.\n"
866 "This function avoids the loss of precision involved in the direct "
867 "evaluation of exp(x)-1 for small x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000868FUNC1(fabs, fabs, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000869 "fabs(x)\n\nReturn the absolute value of the float x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +0000870
871static PyObject * math_floor(PyObject *self, PyObject *number) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 static PyObject *floor_str = NULL;
Benjamin Petersonb0125892010-07-02 13:35:17 +0000873 PyObject *method, *result;
Guido van Rossum13e05de2007-08-23 22:56:55 +0000874
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +0000875 method = _PyObject_LookupSpecial(number, "__floor__", &floor_str);
876 if (method == NULL) {
877 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 return math_1_to_int(number, floor, 0);
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +0000880 }
Benjamin Petersonb0125892010-07-02 13:35:17 +0000881 result = PyObject_CallFunctionObjArgs(method, NULL);
882 Py_DECREF(method);
883 return result;
Guido van Rossum13e05de2007-08-23 22:56:55 +0000884}
885
886PyDoc_STRVAR(math_floor_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 "floor(x)\n\nReturn the floor of x as an int.\n"
888 "This is the largest integral value <= x.");
Guido van Rossum13e05de2007-08-23 22:56:55 +0000889
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000890FUNC1A(gamma, m_tgamma,
891 "gamma(x)\n\nGamma function at x.")
Mark Dickinson05d2e082009-12-11 20:17:17 +0000892FUNC1A(lgamma, m_lgamma,
893 "lgamma(x)\n\nNatural logarithm of absolute value of Gamma function at x.")
Mark Dickinsonbe64d952010-07-07 16:21:29 +0000894FUNC1(log1p, m_log1p, 0,
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000895 "log1p(x)\n\nReturn the natural logarithm of 1+x (base e).\n"
896 "The result is computed in a way which is accurate for x near zero.")
Christian Heimes53876d92008-04-19 00:31:39 +0000897FUNC1(sin, sin, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000898 "sin(x)\n\nReturn the sine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +0000899FUNC1(sinh, sinh, 1,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000900 "sinh(x)\n\nReturn the hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000901FUNC1(sqrt, sqrt, 0,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000902 "sqrt(x)\n\nReturn the square root of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000903FUNC1(tan, tan, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000904 "tan(x)\n\nReturn the tangent of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +0000905FUNC1(tanh, tanh, 0,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000906 "tanh(x)\n\nReturn the hyperbolic tangent of x.")
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000907
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000908/* Precision summation function as msum() by Raymond Hettinger in
909 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
910 enhanced with the exact partials sum and roundoff from Mark
911 Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
912 See those links for more details, proofs and other references.
913
914 Note 1: IEEE 754R floating point semantics are assumed,
915 but the current implementation does not re-establish special
916 value semantics across iterations (i.e. handling -Inf + Inf).
917
918 Note 2: No provision is made for intermediate overflow handling;
Georg Brandlf78e02b2008-06-10 17:40:04 +0000919 therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000920 sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
921 overflow of the first partial sum.
922
Benjamin Petersonfea6a942008-07-02 16:11:42 +0000923 Note 3: The intermediate values lo, yr, and hi are declared volatile so
924 aggressive compilers won't algebraically reduce lo to always be exactly 0.0.
Georg Brandlf78e02b2008-06-10 17:40:04 +0000925 Also, the volatile declaration forces the values to be stored in memory as
926 regular doubles instead of extended long precision (80-bit) values. This
Benjamin Petersonfea6a942008-07-02 16:11:42 +0000927 prevents double rounding because any addition or subtraction of two doubles
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 can be resolved exactly into double-sized hi and lo values. As long as the
Georg Brandlf78e02b2008-06-10 17:40:04 +0000929 hi value gets forced into a double before yr and lo are computed, the extra
930 bits in downstream extended precision operations (x87 for example) will be
931 exactly zero and therefore can be losslessly stored back into a double,
932 thereby preventing double rounding.
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000933
934 Note 4: A similar implementation is in Modules/cmathmodule.c.
935 Be sure to update both when making changes.
936
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000937 Note 5: The signature of math.fsum() differs from __builtin__.sum()
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000938 because the start argument doesn't make sense in the context of
939 accurate summation. Since the partials table is collapsed before
940 returning a result, sum(seq2, start=sum(seq1)) may not equal the
941 accurate result returned by sum(itertools.chain(seq1, seq2)).
942*/
943
944#define NUM_PARTIALS 32 /* initial partials array size, on stack */
945
946/* Extend the partials array p[] by doubling its size. */
947static int /* non-zero on error */
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000948_fsum_realloc(double **p_ptr, Py_ssize_t n,
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000949 double *ps, Py_ssize_t *m_ptr)
950{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 void *v = NULL;
952 Py_ssize_t m = *m_ptr;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 m += m; /* double */
955 if (n < m && m < (PY_SSIZE_T_MAX / sizeof(double))) {
956 double *p = *p_ptr;
957 if (p == ps) {
958 v = PyMem_Malloc(sizeof(double) * m);
959 if (v != NULL)
960 memcpy(v, ps, sizeof(double) * n);
961 }
962 else
963 v = PyMem_Realloc(p, sizeof(double) * m);
964 }
965 if (v == NULL) { /* size overflow or no memory */
966 PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
967 return 1;
968 }
969 *p_ptr = (double*) v;
970 *m_ptr = m;
971 return 0;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000972}
973
974/* Full precision summation of a sequence of floats.
975
976 def msum(iterable):
977 partials = [] # sorted, non-overlapping partial sums
978 for x in iterable:
Mark Dickinsonfdb0acc2010-06-25 20:22:24 +0000979 i = 0
980 for y in partials:
981 if abs(x) < abs(y):
982 x, y = y, x
983 hi = x + y
984 lo = y - (hi - x)
985 if lo:
986 partials[i] = lo
987 i += 1
988 x = hi
989 partials[i:] = [x]
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000990 return sum_exact(partials)
991
992 Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
993 are exactly equal to x+y. The inner loop applies hi/lo summation to each
994 partial so that the list of partial sums remains exact.
995
996 Sum_exact() adds the partial sums exactly and correctly rounds the final
997 result (using the round-half-to-even rule). The items in partials remain
998 non-zero, non-special, non-overlapping and strictly increasing in
999 magnitude, but possibly not all having the same sign.
1000
1001 Depends on IEEE 754 arithmetic guarantees and half-even rounding.
1002*/
1003
1004static PyObject*
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001005math_fsum(PyObject *self, PyObject *seq)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001006{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 PyObject *item, *iter, *sum = NULL;
1008 Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
1009 double x, y, t, ps[NUM_PARTIALS], *p = ps;
1010 double xsave, special_sum = 0.0, inf_sum = 0.0;
1011 volatile double hi, yr, lo;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 iter = PyObject_GetIter(seq);
1014 if (iter == NULL)
1015 return NULL;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 for(;;) { /* for x in iterable */
1020 assert(0 <= n && n <= m);
1021 assert((m == NUM_PARTIALS && p == ps) ||
1022 (m > NUM_PARTIALS && p != NULL));
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 item = PyIter_Next(iter);
1025 if (item == NULL) {
1026 if (PyErr_Occurred())
1027 goto _fsum_error;
1028 break;
1029 }
1030 x = PyFloat_AsDouble(item);
1031 Py_DECREF(item);
1032 if (PyErr_Occurred())
1033 goto _fsum_error;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 xsave = x;
1036 for (i = j = 0; j < n; j++) { /* for y in partials */
1037 y = p[j];
1038 if (fabs(x) < fabs(y)) {
1039 t = x; x = y; y = t;
1040 }
1041 hi = x + y;
1042 yr = hi - x;
1043 lo = y - yr;
1044 if (lo != 0.0)
1045 p[i++] = lo;
1046 x = hi;
1047 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 n = i; /* ps[i:] = [x] */
1050 if (x != 0.0) {
1051 if (! Py_IS_FINITE(x)) {
1052 /* a nonfinite x could arise either as
1053 a result of intermediate overflow, or
1054 as a result of a nan or inf in the
1055 summands */
1056 if (Py_IS_FINITE(xsave)) {
1057 PyErr_SetString(PyExc_OverflowError,
1058 "intermediate overflow in fsum");
1059 goto _fsum_error;
1060 }
1061 if (Py_IS_INFINITY(xsave))
1062 inf_sum += xsave;
1063 special_sum += xsave;
1064 /* reset partials */
1065 n = 0;
1066 }
1067 else if (n >= m && _fsum_realloc(&p, n, ps, &m))
1068 goto _fsum_error;
1069 else
1070 p[n++] = x;
1071 }
1072 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 if (special_sum != 0.0) {
1075 if (Py_IS_NAN(inf_sum))
1076 PyErr_SetString(PyExc_ValueError,
1077 "-inf + inf in fsum");
1078 else
1079 sum = PyFloat_FromDouble(special_sum);
1080 goto _fsum_error;
1081 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 hi = 0.0;
1084 if (n > 0) {
1085 hi = p[--n];
1086 /* sum_exact(ps, hi) from the top, stop when the sum becomes
1087 inexact. */
1088 while (n > 0) {
1089 x = hi;
1090 y = p[--n];
1091 assert(fabs(y) < fabs(x));
1092 hi = x + y;
1093 yr = hi - x;
1094 lo = y - yr;
1095 if (lo != 0.0)
1096 break;
1097 }
1098 /* Make half-even rounding work across multiple partials.
1099 Needed so that sum([1e-16, 1, 1e16]) will round-up the last
1100 digit to two instead of down to zero (the 1e-16 makes the 1
1101 slightly closer to two). With a potential 1 ULP rounding
1102 error fixed-up, math.fsum() can guarantee commutativity. */
1103 if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
1104 (lo > 0.0 && p[n-1] > 0.0))) {
1105 y = lo * 2.0;
1106 x = hi + y;
1107 yr = x - hi;
1108 if (y == yr)
1109 hi = x;
1110 }
1111 }
1112 sum = PyFloat_FromDouble(hi);
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001113
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001114_fsum_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 PyFPE_END_PROTECT(hi)
1116 Py_DECREF(iter);
1117 if (p != ps)
1118 PyMem_Free(p);
1119 return sum;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001120}
1121
1122#undef NUM_PARTIALS
1123
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001124PyDoc_STRVAR(math_fsum_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001125"fsum(iterable)\n\n\
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001126Return an accurate floating point sum of values in the iterable.\n\
1127Assumes IEEE-754 floating point arithmetic.");
1128
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001129/* Return the smallest integer k such that n < 2**k, or 0 if n == 0.
1130 * Equivalent to floor(lg(x))+1. Also equivalent to: bitwidth_of_type -
1131 * count_leading_zero_bits(x)
1132 */
1133
1134/* XXX: This routine does more or less the same thing as
1135 * bits_in_digit() in Objects/longobject.c. Someday it would be nice to
1136 * consolidate them. On BSD, there's a library function called fls()
1137 * that we could use, and GCC provides __builtin_clz().
1138 */
1139
1140static unsigned long
1141bit_length(unsigned long n)
1142{
1143 unsigned long len = 0;
1144 while (n != 0) {
1145 ++len;
1146 n >>= 1;
1147 }
1148 return len;
1149}
1150
1151static unsigned long
1152count_set_bits(unsigned long n)
1153{
1154 unsigned long count = 0;
1155 while (n != 0) {
1156 ++count;
1157 n &= n - 1; /* clear least significant bit */
1158 }
1159 return count;
1160}
1161
1162/* Divide-and-conquer factorial algorithm
1163 *
1164 * Based on the formula and psuedo-code provided at:
1165 * http://www.luschny.de/math/factorial/binarysplitfact.html
1166 *
1167 * Faster algorithms exist, but they're more complicated and depend on
Ezio Melotti9527afd2010-07-08 15:03:02 +00001168 * a fast prime factorization algorithm.
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001169 *
1170 * Notes on the algorithm
1171 * ----------------------
1172 *
1173 * factorial(n) is written in the form 2**k * m, with m odd. k and m are
1174 * computed separately, and then combined using a left shift.
1175 *
1176 * The function factorial_odd_part computes the odd part m (i.e., the greatest
1177 * odd divisor) of factorial(n), using the formula:
1178 *
1179 * factorial_odd_part(n) =
1180 *
1181 * product_{i >= 0} product_{0 < j <= n / 2**i, j odd} j
1182 *
1183 * Example: factorial_odd_part(20) =
1184 *
1185 * (1) *
1186 * (1) *
1187 * (1 * 3 * 5) *
1188 * (1 * 3 * 5 * 7 * 9)
1189 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1190 *
1191 * Here i goes from large to small: the first term corresponds to i=4 (any
1192 * larger i gives an empty product), and the last term corresponds to i=0.
1193 * Each term can be computed from the last by multiplying by the extra odd
1194 * numbers required: e.g., to get from the penultimate term to the last one,
1195 * we multiply by (11 * 13 * 15 * 17 * 19).
1196 *
1197 * To see a hint of why this formula works, here are the same numbers as above
1198 * but with the even parts (i.e., the appropriate powers of 2) included. For
1199 * each subterm in the product for i, we multiply that subterm by 2**i:
1200 *
1201 * factorial(20) =
1202 *
1203 * (16) *
1204 * (8) *
1205 * (4 * 12 * 20) *
1206 * (2 * 6 * 10 * 14 * 18) *
1207 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1208 *
1209 * The factorial_partial_product function computes the product of all odd j in
1210 * range(start, stop) for given start and stop. It's used to compute the
1211 * partial products like (11 * 13 * 15 * 17 * 19) in the example above. It
1212 * operates recursively, repeatedly splitting the range into two roughly equal
1213 * pieces until the subranges are small enough to be computed using only C
1214 * integer arithmetic.
1215 *
1216 * The two-valuation k (i.e., the exponent of the largest power of 2 dividing
1217 * the factorial) is computed independently in the main math_factorial
1218 * function. By standard results, its value is:
1219 *
1220 * two_valuation = n//2 + n//4 + n//8 + ....
1221 *
1222 * It can be shown (e.g., by complete induction on n) that two_valuation is
1223 * equal to n - count_set_bits(n), where count_set_bits(n) gives the number of
1224 * '1'-bits in the binary expansion of n.
1225 */
1226
1227/* factorial_partial_product: Compute product(range(start, stop, 2)) using
1228 * divide and conquer. Assumes start and stop are odd and stop > start.
1229 * max_bits must be >= bit_length(stop - 2). */
1230
1231static PyObject *
1232factorial_partial_product(unsigned long start, unsigned long stop,
1233 unsigned long max_bits)
1234{
1235 unsigned long midpoint, num_operands;
1236 PyObject *left = NULL, *right = NULL, *result = NULL;
1237
1238 /* If the return value will fit an unsigned long, then we can
1239 * multiply in a tight, fast loop where each multiply is O(1).
1240 * Compute an upper bound on the number of bits required to store
1241 * the answer.
1242 *
1243 * Storing some integer z requires floor(lg(z))+1 bits, which is
1244 * conveniently the value returned by bit_length(z). The
1245 * product x*y will require at most
1246 * bit_length(x) + bit_length(y) bits to store, based
1247 * on the idea that lg product = lg x + lg y.
1248 *
1249 * We know that stop - 2 is the largest number to be multiplied. From
1250 * there, we have: bit_length(answer) <= num_operands *
1251 * bit_length(stop - 2)
1252 */
1253
1254 num_operands = (stop - start) / 2;
1255 /* The "num_operands <= 8 * SIZEOF_LONG" check guards against the
1256 * unlikely case of an overflow in num_operands * max_bits. */
1257 if (num_operands <= 8 * SIZEOF_LONG &&
1258 num_operands * max_bits <= 8 * SIZEOF_LONG) {
1259 unsigned long j, total;
1260 for (total = start, j = start + 2; j < stop; j += 2)
1261 total *= j;
1262 return PyLong_FromUnsignedLong(total);
1263 }
1264
1265 /* find midpoint of range(start, stop), rounded up to next odd number. */
1266 midpoint = (start + num_operands) | 1;
1267 left = factorial_partial_product(start, midpoint,
1268 bit_length(midpoint - 2));
1269 if (left == NULL)
1270 goto error;
1271 right = factorial_partial_product(midpoint, stop, max_bits);
1272 if (right == NULL)
1273 goto error;
1274 result = PyNumber_Multiply(left, right);
1275
1276 error:
1277 Py_XDECREF(left);
1278 Py_XDECREF(right);
1279 return result;
1280}
1281
1282/* factorial_odd_part: compute the odd part of factorial(n). */
1283
1284static PyObject *
1285factorial_odd_part(unsigned long n)
1286{
1287 long i;
1288 unsigned long v, lower, upper;
1289 PyObject *partial, *tmp, *inner, *outer;
1290
1291 inner = PyLong_FromLong(1);
1292 if (inner == NULL)
1293 return NULL;
1294 outer = inner;
1295 Py_INCREF(outer);
1296
1297 upper = 3;
1298 for (i = bit_length(n) - 2; i >= 0; i--) {
1299 v = n >> i;
1300 if (v <= 2)
1301 continue;
1302 lower = upper;
1303 /* (v + 1) | 1 = least odd integer strictly larger than n / 2**i */
1304 upper = (v + 1) | 1;
1305 /* Here inner is the product of all odd integers j in the range (0,
1306 n/2**(i+1)]. The factorial_partial_product call below gives the
1307 product of all odd integers j in the range (n/2**(i+1), n/2**i]. */
1308 partial = factorial_partial_product(lower, upper, bit_length(upper-2));
1309 /* inner *= partial */
1310 if (partial == NULL)
1311 goto error;
1312 tmp = PyNumber_Multiply(inner, partial);
1313 Py_DECREF(partial);
1314 if (tmp == NULL)
1315 goto error;
1316 Py_DECREF(inner);
1317 inner = tmp;
1318 /* Now inner is the product of all odd integers j in the range (0,
1319 n/2**i], giving the inner product in the formula above. */
1320
1321 /* outer *= inner; */
1322 tmp = PyNumber_Multiply(outer, inner);
1323 if (tmp == NULL)
1324 goto error;
1325 Py_DECREF(outer);
1326 outer = tmp;
1327 }
1328
1329 goto done;
1330
1331 error:
1332 Py_DECREF(outer);
1333 done:
1334 Py_DECREF(inner);
1335 return outer;
1336}
1337
1338/* Lookup table for small factorial values */
1339
1340static const unsigned long SmallFactorials[] = {
1341 1, 1, 2, 6, 24, 120, 720, 5040, 40320,
1342 362880, 3628800, 39916800, 479001600,
1343#if SIZEOF_LONG >= 8
1344 6227020800, 87178291200, 1307674368000,
1345 20922789888000, 355687428096000, 6402373705728000,
1346 121645100408832000, 2432902008176640000
1347#endif
1348};
1349
Barry Warsaw8b43b191996-12-09 22:32:36 +00001350static PyObject *
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001351math_factorial(PyObject *self, PyObject *arg)
1352{
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001353 long x;
1354 PyObject *result, *odd_part, *two_valuation;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 if (PyFloat_Check(arg)) {
1357 PyObject *lx;
1358 double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
1359 if (!(Py_IS_FINITE(dx) && dx == floor(dx))) {
1360 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001361 "factorial() only accepts integral values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 return NULL;
1363 }
1364 lx = PyLong_FromDouble(dx);
1365 if (lx == NULL)
1366 return NULL;
1367 x = PyLong_AsLong(lx);
1368 Py_DECREF(lx);
1369 }
1370 else
1371 x = PyLong_AsLong(arg);
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 if (x == -1 && PyErr_Occurred())
1374 return NULL;
1375 if (x < 0) {
1376 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001377 "factorial() not defined for negative values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 return NULL;
1379 }
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001380
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001381 /* use lookup table if x is small */
1382 if (x < (long)(sizeof(SmallFactorials)/sizeof(SmallFactorials[0])))
1383 return PyLong_FromUnsignedLong(SmallFactorials[x]);
1384
1385 /* else express in the form odd_part * 2**two_valuation, and compute as
1386 odd_part << two_valuation. */
1387 odd_part = factorial_odd_part(x);
1388 if (odd_part == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 return NULL;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001390 two_valuation = PyLong_FromLong(x - count_set_bits(x));
1391 if (two_valuation == NULL) {
1392 Py_DECREF(odd_part);
1393 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 }
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001395 result = PyNumber_Lshift(odd_part, two_valuation);
1396 Py_DECREF(two_valuation);
1397 Py_DECREF(odd_part);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 return result;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001399}
1400
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001401PyDoc_STRVAR(math_factorial_doc,
1402"factorial(x) -> Integral\n"
1403"\n"
1404"Find x!. Raise a ValueError if x is negative or non-integral.");
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001405
1406static PyObject *
Christian Heimes400adb02008-02-01 08:12:03 +00001407math_trunc(PyObject *self, PyObject *number)
1408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 static PyObject *trunc_str = NULL;
Benjamin Petersonb0125892010-07-02 13:35:17 +00001410 PyObject *trunc, *result;
Christian Heimes400adb02008-02-01 08:12:03 +00001411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 if (Py_TYPE(number)->tp_dict == NULL) {
1413 if (PyType_Ready(Py_TYPE(number)) < 0)
1414 return NULL;
1415 }
Christian Heimes400adb02008-02-01 08:12:03 +00001416
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001417 trunc = _PyObject_LookupSpecial(number, "__trunc__", &trunc_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 if (trunc == NULL) {
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001419 if (!PyErr_Occurred())
1420 PyErr_Format(PyExc_TypeError,
1421 "type %.100s doesn't define __trunc__ method",
1422 Py_TYPE(number)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 return NULL;
1424 }
Benjamin Petersonb0125892010-07-02 13:35:17 +00001425 result = PyObject_CallFunctionObjArgs(trunc, NULL);
1426 Py_DECREF(trunc);
1427 return result;
Christian Heimes400adb02008-02-01 08:12:03 +00001428}
1429
1430PyDoc_STRVAR(math_trunc_doc,
1431"trunc(x:Real) -> Integral\n"
1432"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001433"Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.");
Christian Heimes400adb02008-02-01 08:12:03 +00001434
1435static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001436math_frexp(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 int i;
1439 double x = PyFloat_AsDouble(arg);
1440 if (x == -1.0 && PyErr_Occurred())
1441 return NULL;
1442 /* deal with special cases directly, to sidestep platform
1443 differences */
1444 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
1445 i = 0;
1446 }
1447 else {
1448 PyFPE_START_PROTECT("in math_frexp", return 0);
1449 x = frexp(x, &i);
1450 PyFPE_END_PROTECT(x);
1451 }
1452 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001453}
1454
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001455PyDoc_STRVAR(math_frexp_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001456"frexp(x)\n"
1457"\n"
1458"Return the mantissa and exponent of x, as pair (m, e).\n"
1459"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 +00001460"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 +00001461
Barry Warsaw8b43b191996-12-09 22:32:36 +00001462static PyObject *
Fred Drake40c48682000-07-03 18:11:56 +00001463math_ldexp(PyObject *self, PyObject *args)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 double x, r;
1466 PyObject *oexp;
1467 long exp;
1468 int overflow;
1469 if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp))
1470 return NULL;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 if (PyLong_Check(oexp)) {
1473 /* on overflow, replace exponent with either LONG_MAX
1474 or LONG_MIN, depending on the sign. */
1475 exp = PyLong_AsLongAndOverflow(oexp, &overflow);
1476 if (exp == -1 && PyErr_Occurred())
1477 return NULL;
1478 if (overflow)
1479 exp = overflow < 0 ? LONG_MIN : LONG_MAX;
1480 }
1481 else {
1482 PyErr_SetString(PyExc_TypeError,
1483 "Expected an int or long as second argument "
1484 "to ldexp.");
1485 return NULL;
1486 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 if (x == 0. || !Py_IS_FINITE(x)) {
1489 /* NaNs, zeros and infinities are returned unchanged */
1490 r = x;
1491 errno = 0;
1492 } else if (exp > INT_MAX) {
1493 /* overflow */
1494 r = copysign(Py_HUGE_VAL, x);
1495 errno = ERANGE;
1496 } else if (exp < INT_MIN) {
1497 /* underflow to +-0 */
1498 r = copysign(0., x);
1499 errno = 0;
1500 } else {
1501 errno = 0;
1502 PyFPE_START_PROTECT("in math_ldexp", return 0);
1503 r = ldexp(x, (int)exp);
1504 PyFPE_END_PROTECT(r);
1505 if (Py_IS_INFINITY(r))
1506 errno = ERANGE;
1507 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 if (errno && is_error(r))
1510 return NULL;
1511 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001512}
1513
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001514PyDoc_STRVAR(math_ldexp_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001515"ldexp(x, i)\n\n\
1516Return x * (2**i).");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001517
Barry Warsaw8b43b191996-12-09 22:32:36 +00001518static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001519math_modf(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001520{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 double y, x = PyFloat_AsDouble(arg);
1522 if (x == -1.0 && PyErr_Occurred())
1523 return NULL;
1524 /* some platforms don't do the right thing for NaNs and
1525 infinities, so we take care of special cases directly. */
1526 if (!Py_IS_FINITE(x)) {
1527 if (Py_IS_INFINITY(x))
1528 return Py_BuildValue("(dd)", copysign(0., x), x);
1529 else if (Py_IS_NAN(x))
1530 return Py_BuildValue("(dd)", x, x);
1531 }
Christian Heimesa342c012008-04-20 21:01:16 +00001532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 errno = 0;
1534 PyFPE_START_PROTECT("in math_modf", return 0);
1535 x = modf(x, &y);
1536 PyFPE_END_PROTECT(x);
1537 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001538}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001539
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001540PyDoc_STRVAR(math_modf_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001541"modf(x)\n"
1542"\n"
1543"Return the fractional and integer parts of x. Both results carry the sign\n"
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001544"of x and are floats.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001545
Tim Peters78526162001-09-05 00:53:45 +00001546/* A decent logarithm is easy to compute even for huge longs, but libm can't
1547 do that by itself -- loghelper can. func is log or log10, and name is
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00001548 "log" or "log10". Note that overflow of the result isn't possible: a long
1549 can contain no more than INT_MAX * SHIFT bits, so has value certainly less
1550 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 +00001551 small enough to fit in an IEEE single. log and log10 are even smaller.
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00001552 However, intermediate overflow is possible for a long if the number of bits
1553 in that long is larger than PY_SSIZE_T_MAX. */
Tim Peters78526162001-09-05 00:53:45 +00001554
1555static PyObject*
Thomas Wouters89f507f2006-12-13 04:49:30 +00001556loghelper(PyObject* arg, double (*func)(double), char *funcname)
Tim Peters78526162001-09-05 00:53:45 +00001557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 /* If it is long, do it ourselves. */
1559 if (PyLong_Check(arg)) {
Mark Dickinsonc6037172010-09-29 19:06:36 +00001560 double x, result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 Py_ssize_t e;
Mark Dickinsonc6037172010-09-29 19:06:36 +00001562
1563 /* Negative or zero inputs give a ValueError. */
1564 if (Py_SIZE(arg) <= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 PyErr_SetString(PyExc_ValueError,
1566 "math domain error");
1567 return NULL;
1568 }
Mark Dickinsonfa41e602010-09-28 07:22:27 +00001569
Mark Dickinsonc6037172010-09-29 19:06:36 +00001570 x = PyLong_AsDouble(arg);
1571 if (x == -1.0 && PyErr_Occurred()) {
1572 if (!PyErr_ExceptionMatches(PyExc_OverflowError))
1573 return NULL;
1574 /* Here the conversion to double overflowed, but it's possible
1575 to compute the log anyway. Clear the exception and continue. */
1576 PyErr_Clear();
1577 x = _PyLong_Frexp((PyLongObject *)arg, &e);
1578 if (x == -1.0 && PyErr_Occurred())
1579 return NULL;
1580 /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */
1581 result = func(x) + func(2.0) * e;
1582 }
1583 else
1584 /* Successfully converted x to a double. */
1585 result = func(x);
1586 return PyFloat_FromDouble(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 }
Tim Peters78526162001-09-05 00:53:45 +00001588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 /* Else let libm handle it by itself. */
1590 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +00001591}
1592
1593static PyObject *
1594math_log(PyObject *self, PyObject *args)
1595{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 PyObject *arg;
1597 PyObject *base = NULL;
1598 PyObject *num, *den;
1599 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base))
1602 return NULL;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 num = loghelper(arg, m_log, "log");
1605 if (num == NULL || base == NULL)
1606 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 den = loghelper(base, m_log, "log");
1609 if (den == NULL) {
1610 Py_DECREF(num);
1611 return NULL;
1612 }
Raymond Hettinger866964c2002-12-14 19:51:34 +00001613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 ans = PyNumber_TrueDivide(num, den);
1615 Py_DECREF(num);
1616 Py_DECREF(den);
1617 return ans;
Tim Peters78526162001-09-05 00:53:45 +00001618}
1619
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001620PyDoc_STRVAR(math_log_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001621"log(x[, base])\n\n\
1622Return the logarithm of x to the given base.\n\
Raymond Hettinger866964c2002-12-14 19:51:34 +00001623If the base not specified, returns the natural logarithm (base e) of x.");
Tim Peters78526162001-09-05 00:53:45 +00001624
1625static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001626math_log10(PyObject *self, PyObject *arg)
Tim Peters78526162001-09-05 00:53:45 +00001627{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 return loghelper(arg, m_log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +00001629}
1630
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001631PyDoc_STRVAR(math_log10_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001632"log10(x)\n\nReturn the base 10 logarithm of x.");
Tim Peters78526162001-09-05 00:53:45 +00001633
Christian Heimes53876d92008-04-19 00:31:39 +00001634static PyObject *
1635math_fmod(PyObject *self, PyObject *args)
1636{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 PyObject *ox, *oy;
1638 double r, x, y;
1639 if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy))
1640 return NULL;
1641 x = PyFloat_AsDouble(ox);
1642 y = PyFloat_AsDouble(oy);
1643 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1644 return NULL;
1645 /* fmod(x, +/-Inf) returns x for finite x. */
1646 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
1647 return PyFloat_FromDouble(x);
1648 errno = 0;
1649 PyFPE_START_PROTECT("in math_fmod", return 0);
1650 r = fmod(x, y);
1651 PyFPE_END_PROTECT(r);
1652 if (Py_IS_NAN(r)) {
1653 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1654 errno = EDOM;
1655 else
1656 errno = 0;
1657 }
1658 if (errno && is_error(r))
1659 return NULL;
1660 else
1661 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00001662}
1663
1664PyDoc_STRVAR(math_fmod_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001665"fmod(x, y)\n\nReturn fmod(x, y), according to platform C."
Christian Heimes53876d92008-04-19 00:31:39 +00001666" x % y may differ.");
1667
1668static PyObject *
1669math_hypot(PyObject *self, PyObject *args)
1670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 PyObject *ox, *oy;
1672 double r, x, y;
1673 if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy))
1674 return NULL;
1675 x = PyFloat_AsDouble(ox);
1676 y = PyFloat_AsDouble(oy);
1677 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1678 return NULL;
1679 /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */
1680 if (Py_IS_INFINITY(x))
1681 return PyFloat_FromDouble(fabs(x));
1682 if (Py_IS_INFINITY(y))
1683 return PyFloat_FromDouble(fabs(y));
1684 errno = 0;
1685 PyFPE_START_PROTECT("in math_hypot", return 0);
1686 r = hypot(x, y);
1687 PyFPE_END_PROTECT(r);
1688 if (Py_IS_NAN(r)) {
1689 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1690 errno = EDOM;
1691 else
1692 errno = 0;
1693 }
1694 else if (Py_IS_INFINITY(r)) {
1695 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
1696 errno = ERANGE;
1697 else
1698 errno = 0;
1699 }
1700 if (errno && is_error(r))
1701 return NULL;
1702 else
1703 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00001704}
1705
1706PyDoc_STRVAR(math_hypot_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001707"hypot(x, y)\n\nReturn the Euclidean distance, sqrt(x*x + y*y).");
Christian Heimes53876d92008-04-19 00:31:39 +00001708
1709/* pow can't use math_2, but needs its own wrapper: the problem is
1710 that an infinite result can arise either as a result of overflow
1711 (in which case OverflowError should be raised) or as a result of
1712 e.g. 0.**-5. (for which ValueError needs to be raised.)
1713*/
1714
1715static PyObject *
1716math_pow(PyObject *self, PyObject *args)
1717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 PyObject *ox, *oy;
1719 double r, x, y;
1720 int odd_y;
Christian Heimes53876d92008-04-19 00:31:39 +00001721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy))
1723 return NULL;
1724 x = PyFloat_AsDouble(ox);
1725 y = PyFloat_AsDouble(oy);
1726 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1727 return NULL;
Christian Heimesa342c012008-04-20 21:01:16 +00001728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 /* deal directly with IEEE specials, to cope with problems on various
1730 platforms whose semantics don't exactly match C99 */
1731 r = 0.; /* silence compiler warning */
1732 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
1733 errno = 0;
1734 if (Py_IS_NAN(x))
1735 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
1736 else if (Py_IS_NAN(y))
1737 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
1738 else if (Py_IS_INFINITY(x)) {
1739 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
1740 if (y > 0.)
1741 r = odd_y ? x : fabs(x);
1742 else if (y == 0.)
1743 r = 1.;
1744 else /* y < 0. */
1745 r = odd_y ? copysign(0., x) : 0.;
1746 }
1747 else if (Py_IS_INFINITY(y)) {
1748 if (fabs(x) == 1.0)
1749 r = 1.;
1750 else if (y > 0. && fabs(x) > 1.0)
1751 r = y;
1752 else if (y < 0. && fabs(x) < 1.0) {
1753 r = -y; /* result is +inf */
1754 if (x == 0.) /* 0**-inf: divide-by-zero */
1755 errno = EDOM;
1756 }
1757 else
1758 r = 0.;
1759 }
1760 }
1761 else {
1762 /* let libm handle finite**finite */
1763 errno = 0;
1764 PyFPE_START_PROTECT("in math_pow", return 0);
1765 r = pow(x, y);
1766 PyFPE_END_PROTECT(r);
1767 /* a NaN result should arise only from (-ve)**(finite
1768 non-integer); in this case we want to raise ValueError. */
1769 if (!Py_IS_FINITE(r)) {
1770 if (Py_IS_NAN(r)) {
1771 errno = EDOM;
1772 }
1773 /*
1774 an infinite result here arises either from:
1775 (A) (+/-0.)**negative (-> divide-by-zero)
1776 (B) overflow of x**y with x and y finite
1777 */
1778 else if (Py_IS_INFINITY(r)) {
1779 if (x == 0.)
1780 errno = EDOM;
1781 else
1782 errno = ERANGE;
1783 }
1784 }
1785 }
Christian Heimes53876d92008-04-19 00:31:39 +00001786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 if (errno && is_error(r))
1788 return NULL;
1789 else
1790 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00001791}
1792
1793PyDoc_STRVAR(math_pow_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001794"pow(x, y)\n\nReturn x**y (x to the power of y).");
Christian Heimes53876d92008-04-19 00:31:39 +00001795
Christian Heimes072c0f12008-01-03 23:01:04 +00001796static const double degToRad = Py_MATH_PI / 180.0;
1797static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001798
1799static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001800math_degrees(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001801{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 double x = PyFloat_AsDouble(arg);
1803 if (x == -1.0 && PyErr_Occurred())
1804 return NULL;
1805 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001806}
1807
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001808PyDoc_STRVAR(math_degrees_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001809"degrees(x)\n\n\
1810Convert angle x from radians to degrees.");
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001811
1812static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001813math_radians(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001814{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 double x = PyFloat_AsDouble(arg);
1816 if (x == -1.0 && PyErr_Occurred())
1817 return NULL;
1818 return PyFloat_FromDouble(x * degToRad);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001819}
1820
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001821PyDoc_STRVAR(math_radians_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001822"radians(x)\n\n\
1823Convert angle x from degrees to radians.");
Tim Peters78526162001-09-05 00:53:45 +00001824
Christian Heimes072c0f12008-01-03 23:01:04 +00001825static PyObject *
Mark Dickinson8e0c9962010-07-11 17:38:24 +00001826math_isfinite(PyObject *self, PyObject *arg)
1827{
1828 double x = PyFloat_AsDouble(arg);
1829 if (x == -1.0 && PyErr_Occurred())
1830 return NULL;
1831 return PyBool_FromLong((long)Py_IS_FINITE(x));
1832}
1833
1834PyDoc_STRVAR(math_isfinite_doc,
1835"isfinite(x) -> bool\n\n\
Mark Dickinson226f5442010-07-11 18:13:41 +00001836Return True if x is neither an infinity nor a NaN, and False otherwise.");
Mark Dickinson8e0c9962010-07-11 17:38:24 +00001837
1838static PyObject *
Christian Heimes072c0f12008-01-03 23:01:04 +00001839math_isnan(PyObject *self, PyObject *arg)
1840{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 double x = PyFloat_AsDouble(arg);
1842 if (x == -1.0 && PyErr_Occurred())
1843 return NULL;
1844 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00001845}
1846
1847PyDoc_STRVAR(math_isnan_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001848"isnan(x) -> bool\n\n\
Mark Dickinson226f5442010-07-11 18:13:41 +00001849Return True if x is a NaN (not a number), and False otherwise.");
Christian Heimes072c0f12008-01-03 23:01:04 +00001850
1851static PyObject *
1852math_isinf(PyObject *self, PyObject *arg)
1853{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 double x = PyFloat_AsDouble(arg);
1855 if (x == -1.0 && PyErr_Occurred())
1856 return NULL;
1857 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00001858}
1859
1860PyDoc_STRVAR(math_isinf_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001861"isinf(x) -> bool\n\n\
Mark Dickinson226f5442010-07-11 18:13:41 +00001862Return True if x is a positive or negative infinity, and False otherwise.");
Christian Heimes072c0f12008-01-03 23:01:04 +00001863
Barry Warsaw8b43b191996-12-09 22:32:36 +00001864static PyMethodDef math_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 {"acos", math_acos, METH_O, math_acos_doc},
1866 {"acosh", math_acosh, METH_O, math_acosh_doc},
1867 {"asin", math_asin, METH_O, math_asin_doc},
1868 {"asinh", math_asinh, METH_O, math_asinh_doc},
1869 {"atan", math_atan, METH_O, math_atan_doc},
1870 {"atan2", math_atan2, METH_VARARGS, math_atan2_doc},
1871 {"atanh", math_atanh, METH_O, math_atanh_doc},
1872 {"ceil", math_ceil, METH_O, math_ceil_doc},
1873 {"copysign", math_copysign, METH_VARARGS, math_copysign_doc},
1874 {"cos", math_cos, METH_O, math_cos_doc},
1875 {"cosh", math_cosh, METH_O, math_cosh_doc},
1876 {"degrees", math_degrees, METH_O, math_degrees_doc},
1877 {"erf", math_erf, METH_O, math_erf_doc},
1878 {"erfc", math_erfc, METH_O, math_erfc_doc},
1879 {"exp", math_exp, METH_O, math_exp_doc},
1880 {"expm1", math_expm1, METH_O, math_expm1_doc},
1881 {"fabs", math_fabs, METH_O, math_fabs_doc},
1882 {"factorial", math_factorial, METH_O, math_factorial_doc},
1883 {"floor", math_floor, METH_O, math_floor_doc},
1884 {"fmod", math_fmod, METH_VARARGS, math_fmod_doc},
1885 {"frexp", math_frexp, METH_O, math_frexp_doc},
1886 {"fsum", math_fsum, METH_O, math_fsum_doc},
1887 {"gamma", math_gamma, METH_O, math_gamma_doc},
1888 {"hypot", math_hypot, METH_VARARGS, math_hypot_doc},
Mark Dickinson8e0c9962010-07-11 17:38:24 +00001889 {"isfinite", math_isfinite, METH_O, math_isfinite_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 {"isinf", math_isinf, METH_O, math_isinf_doc},
1891 {"isnan", math_isnan, METH_O, math_isnan_doc},
1892 {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc},
1893 {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
1894 {"log", math_log, METH_VARARGS, math_log_doc},
1895 {"log1p", math_log1p, METH_O, math_log1p_doc},
1896 {"log10", math_log10, METH_O, math_log10_doc},
1897 {"modf", math_modf, METH_O, math_modf_doc},
1898 {"pow", math_pow, METH_VARARGS, math_pow_doc},
1899 {"radians", math_radians, METH_O, math_radians_doc},
1900 {"sin", math_sin, METH_O, math_sin_doc},
1901 {"sinh", math_sinh, METH_O, math_sinh_doc},
1902 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
1903 {"tan", math_tan, METH_O, math_tan_doc},
1904 {"tanh", math_tanh, METH_O, math_tanh_doc},
1905 {"trunc", math_trunc, METH_O, math_trunc_doc},
1906 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001907};
1908
Guido van Rossumc6e22901998-12-04 19:26:43 +00001909
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001910PyDoc_STRVAR(module_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001911"This module is always available. It provides access to the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001912"mathematical functions defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001913
Martin v. Löwis1a214512008-06-11 05:26:20 +00001914
1915static struct PyModuleDef mathmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 PyModuleDef_HEAD_INIT,
1917 "math",
1918 module_doc,
1919 -1,
1920 math_methods,
1921 NULL,
1922 NULL,
1923 NULL,
1924 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001925};
1926
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001927PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001928PyInit_math(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001929{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 PyObject *m;
Tim Petersfe71f812001-08-07 22:10:00 +00001931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 m = PyModule_Create(&mathmodule);
1933 if (m == NULL)
1934 goto finally;
Barry Warsawfc93f751996-12-17 00:47:03 +00001935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
1937 PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
Barry Warsawfc93f751996-12-17 00:47:03 +00001938
Christian Heimes53876d92008-04-19 00:31:39 +00001939 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001941}