blob: 77b56a0027fcfd60e6b2e7a2c595f716e65d0d70 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Math module -- standard C math library functions, pi and e */
2
Christian Heimes6f341092008-04-18 23:13:07 +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 Dickinson9cae1782009-12-16 20:13:40 +000056#include "_math.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000057
Neal Norwitz5f95a792008-01-25 08:04:16 +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 Dickinsonb93fff02009-09-28 18:54:55 +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 Dickinsonb93fff02009-09-28 18:54:55 +000070static const double pi = 3.141592653589793238462643383279502884197;
Mark Dickinson5ff37ae2009-12-19 11:07:23 +000071static const double sqrtpi = 1.772453850905516027298167483341145182798;
Mark Dickinsonb93fff02009-09-28 18:54:55 +000072
73static double
74sinpi(double x)
75{
Antoine Pitrouc83ea132010-05-09 14:46:46 +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 Dickinsonb93fff02009-09-28 18:54:55 +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 Pitrouc83ea132010-05-09 14:46:46 +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 Dickinsonb93fff02009-09-28 18:54:55 +0000182};
183
184/* denominator is x*(x+1)*...*(x+LANCZOS_N-2) */
185static const double lanczos_den_coeffs[LANCZOS_N] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +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 Dickinsonb93fff02009-09-28 18:54:55 +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 Pitrouc83ea132010-05-09 14:46:46 +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 Dickinsonb93fff02009-09-28 18:54:55 +0000197};
198
199/* Lanczos' sum L_g(x), for positive x */
200
201static double
202lanczos_sum(double x)
203{
Antoine Pitrouc83ea132010-05-09 14:46:46 +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 Dickinsonb93fff02009-09-28 18:54:55 +0000228}
229
230static double
231m_tgamma(double x)
232{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000233 double absx, r, y, z, sqrtpow;
Mark Dickinsonb93fff02009-09-28 18:54:55 +0000234
Antoine Pitrouc83ea132010-05-09 14:46:46 +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 Dickinsonb93fff02009-09-28 18:54:55 +0000248
Antoine Pitrouc83ea132010-05-09 14:46:46 +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 Dickinsonb93fff02009-09-28 18:54:55 +0000259
Antoine Pitrouc83ea132010-05-09 14:46:46 +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 Dickinsonb93fff02009-09-28 18:54:55 +0000267
Antoine Pitrouc83ea132010-05-09 14:46:46 +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 Dickinsonb93fff02009-09-28 18:54:55 +0000280
Antoine Pitrouc83ea132010-05-09 14:46:46 +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 Heimes6f341092008-04-18 23:13:07 +0000325/*
Mark Dickinson9be87bc2009-12-11 17:29:33 +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 Pitrouc83ea132010-05-09 14:46:46 +0000333 double r, absx;
Mark Dickinson9be87bc2009-12-11 17:29:33 +0000334
Antoine Pitrouc83ea132010-05-09 14:46:46 +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 Dickinson9be87bc2009-12-11 17:29:33 +0000342
Antoine Pitrouc83ea132010-05-09 14:46:46 +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 Dickinson9be87bc2009-12-11 17:29:33 +0000353
Antoine Pitrouc83ea132010-05-09 14:46:46 +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 Dickinson9be87bc2009-12-11 17:29:33 +0000358
Antoine Pitrouc83ea132010-05-09 14:46:46 +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 Dickinson9be87bc2009-12-11 17:29:33 +0000376}
377
Mark Dickinson5ff37ae2009-12-19 11:07:23 +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{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000431 double x2, acc, fk;
432 int i;
Mark Dickinson5ff37ae2009-12-19 11:07:23 +0000433
Antoine Pitrouc83ea132010-05-09 14:46:46 +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 }
441 return acc * x * exp(-x2) / sqrtpi;
Mark Dickinson5ff37ae2009-12-19 11:07:23 +0000442}
443
444/*
445 Complementary error function, via continued fraction expansion.
446
447 Given a positive float x, return an approximation to erfc(x). Converges
448 reasonably fast for x large (say, x > 2.0), and should be safe from
449 overflow if x and nterms are not too large. On an IEEE 754 machine, with x
450 <= 30.0, we're safe up to nterms = 100. For x >= 30.0, erfc(x) is smaller
451 than the smallest representable nonzero float. */
452
453static double
454m_erfc_contfrac(double x)
455{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000456 double x2, a, da, p, p_last, q, q_last, b;
457 int i;
Mark Dickinson5ff37ae2009-12-19 11:07:23 +0000458
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000459 if (x >= ERFC_CONTFRAC_CUTOFF)
460 return 0.0;
Mark Dickinson5ff37ae2009-12-19 11:07:23 +0000461
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000462 x2 = x*x;
463 a = 0.0;
464 da = 0.5;
465 p = 1.0; p_last = 0.0;
466 q = da + x2; q_last = 1.0;
467 for (i = 0; i < ERFC_CONTFRAC_TERMS; i++) {
468 double temp;
469 a += da;
470 da += 2.0;
471 b = da + x2;
472 temp = p; p = b*p - a*p_last; p_last = temp;
473 temp = q; q = b*q - a*q_last; q_last = temp;
474 }
475 return p / q * x * exp(-x2) / sqrtpi;
Mark Dickinson5ff37ae2009-12-19 11:07:23 +0000476}
477
478/* Error function erf(x), for general x */
479
480static double
481m_erf(double x)
482{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000483 double absx, cf;
Mark Dickinson5ff37ae2009-12-19 11:07:23 +0000484
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000485 if (Py_IS_NAN(x))
486 return x;
487 absx = fabs(x);
488 if (absx < ERF_SERIES_CUTOFF)
489 return m_erf_series(x);
490 else {
491 cf = m_erfc_contfrac(absx);
492 return x > 0.0 ? 1.0 - cf : cf - 1.0;
493 }
Mark Dickinson5ff37ae2009-12-19 11:07:23 +0000494}
495
496/* Complementary error function erfc(x), for general x. */
497
498static double
499m_erfc(double x)
500{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000501 double absx, cf;
Mark Dickinson5ff37ae2009-12-19 11:07:23 +0000502
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000503 if (Py_IS_NAN(x))
504 return x;
505 absx = fabs(x);
506 if (absx < ERF_SERIES_CUTOFF)
507 return 1.0 - m_erf_series(x);
508 else {
509 cf = m_erfc_contfrac(absx);
510 return x > 0.0 ? cf : 2.0 - cf;
511 }
Mark Dickinson5ff37ae2009-12-19 11:07:23 +0000512}
Mark Dickinson9be87bc2009-12-11 17:29:33 +0000513
514/*
Mark Dickinson92483cd2008-04-20 21:39:04 +0000515 wrapper for atan2 that deals directly with special cases before
516 delegating to the platform libm for the remaining cases. This
517 is necessary to get consistent behaviour across platforms.
518 Windows, FreeBSD and alpha Tru64 are amongst platforms that don't
519 always follow C99.
520*/
521
522static double
523m_atan2(double y, double x)
524{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000525 if (Py_IS_NAN(x) || Py_IS_NAN(y))
526 return Py_NAN;
527 if (Py_IS_INFINITY(y)) {
528 if (Py_IS_INFINITY(x)) {
529 if (copysign(1., x) == 1.)
530 /* atan2(+-inf, +inf) == +-pi/4 */
531 return copysign(0.25*Py_MATH_PI, y);
532 else
533 /* atan2(+-inf, -inf) == +-pi*3/4 */
534 return copysign(0.75*Py_MATH_PI, y);
535 }
536 /* atan2(+-inf, x) == +-pi/2 for finite x */
537 return copysign(0.5*Py_MATH_PI, y);
538 }
539 if (Py_IS_INFINITY(x) || y == 0.) {
540 if (copysign(1., x) == 1.)
541 /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */
542 return copysign(0., y);
543 else
544 /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */
545 return copysign(Py_MATH_PI, y);
546 }
547 return atan2(y, x);
Mark Dickinson92483cd2008-04-20 21:39:04 +0000548}
549
550/*
Mark Dickinson4c96fa52008-12-11 19:28:08 +0000551 Various platforms (Solaris, OpenBSD) do nonstandard things for log(0),
552 log(-ve), log(NaN). Here are wrappers for log and log10 that deal with
553 special values directly, passing positive non-special values through to
554 the system log/log10.
555 */
556
557static double
558m_log(double x)
559{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000560 if (Py_IS_FINITE(x)) {
561 if (x > 0.0)
562 return log(x);
563 errno = EDOM;
564 if (x == 0.0)
565 return -Py_HUGE_VAL; /* log(0) = -inf */
566 else
567 return Py_NAN; /* log(-ve) = nan */
568 }
569 else if (Py_IS_NAN(x))
570 return x; /* log(nan) = nan */
571 else if (x > 0.0)
572 return x; /* log(inf) = inf */
573 else {
574 errno = EDOM;
575 return Py_NAN; /* log(-inf) = nan */
576 }
Mark Dickinson4c96fa52008-12-11 19:28:08 +0000577}
578
579static double
580m_log10(double x)
581{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000582 if (Py_IS_FINITE(x)) {
583 if (x > 0.0)
584 return log10(x);
585 errno = EDOM;
586 if (x == 0.0)
587 return -Py_HUGE_VAL; /* log10(0) = -inf */
588 else
589 return Py_NAN; /* log10(-ve) = nan */
590 }
591 else if (Py_IS_NAN(x))
592 return x; /* log10(nan) = nan */
593 else if (x > 0.0)
594 return x; /* log10(inf) = inf */
595 else {
596 errno = EDOM;
597 return Py_NAN; /* log10(-inf) = nan */
598 }
Mark Dickinson4c96fa52008-12-11 19:28:08 +0000599}
600
601
Mark Dickinsonb93fff02009-09-28 18:54:55 +0000602/* Call is_error when errno != 0, and where x is the result libm
603 * returned. is_error will usually set up an exception and return
604 * true (1), but may return false (0) without setting up an exception.
605 */
606static int
607is_error(double x)
608{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000609 int result = 1; /* presumption of guilt */
610 assert(errno); /* non-zero errno is a precondition for calling */
611 if (errno == EDOM)
612 PyErr_SetString(PyExc_ValueError, "math domain error");
Mark Dickinsonb93fff02009-09-28 18:54:55 +0000613
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000614 else if (errno == ERANGE) {
615 /* ANSI C generally requires libm functions to set ERANGE
616 * on overflow, but also generally *allows* them to set
617 * ERANGE on underflow too. There's no consistency about
618 * the latter across platforms.
619 * Alas, C99 never requires that errno be set.
620 * Here we suppress the underflow errors (libm functions
621 * should return a zero on underflow, and +- HUGE_VAL on
622 * overflow, so testing the result for zero suffices to
623 * distinguish the cases).
624 *
625 * On some platforms (Ubuntu/ia64) it seems that errno can be
626 * set to ERANGE for subnormal results that do *not* underflow
627 * to zero. So to be safe, we'll ignore ERANGE whenever the
628 * function result is less than one in absolute value.
629 */
630 if (fabs(x) < 1.0)
631 result = 0;
632 else
633 PyErr_SetString(PyExc_OverflowError,
634 "math range error");
635 }
636 else
637 /* Unexpected math error */
638 PyErr_SetFromErrno(PyExc_ValueError);
639 return result;
Mark Dickinsonb93fff02009-09-28 18:54:55 +0000640}
641
Mark Dickinson4c96fa52008-12-11 19:28:08 +0000642/*
Christian Heimes6f341092008-04-18 23:13:07 +0000643 math_1 is used to wrap a libm function f that takes a double
644 arguments and returns a double.
645
646 The error reporting follows these rules, which are designed to do
647 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
648 platforms.
649
650 - a NaN result from non-NaN inputs causes ValueError to be raised
651 - an infinite result from finite inputs causes OverflowError to be
652 raised if can_overflow is 1, or raises ValueError if can_overflow
653 is 0.
654 - if the result is finite and errno == EDOM then ValueError is
655 raised
656 - if the result is finite and nonzero and errno == ERANGE then
657 OverflowError is raised
658
659 The last rule is used to catch overflow on platforms which follow
660 C89 but for which HUGE_VAL is not an infinity.
661
662 For the majority of one-argument functions these rules are enough
663 to ensure that Python's functions behave as specified in 'Annex F'
664 of the C99 standard, with the 'invalid' and 'divide-by-zero'
665 floating-point exceptions mapping to Python's ValueError and the
666 'overflow' floating-point exception mapping to OverflowError.
667 math_1 only works for functions that don't have singularities *and*
668 the possibility of overflow; fortunately, that covers everything we
669 care about right now.
670*/
671
Barry Warsaw8b43b191996-12-09 22:32:36 +0000672static PyObject *
Christian Heimes6f341092008-04-18 23:13:07 +0000673math_1(PyObject *arg, double (*func) (double), int can_overflow)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000674{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000675 double x, r;
676 x = PyFloat_AsDouble(arg);
677 if (x == -1.0 && PyErr_Occurred())
678 return NULL;
679 errno = 0;
680 PyFPE_START_PROTECT("in math_1", return 0);
681 r = (*func)(x);
682 PyFPE_END_PROTECT(r);
683 if (Py_IS_NAN(r)) {
684 if (!Py_IS_NAN(x))
685 errno = EDOM;
686 else
687 errno = 0;
688 }
689 else if (Py_IS_INFINITY(r)) {
690 if (Py_IS_FINITE(x))
691 errno = can_overflow ? ERANGE : EDOM;
692 else
693 errno = 0;
694 }
695 if (errno && is_error(r))
696 return NULL;
697 else
698 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000699}
700
Mark Dickinsonb93fff02009-09-28 18:54:55 +0000701/* variant of math_1, to be used when the function being wrapped is known to
702 set errno properly (that is, errno = EDOM for invalid or divide-by-zero,
703 errno = ERANGE for overflow). */
704
705static PyObject *
706math_1a(PyObject *arg, double (*func) (double))
707{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000708 double x, r;
709 x = PyFloat_AsDouble(arg);
710 if (x == -1.0 && PyErr_Occurred())
711 return NULL;
712 errno = 0;
713 PyFPE_START_PROTECT("in math_1a", return 0);
714 r = (*func)(x);
715 PyFPE_END_PROTECT(r);
716 if (errno && is_error(r))
717 return NULL;
718 return PyFloat_FromDouble(r);
Mark Dickinsonb93fff02009-09-28 18:54:55 +0000719}
720
Christian Heimes6f341092008-04-18 23:13:07 +0000721/*
722 math_2 is used to wrap a libm function f that takes two double
723 arguments and returns a double.
724
725 The error reporting follows these rules, which are designed to do
726 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
727 platforms.
728
729 - a NaN result from non-NaN inputs causes ValueError to be raised
730 - an infinite result from finite inputs causes OverflowError to be
731 raised.
732 - if the result is finite and errno == EDOM then ValueError is
733 raised
734 - if the result is finite and nonzero and errno == ERANGE then
735 OverflowError is raised
736
737 The last rule is used to catch overflow on platforms which follow
738 C89 but for which HUGE_VAL is not an infinity.
739
740 For most two-argument functions (copysign, fmod, hypot, atan2)
741 these rules are enough to ensure that Python's functions behave as
742 specified in 'Annex F' of the C99 standard, with the 'invalid' and
743 'divide-by-zero' floating-point exceptions mapping to Python's
744 ValueError and the 'overflow' floating-point exception mapping to
745 OverflowError.
746*/
747
Barry Warsaw8b43b191996-12-09 22:32:36 +0000748static PyObject *
Neal Norwitz45e230a2006-11-19 21:26:53 +0000749math_2(PyObject *args, double (*func) (double, double), char *funcname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000750{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000751 PyObject *ox, *oy;
752 double x, y, r;
753 if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy))
754 return NULL;
755 x = PyFloat_AsDouble(ox);
756 y = PyFloat_AsDouble(oy);
757 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
758 return NULL;
759 errno = 0;
760 PyFPE_START_PROTECT("in math_2", return 0);
761 r = (*func)(x, y);
762 PyFPE_END_PROTECT(r);
763 if (Py_IS_NAN(r)) {
764 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
765 errno = EDOM;
766 else
767 errno = 0;
768 }
769 else if (Py_IS_INFINITY(r)) {
770 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
771 errno = ERANGE;
772 else
773 errno = 0;
774 }
775 if (errno && is_error(r))
776 return NULL;
777 else
778 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000779}
780
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000781#define FUNC1(funcname, func, can_overflow, docstring) \
782 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
783 return math_1(args, func, can_overflow); \
784 }\
785 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000786
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000787#define FUNC1A(funcname, func, docstring) \
788 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
789 return math_1a(args, func); \
790 }\
791 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Mark Dickinsonb93fff02009-09-28 18:54:55 +0000792
Fred Drake40c48682000-07-03 18:11:56 +0000793#define FUNC2(funcname, func, docstring) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000794 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
795 return math_2(args, func, #funcname); \
796 }\
797 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000798
Christian Heimes6f341092008-04-18 23:13:07 +0000799FUNC1(acos, acos, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000800 "acos(x)\n\nReturn the arc cosine (measured in radians) of x.")
Mark Dickinson12748b02009-12-21 15:22:00 +0000801FUNC1(acosh, m_acosh, 0,
Christian Heimes6f341092008-04-18 23:13:07 +0000802 "acosh(x)\n\nReturn the hyperbolic arc cosine (measured in radians) of x.")
803FUNC1(asin, asin, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000804 "asin(x)\n\nReturn the arc sine (measured in radians) of x.")
Mark Dickinson12748b02009-12-21 15:22:00 +0000805FUNC1(asinh, m_asinh, 0,
Christian Heimes6f341092008-04-18 23:13:07 +0000806 "asinh(x)\n\nReturn the hyperbolic arc sine (measured in radians) of x.")
807FUNC1(atan, atan, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000808 "atan(x)\n\nReturn the arc tangent (measured in radians) of x.")
Mark Dickinson92483cd2008-04-20 21:39:04 +0000809FUNC2(atan2, m_atan2,
Tim Petersfe71f812001-08-07 22:10:00 +0000810 "atan2(y, x)\n\nReturn the arc tangent (measured in radians) of y/x.\n"
811 "Unlike atan(y/x), the signs of both x and y are considered.")
Mark Dickinson12748b02009-12-21 15:22:00 +0000812FUNC1(atanh, m_atanh, 0,
Christian Heimes6f341092008-04-18 23:13:07 +0000813 "atanh(x)\n\nReturn the hyperbolic arc tangent (measured in radians) of x.")
814FUNC1(ceil, ceil, 0,
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +0000815 "ceil(x)\n\nReturn the ceiling of x as a float.\n"
816 "This is the smallest integral value >= x.")
Christian Heimeseebb79c2008-01-03 22:32:26 +0000817FUNC2(copysign, copysign,
Georg Brandla8f8bed22009-10-29 20:54:03 +0000818 "copysign(x, y)\n\nReturn x with the sign of y.")
Christian Heimes6f341092008-04-18 23:13:07 +0000819FUNC1(cos, cos, 0,
820 "cos(x)\n\nReturn the cosine of x (measured in radians).")
821FUNC1(cosh, cosh, 1,
822 "cosh(x)\n\nReturn the hyperbolic cosine of x.")
Mark Dickinson5ff37ae2009-12-19 11:07:23 +0000823FUNC1A(erf, m_erf,
824 "erf(x)\n\nError function at x.")
825FUNC1A(erfc, m_erfc,
826 "erfc(x)\n\nComplementary error function at x.")
Christian Heimes6f341092008-04-18 23:13:07 +0000827FUNC1(exp, exp, 1,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000828 "exp(x)\n\nReturn e raised to the power of x.")
Mark Dickinson9cae1782009-12-16 20:13:40 +0000829FUNC1(expm1, m_expm1, 1,
830 "expm1(x)\n\nReturn exp(x)-1.\n"
831 "This function avoids the loss of precision involved in the direct "
832 "evaluation of exp(x)-1 for small x.")
Christian Heimes6f341092008-04-18 23:13:07 +0000833FUNC1(fabs, fabs, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000834 "fabs(x)\n\nReturn the absolute value of the float x.")
Christian Heimes6f341092008-04-18 23:13:07 +0000835FUNC1(floor, floor, 0,
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +0000836 "floor(x)\n\nReturn the floor of x as a float.\n"
837 "This is the largest integral value <= x.")
Mark Dickinsonb93fff02009-09-28 18:54:55 +0000838FUNC1A(gamma, m_tgamma,
839 "gamma(x)\n\nGamma function at x.")
Mark Dickinson9be87bc2009-12-11 17:29:33 +0000840FUNC1A(lgamma, m_lgamma,
841 "lgamma(x)\n\nNatural logarithm of absolute value of Gamma function at x.")
Mark Dickinson12748b02009-12-21 15:22:00 +0000842FUNC1(log1p, m_log1p, 1,
Georg Brandla8f8bed22009-10-29 20:54:03 +0000843 "log1p(x)\n\nReturn the natural logarithm of 1+x (base e).\n"
844 "The result is computed in a way which is accurate for x near zero.")
Christian Heimes6f341092008-04-18 23:13:07 +0000845FUNC1(sin, sin, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000846 "sin(x)\n\nReturn the sine of x (measured in radians).")
Christian Heimes6f341092008-04-18 23:13:07 +0000847FUNC1(sinh, sinh, 1,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000848 "sinh(x)\n\nReturn the hyperbolic sine of x.")
Christian Heimes6f341092008-04-18 23:13:07 +0000849FUNC1(sqrt, sqrt, 0,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000850 "sqrt(x)\n\nReturn the square root of x.")
Christian Heimes6f341092008-04-18 23:13:07 +0000851FUNC1(tan, tan, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000852 "tan(x)\n\nReturn the tangent of x (measured in radians).")
Christian Heimes6f341092008-04-18 23:13:07 +0000853FUNC1(tanh, tanh, 0,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000854 "tanh(x)\n\nReturn the hyperbolic tangent of x.")
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000855
Mark Dickinson99dfe922008-05-23 01:35:30 +0000856/* Precision summation function as msum() by Raymond Hettinger in
857 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
858 enhanced with the exact partials sum and roundoff from Mark
859 Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000860 See those links for more details, proofs and other references.
Mark Dickinson99dfe922008-05-23 01:35:30 +0000861
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000862 Note 1: IEEE 754R floating point semantics are assumed,
863 but the current implementation does not re-establish special
864 value semantics across iterations (i.e. handling -Inf + Inf).
Mark Dickinson99dfe922008-05-23 01:35:30 +0000865
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000866 Note 2: No provision is made for intermediate overflow handling;
Raymond Hettinger2a9179a2008-05-29 08:38:23 +0000867 therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000868 sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
869 overflow of the first partial sum.
Mark Dickinson99dfe922008-05-23 01:35:30 +0000870
Andrew M. Kuchling5f198be2008-06-20 02:11:42 +0000871 Note 3: The intermediate values lo, yr, and hi are declared volatile so
Mark Dickinson2fcd8c92008-06-20 15:26:19 +0000872 aggressive compilers won't algebraically reduce lo to always be exactly 0.0.
Raymond Hettingerd6234142008-06-09 11:24:47 +0000873 Also, the volatile declaration forces the values to be stored in memory as
874 regular doubles instead of extended long precision (80-bit) values. This
Andrew M. Kuchling5f198be2008-06-20 02:11:42 +0000875 prevents double rounding because any addition or subtraction of two doubles
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000876 can be resolved exactly into double-sized hi and lo values. As long as the
Raymond Hettingerd6234142008-06-09 11:24:47 +0000877 hi value gets forced into a double before yr and lo are computed, the extra
878 bits in downstream extended precision operations (x87 for example) will be
879 exactly zero and therefore can be losslessly stored back into a double,
880 thereby preventing double rounding.
Mark Dickinson99dfe922008-05-23 01:35:30 +0000881
Raymond Hettingerd6234142008-06-09 11:24:47 +0000882 Note 4: A similar implementation is in Modules/cmathmodule.c.
883 Be sure to update both when making changes.
Mark Dickinson99dfe922008-05-23 01:35:30 +0000884
Mark Dickinsonff3fdce2008-07-30 16:25:16 +0000885 Note 5: The signature of math.fsum() differs from __builtin__.sum()
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000886 because the start argument doesn't make sense in the context of
887 accurate summation. Since the partials table is collapsed before
888 returning a result, sum(seq2, start=sum(seq1)) may not equal the
889 accurate result returned by sum(itertools.chain(seq1, seq2)).
Mark Dickinson99dfe922008-05-23 01:35:30 +0000890*/
891
892#define NUM_PARTIALS 32 /* initial partials array size, on stack */
893
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000894/* Extend the partials array p[] by doubling its size. */
895static int /* non-zero on error */
Mark Dickinsonfef6b132008-07-30 16:20:10 +0000896_fsum_realloc(double **p_ptr, Py_ssize_t n,
Raymond Hettingerd6234142008-06-09 11:24:47 +0000897 double *ps, Py_ssize_t *m_ptr)
Mark Dickinson99dfe922008-05-23 01:35:30 +0000898{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000899 void *v = NULL;
900 Py_ssize_t m = *m_ptr;
Mark Dickinson99dfe922008-05-23 01:35:30 +0000901
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000902 m += m; /* double */
903 if (n < m && m < (PY_SSIZE_T_MAX / sizeof(double))) {
904 double *p = *p_ptr;
905 if (p == ps) {
906 v = PyMem_Malloc(sizeof(double) * m);
907 if (v != NULL)
908 memcpy(v, ps, sizeof(double) * n);
909 }
910 else
911 v = PyMem_Realloc(p, sizeof(double) * m);
912 }
913 if (v == NULL) { /* size overflow or no memory */
914 PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
915 return 1;
916 }
917 *p_ptr = (double*) v;
918 *m_ptr = m;
919 return 0;
Mark Dickinson99dfe922008-05-23 01:35:30 +0000920}
921
922/* Full precision summation of a sequence of floats.
923
924 def msum(iterable):
925 partials = [] # sorted, non-overlapping partial sums
926 for x in iterable:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000927 i = 0
928 for y in partials:
929 if abs(x) < abs(y):
930 x, y = y, x
931 hi = x + y
932 lo = y - (hi - x)
933 if lo:
934 partials[i] = lo
935 i += 1
936 x = hi
937 partials[i:] = [x]
Mark Dickinson99dfe922008-05-23 01:35:30 +0000938 return sum_exact(partials)
939
940 Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
941 are exactly equal to x+y. The inner loop applies hi/lo summation to each
942 partial so that the list of partial sums remains exact.
943
944 Sum_exact() adds the partial sums exactly and correctly rounds the final
945 result (using the round-half-to-even rule). The items in partials remain
946 non-zero, non-special, non-overlapping and strictly increasing in
947 magnitude, but possibly not all having the same sign.
948
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000949 Depends on IEEE 754 arithmetic guarantees and half-even rounding.
950*/
951
Mark Dickinson99dfe922008-05-23 01:35:30 +0000952static PyObject*
Mark Dickinsonfef6b132008-07-30 16:20:10 +0000953math_fsum(PyObject *self, PyObject *seq)
Mark Dickinson99dfe922008-05-23 01:35:30 +0000954{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000955 PyObject *item, *iter, *sum = NULL;
956 Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
957 double x, y, t, ps[NUM_PARTIALS], *p = ps;
958 double xsave, special_sum = 0.0, inf_sum = 0.0;
959 volatile double hi, yr, lo;
Mark Dickinson99dfe922008-05-23 01:35:30 +0000960
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000961 iter = PyObject_GetIter(seq);
962 if (iter == NULL)
963 return NULL;
Mark Dickinson99dfe922008-05-23 01:35:30 +0000964
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000965 PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL)
Mark Dickinson99dfe922008-05-23 01:35:30 +0000966
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000967 for(;;) { /* for x in iterable */
968 assert(0 <= n && n <= m);
969 assert((m == NUM_PARTIALS && p == ps) ||
970 (m > NUM_PARTIALS && p != NULL));
Mark Dickinson99dfe922008-05-23 01:35:30 +0000971
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000972 item = PyIter_Next(iter);
973 if (item == NULL) {
974 if (PyErr_Occurred())
975 goto _fsum_error;
976 break;
977 }
978 x = PyFloat_AsDouble(item);
979 Py_DECREF(item);
980 if (PyErr_Occurred())
981 goto _fsum_error;
Mark Dickinson99dfe922008-05-23 01:35:30 +0000982
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000983 xsave = x;
984 for (i = j = 0; j < n; j++) { /* for y in partials */
985 y = p[j];
986 if (fabs(x) < fabs(y)) {
987 t = x; x = y; y = t;
988 }
989 hi = x + y;
990 yr = hi - x;
991 lo = y - yr;
992 if (lo != 0.0)
993 p[i++] = lo;
994 x = hi;
995 }
Mark Dickinsonabe0aee2008-07-30 12:01:41 +0000996
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000997 n = i; /* ps[i:] = [x] */
998 if (x != 0.0) {
999 if (! Py_IS_FINITE(x)) {
1000 /* a nonfinite x could arise either as
1001 a result of intermediate overflow, or
1002 as a result of a nan or inf in the
1003 summands */
1004 if (Py_IS_FINITE(xsave)) {
1005 PyErr_SetString(PyExc_OverflowError,
1006 "intermediate overflow in fsum");
1007 goto _fsum_error;
1008 }
1009 if (Py_IS_INFINITY(xsave))
1010 inf_sum += xsave;
1011 special_sum += xsave;
1012 /* reset partials */
1013 n = 0;
1014 }
1015 else if (n >= m && _fsum_realloc(&p, n, ps, &m))
1016 goto _fsum_error;
1017 else
1018 p[n++] = x;
1019 }
1020 }
Mark Dickinson99dfe922008-05-23 01:35:30 +00001021
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001022 if (special_sum != 0.0) {
1023 if (Py_IS_NAN(inf_sum))
1024 PyErr_SetString(PyExc_ValueError,
1025 "-inf + inf in fsum");
1026 else
1027 sum = PyFloat_FromDouble(special_sum);
1028 goto _fsum_error;
1029 }
Mark Dickinsonabe0aee2008-07-30 12:01:41 +00001030
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001031 hi = 0.0;
1032 if (n > 0) {
1033 hi = p[--n];
1034 /* sum_exact(ps, hi) from the top, stop when the sum becomes
1035 inexact. */
1036 while (n > 0) {
1037 x = hi;
1038 y = p[--n];
1039 assert(fabs(y) < fabs(x));
1040 hi = x + y;
1041 yr = hi - x;
1042 lo = y - yr;
1043 if (lo != 0.0)
1044 break;
1045 }
1046 /* Make half-even rounding work across multiple partials.
1047 Needed so that sum([1e-16, 1, 1e16]) will round-up the last
1048 digit to two instead of down to zero (the 1e-16 makes the 1
1049 slightly closer to two). With a potential 1 ULP rounding
1050 error fixed-up, math.fsum() can guarantee commutativity. */
1051 if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
1052 (lo > 0.0 && p[n-1] > 0.0))) {
1053 y = lo * 2.0;
1054 x = hi + y;
1055 yr = x - hi;
1056 if (y == yr)
1057 hi = x;
1058 }
1059 }
1060 sum = PyFloat_FromDouble(hi);
Mark Dickinson99dfe922008-05-23 01:35:30 +00001061
Mark Dickinsonfef6b132008-07-30 16:20:10 +00001062_fsum_error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001063 PyFPE_END_PROTECT(hi)
1064 Py_DECREF(iter);
1065 if (p != ps)
1066 PyMem_Free(p);
1067 return sum;
Mark Dickinson99dfe922008-05-23 01:35:30 +00001068}
1069
1070#undef NUM_PARTIALS
1071
Mark Dickinsonfef6b132008-07-30 16:20:10 +00001072PyDoc_STRVAR(math_fsum_doc,
Georg Brandl40777e62009-10-29 20:38:32 +00001073"fsum(iterable)\n\n\
Raymond Hettinger778d5cc2008-05-23 04:32:43 +00001074Return an accurate floating point sum of values in the iterable.\n\
1075Assumes IEEE-754 floating point arithmetic.");
Mark Dickinson99dfe922008-05-23 01:35:30 +00001076
Raymond Hettingerecbdd2e2008-06-09 06:54:45 +00001077static PyObject *
1078math_factorial(PyObject *self, PyObject *arg)
1079{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001080 long i, x;
1081 PyObject *result, *iobj, *newresult;
Raymond Hettingerecbdd2e2008-06-09 06:54:45 +00001082
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001083 if (PyFloat_Check(arg)) {
1084 PyObject *lx;
1085 double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
1086 if (!(Py_IS_FINITE(dx) && dx == floor(dx))) {
1087 PyErr_SetString(PyExc_ValueError,
1088 "factorial() only accepts integral values");
1089 return NULL;
1090 }
1091 lx = PyLong_FromDouble(dx);
1092 if (lx == NULL)
1093 return NULL;
1094 x = PyLong_AsLong(lx);
1095 Py_DECREF(lx);
1096 }
1097 else
1098 x = PyInt_AsLong(arg);
Raymond Hettingerecbdd2e2008-06-09 06:54:45 +00001099
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001100 if (x == -1 && PyErr_Occurred())
1101 return NULL;
1102 if (x < 0) {
1103 PyErr_SetString(PyExc_ValueError,
1104 "factorial() not defined for negative values");
1105 return NULL;
1106 }
Raymond Hettingerecbdd2e2008-06-09 06:54:45 +00001107
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001108 result = (PyObject *)PyInt_FromLong(1);
1109 if (result == NULL)
1110 return NULL;
1111 for (i=1 ; i<=x ; i++) {
1112 iobj = (PyObject *)PyInt_FromLong(i);
1113 if (iobj == NULL)
1114 goto error;
1115 newresult = PyNumber_Multiply(result, iobj);
1116 Py_DECREF(iobj);
1117 if (newresult == NULL)
1118 goto error;
1119 Py_DECREF(result);
1120 result = newresult;
1121 }
1122 return result;
Raymond Hettingerecbdd2e2008-06-09 06:54:45 +00001123
1124error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001125 Py_DECREF(result);
1126 return NULL;
Raymond Hettingerecbdd2e2008-06-09 06:54:45 +00001127}
1128
Benjamin Petersonfed67fd2008-12-20 02:57:19 +00001129PyDoc_STRVAR(math_factorial_doc,
1130"factorial(x) -> Integral\n"
1131"\n"
1132"Find x!. Raise a ValueError if x is negative or non-integral.");
Raymond Hettingerecbdd2e2008-06-09 06:54:45 +00001133
Barry Warsaw8b43b191996-12-09 22:32:36 +00001134static PyObject *
Jeffrey Yasskinca2b69f2008-02-01 06:22:46 +00001135math_trunc(PyObject *self, PyObject *number)
1136{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001137 return PyObject_CallMethod(number, "__trunc__", NULL);
Jeffrey Yasskinca2b69f2008-02-01 06:22:46 +00001138}
1139
1140PyDoc_STRVAR(math_trunc_doc,
1141"trunc(x:Real) -> Integral\n"
1142"\n"
Raymond Hettingerfe424f72008-02-02 05:24:44 +00001143"Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.");
Jeffrey Yasskinca2b69f2008-02-01 06:22:46 +00001144
1145static PyObject *
Neal Norwitz45e230a2006-11-19 21:26:53 +00001146math_frexp(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001147{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001148 int i;
1149 double x = PyFloat_AsDouble(arg);
1150 if (x == -1.0 && PyErr_Occurred())
1151 return NULL;
1152 /* deal with special cases directly, to sidestep platform
1153 differences */
1154 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
1155 i = 0;
1156 }
1157 else {
1158 PyFPE_START_PROTECT("in math_frexp", return 0);
1159 x = frexp(x, &i);
1160 PyFPE_END_PROTECT(x);
1161 }
1162 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001163}
1164
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001165PyDoc_STRVAR(math_frexp_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001166"frexp(x)\n"
1167"\n"
1168"Return the mantissa and exponent of x, as pair (m, e).\n"
1169"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 +00001170"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 +00001171
Barry Warsaw8b43b191996-12-09 22:32:36 +00001172static PyObject *
Fred Drake40c48682000-07-03 18:11:56 +00001173math_ldexp(PyObject *self, PyObject *args)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001174{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001175 double x, r;
1176 PyObject *oexp;
1177 long exp;
1178 int overflow;
1179 if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp))
1180 return NULL;
Mark Dickinsonf8476c12008-05-09 17:54:23 +00001181
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001182 if (PyLong_Check(oexp) || PyInt_Check(oexp)) {
1183 /* on overflow, replace exponent with either LONG_MAX
1184 or LONG_MIN, depending on the sign. */
1185 exp = PyLong_AsLongAndOverflow(oexp, &overflow);
1186 if (exp == -1 && PyErr_Occurred())
1187 return NULL;
1188 if (overflow)
1189 exp = overflow < 0 ? LONG_MIN : LONG_MAX;
1190 }
1191 else {
1192 PyErr_SetString(PyExc_TypeError,
1193 "Expected an int or long as second argument "
1194 "to ldexp.");
1195 return NULL;
1196 }
Mark Dickinsonf8476c12008-05-09 17:54:23 +00001197
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001198 if (x == 0. || !Py_IS_FINITE(x)) {
1199 /* NaNs, zeros and infinities are returned unchanged */
1200 r = x;
1201 errno = 0;
1202 } else if (exp > INT_MAX) {
1203 /* overflow */
1204 r = copysign(Py_HUGE_VAL, x);
1205 errno = ERANGE;
1206 } else if (exp < INT_MIN) {
1207 /* underflow to +-0 */
1208 r = copysign(0., x);
1209 errno = 0;
1210 } else {
1211 errno = 0;
1212 PyFPE_START_PROTECT("in math_ldexp", return 0);
1213 r = ldexp(x, (int)exp);
1214 PyFPE_END_PROTECT(r);
1215 if (Py_IS_INFINITY(r))
1216 errno = ERANGE;
1217 }
Mark Dickinsonf8476c12008-05-09 17:54:23 +00001218
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001219 if (errno && is_error(r))
1220 return NULL;
1221 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001222}
1223
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001224PyDoc_STRVAR(math_ldexp_doc,
Georg Brandla8f8bed22009-10-29 20:54:03 +00001225"ldexp(x, i)\n\n\
1226Return x * (2**i).");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001227
Barry Warsaw8b43b191996-12-09 22:32:36 +00001228static PyObject *
Neal Norwitz45e230a2006-11-19 21:26:53 +00001229math_modf(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001230{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001231 double y, x = PyFloat_AsDouble(arg);
1232 if (x == -1.0 && PyErr_Occurred())
1233 return NULL;
1234 /* some platforms don't do the right thing for NaNs and
1235 infinities, so we take care of special cases directly. */
1236 if (!Py_IS_FINITE(x)) {
1237 if (Py_IS_INFINITY(x))
1238 return Py_BuildValue("(dd)", copysign(0., x), x);
1239 else if (Py_IS_NAN(x))
1240 return Py_BuildValue("(dd)", x, x);
1241 }
Mark Dickinsonb2f70902008-04-20 01:39:24 +00001242
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001243 errno = 0;
1244 PyFPE_START_PROTECT("in math_modf", return 0);
1245 x = modf(x, &y);
1246 PyFPE_END_PROTECT(x);
1247 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001248}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001249
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001250PyDoc_STRVAR(math_modf_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001251"modf(x)\n"
1252"\n"
1253"Return the fractional and integer parts of x. Both results carry the sign\n"
Benjamin Peterson9de72982008-12-20 22:49:24 +00001254"of x and are floats.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001255
Tim Peters78526162001-09-05 00:53:45 +00001256/* A decent logarithm is easy to compute even for huge longs, but libm can't
1257 do that by itself -- loghelper can. func is log or log10, and name is
Mark Dickinsond3e32322010-01-02 14:45:40 +00001258 "log" or "log10". Note that overflow of the result isn't possible: a long
1259 can contain no more than INT_MAX * SHIFT bits, so has value certainly less
1260 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 +00001261 small enough to fit in an IEEE single. log and log10 are even smaller.
Mark Dickinsond3e32322010-01-02 14:45:40 +00001262 However, intermediate overflow is possible for a long if the number of bits
1263 in that long is larger than PY_SSIZE_T_MAX. */
Tim Peters78526162001-09-05 00:53:45 +00001264
1265static PyObject*
Neal Norwitz45e230a2006-11-19 21:26:53 +00001266loghelper(PyObject* arg, double (*func)(double), char *funcname)
Tim Peters78526162001-09-05 00:53:45 +00001267{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001268 /* If it is long, do it ourselves. */
1269 if (PyLong_Check(arg)) {
1270 double x;
1271 Py_ssize_t e;
1272 x = _PyLong_Frexp((PyLongObject *)arg, &e);
1273 if (x == -1.0 && PyErr_Occurred())
1274 return NULL;
1275 if (x <= 0.0) {
1276 PyErr_SetString(PyExc_ValueError,
1277 "math domain error");
1278 return NULL;
1279 }
1280 /* Special case for log(1), to make sure we get an
1281 exact result there. */
1282 if (e == 1 && x == 0.5)
1283 return PyFloat_FromDouble(0.0);
1284 /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */
1285 x = func(x) + func(2.0) * e;
1286 return PyFloat_FromDouble(x);
1287 }
Tim Peters78526162001-09-05 00:53:45 +00001288
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001289 /* Else let libm handle it by itself. */
1290 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +00001291}
1292
1293static PyObject *
1294math_log(PyObject *self, PyObject *args)
1295{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001296 PyObject *arg;
1297 PyObject *base = NULL;
1298 PyObject *num, *den;
1299 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001300
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001301 if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base))
1302 return NULL;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001303
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001304 num = loghelper(arg, m_log, "log");
1305 if (num == NULL || base == NULL)
1306 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001307
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001308 den = loghelper(base, m_log, "log");
1309 if (den == NULL) {
1310 Py_DECREF(num);
1311 return NULL;
1312 }
Raymond Hettinger866964c2002-12-14 19:51:34 +00001313
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001314 ans = PyNumber_Divide(num, den);
1315 Py_DECREF(num);
1316 Py_DECREF(den);
1317 return ans;
Tim Peters78526162001-09-05 00:53:45 +00001318}
1319
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001320PyDoc_STRVAR(math_log_doc,
Georg Brandla8f8bed22009-10-29 20:54:03 +00001321"log(x[, base])\n\n\
1322Return the logarithm of x to the given base.\n\
Raymond Hettinger866964c2002-12-14 19:51:34 +00001323If the base not specified, returns the natural logarithm (base e) of x.");
Tim Peters78526162001-09-05 00:53:45 +00001324
1325static PyObject *
Neal Norwitz45e230a2006-11-19 21:26:53 +00001326math_log10(PyObject *self, PyObject *arg)
Tim Peters78526162001-09-05 00:53:45 +00001327{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001328 return loghelper(arg, m_log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +00001329}
1330
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001331PyDoc_STRVAR(math_log10_doc,
Georg Brandla8f8bed22009-10-29 20:54:03 +00001332"log10(x)\n\nReturn the base 10 logarithm of x.");
Tim Peters78526162001-09-05 00:53:45 +00001333
Christian Heimes6f341092008-04-18 23:13:07 +00001334static PyObject *
1335math_fmod(PyObject *self, PyObject *args)
1336{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001337 PyObject *ox, *oy;
1338 double r, x, y;
1339 if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy))
1340 return NULL;
1341 x = PyFloat_AsDouble(ox);
1342 y = PyFloat_AsDouble(oy);
1343 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1344 return NULL;
1345 /* fmod(x, +/-Inf) returns x for finite x. */
1346 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
1347 return PyFloat_FromDouble(x);
1348 errno = 0;
1349 PyFPE_START_PROTECT("in math_fmod", return 0);
1350 r = fmod(x, y);
1351 PyFPE_END_PROTECT(r);
1352 if (Py_IS_NAN(r)) {
1353 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1354 errno = EDOM;
1355 else
1356 errno = 0;
1357 }
1358 if (errno && is_error(r))
1359 return NULL;
1360 else
1361 return PyFloat_FromDouble(r);
Christian Heimes6f341092008-04-18 23:13:07 +00001362}
1363
1364PyDoc_STRVAR(math_fmod_doc,
Georg Brandla8f8bed22009-10-29 20:54:03 +00001365"fmod(x, y)\n\nReturn fmod(x, y), according to platform C."
Christian Heimes6f341092008-04-18 23:13:07 +00001366" x % y may differ.");
1367
1368static PyObject *
1369math_hypot(PyObject *self, PyObject *args)
1370{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001371 PyObject *ox, *oy;
1372 double r, x, y;
1373 if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy))
1374 return NULL;
1375 x = PyFloat_AsDouble(ox);
1376 y = PyFloat_AsDouble(oy);
1377 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1378 return NULL;
1379 /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */
1380 if (Py_IS_INFINITY(x))
1381 return PyFloat_FromDouble(fabs(x));
1382 if (Py_IS_INFINITY(y))
1383 return PyFloat_FromDouble(fabs(y));
1384 errno = 0;
1385 PyFPE_START_PROTECT("in math_hypot", return 0);
1386 r = hypot(x, y);
1387 PyFPE_END_PROTECT(r);
1388 if (Py_IS_NAN(r)) {
1389 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1390 errno = EDOM;
1391 else
1392 errno = 0;
1393 }
1394 else if (Py_IS_INFINITY(r)) {
1395 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
1396 errno = ERANGE;
1397 else
1398 errno = 0;
1399 }
1400 if (errno && is_error(r))
1401 return NULL;
1402 else
1403 return PyFloat_FromDouble(r);
Christian Heimes6f341092008-04-18 23:13:07 +00001404}
1405
1406PyDoc_STRVAR(math_hypot_doc,
Georg Brandla8f8bed22009-10-29 20:54:03 +00001407"hypot(x, y)\n\nReturn the Euclidean distance, sqrt(x*x + y*y).");
Christian Heimes6f341092008-04-18 23:13:07 +00001408
1409/* pow can't use math_2, but needs its own wrapper: the problem is
1410 that an infinite result can arise either as a result of overflow
1411 (in which case OverflowError should be raised) or as a result of
1412 e.g. 0.**-5. (for which ValueError needs to be raised.)
1413*/
1414
1415static PyObject *
1416math_pow(PyObject *self, PyObject *args)
1417{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001418 PyObject *ox, *oy;
1419 double r, x, y;
1420 int odd_y;
Christian Heimes6f341092008-04-18 23:13:07 +00001421
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001422 if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy))
1423 return NULL;
1424 x = PyFloat_AsDouble(ox);
1425 y = PyFloat_AsDouble(oy);
1426 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1427 return NULL;
Mark Dickinsona1293eb2008-04-19 19:41:52 +00001428
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001429 /* deal directly with IEEE specials, to cope with problems on various
1430 platforms whose semantics don't exactly match C99 */
1431 r = 0.; /* silence compiler warning */
1432 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
1433 errno = 0;
1434 if (Py_IS_NAN(x))
1435 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
1436 else if (Py_IS_NAN(y))
1437 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
1438 else if (Py_IS_INFINITY(x)) {
1439 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
1440 if (y > 0.)
1441 r = odd_y ? x : fabs(x);
1442 else if (y == 0.)
1443 r = 1.;
1444 else /* y < 0. */
1445 r = odd_y ? copysign(0., x) : 0.;
1446 }
1447 else if (Py_IS_INFINITY(y)) {
1448 if (fabs(x) == 1.0)
1449 r = 1.;
1450 else if (y > 0. && fabs(x) > 1.0)
1451 r = y;
1452 else if (y < 0. && fabs(x) < 1.0) {
1453 r = -y; /* result is +inf */
1454 if (x == 0.) /* 0**-inf: divide-by-zero */
1455 errno = EDOM;
1456 }
1457 else
1458 r = 0.;
1459 }
1460 }
1461 else {
1462 /* let libm handle finite**finite */
1463 errno = 0;
1464 PyFPE_START_PROTECT("in math_pow", return 0);
1465 r = pow(x, y);
1466 PyFPE_END_PROTECT(r);
1467 /* a NaN result should arise only from (-ve)**(finite
1468 non-integer); in this case we want to raise ValueError. */
1469 if (!Py_IS_FINITE(r)) {
1470 if (Py_IS_NAN(r)) {
1471 errno = EDOM;
1472 }
1473 /*
1474 an infinite result here arises either from:
1475 (A) (+/-0.)**negative (-> divide-by-zero)
1476 (B) overflow of x**y with x and y finite
1477 */
1478 else if (Py_IS_INFINITY(r)) {
1479 if (x == 0.)
1480 errno = EDOM;
1481 else
1482 errno = ERANGE;
1483 }
1484 }
1485 }
Christian Heimes6f341092008-04-18 23:13:07 +00001486
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001487 if (errno && is_error(r))
1488 return NULL;
1489 else
1490 return PyFloat_FromDouble(r);
Christian Heimes6f341092008-04-18 23:13:07 +00001491}
1492
1493PyDoc_STRVAR(math_pow_doc,
Georg Brandla8f8bed22009-10-29 20:54:03 +00001494"pow(x, y)\n\nReturn x**y (x to the power of y).");
Christian Heimes6f341092008-04-18 23:13:07 +00001495
Christian Heimese2ca4242008-01-03 20:23:15 +00001496static const double degToRad = Py_MATH_PI / 180.0;
1497static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001498
1499static PyObject *
Neal Norwitz45e230a2006-11-19 21:26:53 +00001500math_degrees(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001501{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001502 double x = PyFloat_AsDouble(arg);
1503 if (x == -1.0 && PyErr_Occurred())
1504 return NULL;
1505 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001506}
1507
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001508PyDoc_STRVAR(math_degrees_doc,
Georg Brandla8f8bed22009-10-29 20:54:03 +00001509"degrees(x)\n\n\
1510Convert angle x from radians to degrees.");
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001511
1512static PyObject *
Neal Norwitz45e230a2006-11-19 21:26:53 +00001513math_radians(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001514{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001515 double x = PyFloat_AsDouble(arg);
1516 if (x == -1.0 && PyErr_Occurred())
1517 return NULL;
1518 return PyFloat_FromDouble(x * degToRad);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001519}
1520
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001521PyDoc_STRVAR(math_radians_doc,
Georg Brandla8f8bed22009-10-29 20:54:03 +00001522"radians(x)\n\n\
1523Convert angle x from degrees to radians.");
Tim Peters78526162001-09-05 00:53:45 +00001524
Christian Heimese2ca4242008-01-03 20:23:15 +00001525static PyObject *
1526math_isnan(PyObject *self, PyObject *arg)
1527{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001528 double x = PyFloat_AsDouble(arg);
1529 if (x == -1.0 && PyErr_Occurred())
1530 return NULL;
1531 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimese2ca4242008-01-03 20:23:15 +00001532}
1533
1534PyDoc_STRVAR(math_isnan_doc,
Georg Brandla8f8bed22009-10-29 20:54:03 +00001535"isnan(x) -> bool\n\n\
1536Check if float x is not a number (NaN).");
Christian Heimese2ca4242008-01-03 20:23:15 +00001537
1538static PyObject *
1539math_isinf(PyObject *self, PyObject *arg)
1540{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001541 double x = PyFloat_AsDouble(arg);
1542 if (x == -1.0 && PyErr_Occurred())
1543 return NULL;
1544 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimese2ca4242008-01-03 20:23:15 +00001545}
1546
1547PyDoc_STRVAR(math_isinf_doc,
Georg Brandla8f8bed22009-10-29 20:54:03 +00001548"isinf(x) -> bool\n\n\
1549Check if float x is infinite (positive or negative).");
Christian Heimese2ca4242008-01-03 20:23:15 +00001550
Barry Warsaw8b43b191996-12-09 22:32:36 +00001551static PyMethodDef math_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001552 {"acos", math_acos, METH_O, math_acos_doc},
1553 {"acosh", math_acosh, METH_O, math_acosh_doc},
1554 {"asin", math_asin, METH_O, math_asin_doc},
1555 {"asinh", math_asinh, METH_O, math_asinh_doc},
1556 {"atan", math_atan, METH_O, math_atan_doc},
1557 {"atan2", math_atan2, METH_VARARGS, math_atan2_doc},
1558 {"atanh", math_atanh, METH_O, math_atanh_doc},
1559 {"ceil", math_ceil, METH_O, math_ceil_doc},
1560 {"copysign", math_copysign, METH_VARARGS, math_copysign_doc},
1561 {"cos", math_cos, METH_O, math_cos_doc},
1562 {"cosh", math_cosh, METH_O, math_cosh_doc},
1563 {"degrees", math_degrees, METH_O, math_degrees_doc},
1564 {"erf", math_erf, METH_O, math_erf_doc},
1565 {"erfc", math_erfc, METH_O, math_erfc_doc},
1566 {"exp", math_exp, METH_O, math_exp_doc},
1567 {"expm1", math_expm1, METH_O, math_expm1_doc},
1568 {"fabs", math_fabs, METH_O, math_fabs_doc},
1569 {"factorial", math_factorial, METH_O, math_factorial_doc},
1570 {"floor", math_floor, METH_O, math_floor_doc},
1571 {"fmod", math_fmod, METH_VARARGS, math_fmod_doc},
1572 {"frexp", math_frexp, METH_O, math_frexp_doc},
1573 {"fsum", math_fsum, METH_O, math_fsum_doc},
1574 {"gamma", math_gamma, METH_O, math_gamma_doc},
1575 {"hypot", math_hypot, METH_VARARGS, math_hypot_doc},
1576 {"isinf", math_isinf, METH_O, math_isinf_doc},
1577 {"isnan", math_isnan, METH_O, math_isnan_doc},
1578 {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc},
1579 {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
1580 {"log", math_log, METH_VARARGS, math_log_doc},
1581 {"log1p", math_log1p, METH_O, math_log1p_doc},
1582 {"log10", math_log10, METH_O, math_log10_doc},
1583 {"modf", math_modf, METH_O, math_modf_doc},
1584 {"pow", math_pow, METH_VARARGS, math_pow_doc},
1585 {"radians", math_radians, METH_O, math_radians_doc},
1586 {"sin", math_sin, METH_O, math_sin_doc},
1587 {"sinh", math_sinh, METH_O, math_sinh_doc},
1588 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
1589 {"tan", math_tan, METH_O, math_tan_doc},
1590 {"tanh", math_tanh, METH_O, math_tanh_doc},
1591 {"trunc", math_trunc, METH_O, math_trunc_doc},
1592 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001593};
1594
Guido van Rossumc6e22901998-12-04 19:26:43 +00001595
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001596PyDoc_STRVAR(module_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001597"This module is always available. It provides access to the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001598"mathematical functions defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001599
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001600PyMODINIT_FUNC
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001601initmath(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001602{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001603 PyObject *m;
Tim Petersfe71f812001-08-07 22:10:00 +00001604
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001605 m = Py_InitModule3("math", math_methods, module_doc);
1606 if (m == NULL)
1607 goto finally;
Barry Warsawfc93f751996-12-17 00:47:03 +00001608
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001609 PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
1610 PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
Barry Warsawfc93f751996-12-17 00:47:03 +00001611
Christian Heimes6f341092008-04-18 23:13:07 +00001612 finally:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001613 return;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001614}