blob: 5dedf0409a554c95147abdb38bd8085b29a59f51 [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"
Michael W. Hudson9ef852c2005-04-06 13:05:18 +000057#include "longintrepr.h" /* just for SHIFT */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000058
Neal Norwitz5f95a792008-01-25 08:04:16 +000059#ifdef _OSF_SOURCE
60/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
61extern double copysign(double, double);
62#endif
63
Mark Dickinsonb93fff02009-09-28 18:54:55 +000064/*
65 sin(pi*x), giving accurate results for all finite x (especially x
66 integral or close to an integer). This is here for use in the
67 reflection formula for the gamma function. It conforms to IEEE
68 754-2008 for finite arguments, but not for infinities or nans.
69*/
Tim Petersa40c7932001-09-05 22:36:56 +000070
Mark Dickinsonb93fff02009-09-28 18:54:55 +000071static const double pi = 3.141592653589793238462643383279502884197;
Mark Dickinson5ff37ae2009-12-19 11:07:23 +000072static const double sqrtpi = 1.772453850905516027298167483341145182798;
Mark Dickinsonb93fff02009-09-28 18:54:55 +000073
74static double
75sinpi(double x)
76{
77 double y, r;
78 int n;
79 /* this function should only ever be called for finite arguments */
80 assert(Py_IS_FINITE(x));
81 y = fmod(fabs(x), 2.0);
82 n = (int)round(2.0*y);
83 assert(0 <= n && n <= 4);
84 switch (n) {
85 case 0:
86 r = sin(pi*y);
87 break;
88 case 1:
89 r = cos(pi*(y-0.5));
90 break;
91 case 2:
92 /* N.B. -sin(pi*(y-1.0)) is *not* equivalent: it would give
93 -0.0 instead of 0.0 when y == 1.0. */
94 r = sin(pi*(1.0-y));
95 break;
96 case 3:
97 r = -cos(pi*(y-1.5));
98 break;
99 case 4:
100 r = sin(pi*(y-2.0));
101 break;
102 default:
103 assert(0); /* should never get here */
104 r = -1.23e200; /* silence gcc warning */
Tim Peters1d120612000-10-12 06:10:25 +0000105 }
Mark Dickinsonb93fff02009-09-28 18:54:55 +0000106 return copysign(1.0, x)*r;
107}
108
109/* Implementation of the real gamma function. In extensive but non-exhaustive
110 random tests, this function proved accurate to within <= 10 ulps across the
111 entire float domain. Note that accuracy may depend on the quality of the
112 system math functions, the pow function in particular. Special cases
113 follow C99 annex F. The parameters and method are tailored to platforms
114 whose double format is the IEEE 754 binary64 format.
115
116 Method: for x > 0.0 we use the Lanczos approximation with parameters N=13
117 and g=6.024680040776729583740234375; these parameters are amongst those
118 used by the Boost library. Following Boost (again), we re-express the
119 Lanczos sum as a rational function, and compute it that way. The
120 coefficients below were computed independently using MPFR, and have been
121 double-checked against the coefficients in the Boost source code.
122
123 For x < 0.0 we use the reflection formula.
124
125 There's one minor tweak that deserves explanation: Lanczos' formula for
126 Gamma(x) involves computing pow(x+g-0.5, x-0.5) / exp(x+g-0.5). For many x
127 values, x+g-0.5 can be represented exactly. However, in cases where it
128 can't be represented exactly the small error in x+g-0.5 can be magnified
129 significantly by the pow and exp calls, especially for large x. A cheap
130 correction is to multiply by (1 + e*g/(x+g-0.5)), where e is the error
131 involved in the computation of x+g-0.5 (that is, e = computed value of
132 x+g-0.5 - exact value of x+g-0.5). Here's the proof:
133
134 Correction factor
135 -----------------
136 Write x+g-0.5 = y-e, where y is exactly representable as an IEEE 754
137 double, and e is tiny. Then:
138
139 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) = pow(y-e, x-0.5)/exp(y-e)
140 = pow(y, x-0.5)/exp(y) * C,
141
142 where the correction_factor C is given by
143
144 C = pow(1-e/y, x-0.5) * exp(e)
145
146 Since e is tiny, pow(1-e/y, x-0.5) ~ 1-(x-0.5)*e/y, and exp(x) ~ 1+e, so:
147
148 C ~ (1-(x-0.5)*e/y) * (1+e) ~ 1 + e*(y-(x-0.5))/y
149
150 But y-(x-0.5) = g+e, and g+e ~ g. So we get C ~ 1 + e*g/y, and
151
152 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) ~ pow(y, x-0.5)/exp(y) * (1 + e*g/y),
153
154 Note that for accuracy, when computing r*C it's better to do
155
156 r + e*g/y*r;
157
158 than
159
160 r * (1 + e*g/y);
161
162 since the addition in the latter throws away most of the bits of
163 information in e*g/y.
164*/
165
166#define LANCZOS_N 13
167static const double lanczos_g = 6.024680040776729583740234375;
168static const double lanczos_g_minus_half = 5.524680040776729583740234375;
169static const double lanczos_num_coeffs[LANCZOS_N] = {
170 23531376880.410759688572007674451636754734846804940,
171 42919803642.649098768957899047001988850926355848959,
172 35711959237.355668049440185451547166705960488635843,
173 17921034426.037209699919755754458931112671403265390,
174 6039542586.3520280050642916443072979210699388420708,
175 1439720407.3117216736632230727949123939715485786772,
176 248874557.86205415651146038641322942321632125127801,
177 31426415.585400194380614231628318205362874684987640,
178 2876370.6289353724412254090516208496135991145378768,
179 186056.26539522349504029498971604569928220784236328,
180 8071.6720023658162106380029022722506138218516325024,
181 210.82427775157934587250973392071336271166969580291,
182 2.5066282746310002701649081771338373386264310793408
183};
184
185/* denominator is x*(x+1)*...*(x+LANCZOS_N-2) */
186static const double lanczos_den_coeffs[LANCZOS_N] = {
187 0.0, 39916800.0, 120543840.0, 150917976.0, 105258076.0, 45995730.0,
188 13339535.0, 2637558.0, 357423.0, 32670.0, 1925.0, 66.0, 1.0};
189
190/* gamma values for small positive integers, 1 though NGAMMA_INTEGRAL */
191#define NGAMMA_INTEGRAL 23
192static const double gamma_integral[NGAMMA_INTEGRAL] = {
193 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0,
194 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0,
195 1307674368000.0, 20922789888000.0, 355687428096000.0,
196 6402373705728000.0, 121645100408832000.0, 2432902008176640000.0,
197 51090942171709440000.0, 1124000727777607680000.0,
198};
199
200/* Lanczos' sum L_g(x), for positive x */
201
202static double
203lanczos_sum(double x)
204{
205 double num = 0.0, den = 0.0;
206 int i;
207 assert(x > 0.0);
208 /* evaluate the rational function lanczos_sum(x). For large
209 x, the obvious algorithm risks overflow, so we instead
210 rescale the denominator and numerator of the rational
211 function by x**(1-LANCZOS_N) and treat this as a
212 rational function in 1/x. This also reduces the error for
213 larger x values. The choice of cutoff point (5.0 below) is
214 somewhat arbitrary; in tests, smaller cutoff values than
215 this resulted in lower accuracy. */
216 if (x < 5.0) {
217 for (i = LANCZOS_N; --i >= 0; ) {
218 num = num * x + lanczos_num_coeffs[i];
219 den = den * x + lanczos_den_coeffs[i];
220 }
221 }
222 else {
223 for (i = 0; i < LANCZOS_N; i++) {
224 num = num / x + lanczos_num_coeffs[i];
225 den = den / x + lanczos_den_coeffs[i];
226 }
227 }
228 return num/den;
229}
230
231static double
232m_tgamma(double x)
233{
234 double absx, r, y, z, sqrtpow;
235
236 /* special cases */
237 if (!Py_IS_FINITE(x)) {
238 if (Py_IS_NAN(x) || x > 0.0)
239 return x; /* tgamma(nan) = nan, tgamma(inf) = inf */
240 else {
241 errno = EDOM;
242 return Py_NAN; /* tgamma(-inf) = nan, invalid */
243 }
244 }
245 if (x == 0.0) {
246 errno = EDOM;
247 return 1.0/x; /* tgamma(+-0.0) = +-inf, divide-by-zero */
248 }
249
250 /* integer arguments */
251 if (x == floor(x)) {
252 if (x < 0.0) {
253 errno = EDOM; /* tgamma(n) = nan, invalid for */
254 return Py_NAN; /* negative integers n */
255 }
256 if (x <= NGAMMA_INTEGRAL)
257 return gamma_integral[(int)x - 1];
258 }
259 absx = fabs(x);
260
261 /* tiny arguments: tgamma(x) ~ 1/x for x near 0 */
262 if (absx < 1e-20) {
263 r = 1.0/x;
264 if (Py_IS_INFINITY(r))
265 errno = ERANGE;
266 return r;
267 }
268
269 /* large arguments: assuming IEEE 754 doubles, tgamma(x) overflows for
270 x > 200, and underflows to +-0.0 for x < -200, not a negative
271 integer. */
272 if (absx > 200.0) {
273 if (x < 0.0) {
274 return 0.0/sinpi(x);
275 }
276 else {
277 errno = ERANGE;
278 return Py_HUGE_VAL;
279 }
280 }
281
282 y = absx + lanczos_g_minus_half;
283 /* compute error in sum */
284 if (absx > lanczos_g_minus_half) {
285 /* note: the correction can be foiled by an optimizing
286 compiler that (incorrectly) thinks that an expression like
287 a + b - a - b can be optimized to 0.0. This shouldn't
288 happen in a standards-conforming compiler. */
289 double q = y - absx;
290 z = q - lanczos_g_minus_half;
291 }
292 else {
293 double q = y - lanczos_g_minus_half;
294 z = q - absx;
295 }
296 z = z * lanczos_g / y;
297 if (x < 0.0) {
298 r = -pi / sinpi(absx) / absx * exp(y) / lanczos_sum(absx);
299 r -= z * r;
300 if (absx < 140.0) {
301 r /= pow(y, absx - 0.5);
302 }
303 else {
304 sqrtpow = pow(y, absx / 2.0 - 0.25);
305 r /= sqrtpow;
306 r /= sqrtpow;
307 }
308 }
309 else {
310 r = lanczos_sum(absx) / exp(y);
311 r += z * r;
312 if (absx < 140.0) {
313 r *= pow(y, absx - 0.5);
314 }
315 else {
316 sqrtpow = pow(y, absx / 2.0 - 0.25);
317 r *= sqrtpow;
318 r *= sqrtpow;
319 }
320 }
321 if (Py_IS_INFINITY(r))
322 errno = ERANGE;
323 return r;
Guido van Rossum8832b621991-12-16 15:44:24 +0000324}
325
Christian Heimes6f341092008-04-18 23:13:07 +0000326/*
Mark Dickinson9be87bc2009-12-11 17:29:33 +0000327 lgamma: natural log of the absolute value of the Gamma function.
328 For large arguments, Lanczos' formula works extremely well here.
329*/
330
331static double
332m_lgamma(double x)
333{
334 double r, absx;
335
336 /* special cases */
337 if (!Py_IS_FINITE(x)) {
338 if (Py_IS_NAN(x))
339 return x; /* lgamma(nan) = nan */
340 else
341 return Py_HUGE_VAL; /* lgamma(+-inf) = +inf */
342 }
343
344 /* integer arguments */
345 if (x == floor(x) && x <= 2.0) {
346 if (x <= 0.0) {
347 errno = EDOM; /* lgamma(n) = inf, divide-by-zero for */
348 return Py_HUGE_VAL; /* integers n <= 0 */
349 }
350 else {
351 return 0.0; /* lgamma(1) = lgamma(2) = 0.0 */
352 }
353 }
354
355 absx = fabs(x);
356 /* tiny arguments: lgamma(x) ~ -log(fabs(x)) for small x */
357 if (absx < 1e-20)
358 return -log(absx);
359
360 /* Lanczos' formula */
361 if (x > 0.0) {
362 /* we could save a fraction of a ulp in accuracy by having a
363 second set of numerator coefficients for lanczos_sum that
364 absorbed the exp(-lanczos_g) term, and throwing out the
365 lanczos_g subtraction below; it's probably not worth it. */
366 r = log(lanczos_sum(x)) - lanczos_g +
367 (x-0.5)*(log(x+lanczos_g-0.5)-1);
368 }
369 else {
370 r = log(pi) - log(fabs(sinpi(absx))) - log(absx) -
371 (log(lanczos_sum(absx)) - lanczos_g +
372 (absx-0.5)*(log(absx+lanczos_g-0.5)-1));
373 }
374 if (Py_IS_INFINITY(r))
375 errno = ERANGE;
376 return r;
377}
378
Mark Dickinson5ff37ae2009-12-19 11:07:23 +0000379/*
380 Implementations of the error function erf(x) and the complementary error
381 function erfc(x).
382
383 Method: following 'Numerical Recipes' by Flannery, Press et. al. (2nd ed.,
384 Cambridge University Press), we use a series approximation for erf for
385 small x, and a continued fraction approximation for erfc(x) for larger x;
386 combined with the relations erf(-x) = -erf(x) and erfc(x) = 1.0 - erf(x),
387 this gives us erf(x) and erfc(x) for all x.
388
389 The series expansion used is:
390
391 erf(x) = x*exp(-x*x)/sqrt(pi) * [
392 2/1 + 4/3 x**2 + 8/15 x**4 + 16/105 x**6 + ...]
393
394 The coefficient of x**(2k-2) here is 4**k*factorial(k)/factorial(2*k).
395 This series converges well for smallish x, but slowly for larger x.
396
397 The continued fraction expansion used is:
398
399 erfc(x) = x*exp(-x*x)/sqrt(pi) * [1/(0.5 + x**2 -) 0.5/(2.5 + x**2 - )
400 3.0/(4.5 + x**2 - ) 7.5/(6.5 + x**2 - ) ...]
401
402 after the first term, the general term has the form:
403
404 k*(k-0.5)/(2*k+0.5 + x**2 - ...).
405
406 This expansion converges fast for larger x, but convergence becomes
407 infinitely slow as x approaches 0.0. The (somewhat naive) continued
408 fraction evaluation algorithm used below also risks overflow for large x;
409 but for large x, erfc(x) == 0.0 to within machine precision. (For
410 example, erfc(30.0) is approximately 2.56e-393).
411
412 Parameters: use series expansion for abs(x) < ERF_SERIES_CUTOFF and
413 continued fraction expansion for ERF_SERIES_CUTOFF <= abs(x) <
414 ERFC_CONTFRAC_CUTOFF. ERFC_SERIES_TERMS and ERFC_CONTFRAC_TERMS are the
415 numbers of terms to use for the relevant expansions. */
416
417#define ERF_SERIES_CUTOFF 1.5
418#define ERF_SERIES_TERMS 25
419#define ERFC_CONTFRAC_CUTOFF 30.0
420#define ERFC_CONTFRAC_TERMS 50
421
422/*
423 Error function, via power series.
424
425 Given a finite float x, return an approximation to erf(x).
426 Converges reasonably fast for small x.
427*/
428
429static double
430m_erf_series(double x)
431{
432 double x2, acc, fk;
433 int i;
434
435 x2 = x * x;
436 acc = 0.0;
437 fk = (double)ERF_SERIES_TERMS + 0.5;
438 for (i = 0; i < ERF_SERIES_TERMS; i++) {
439 acc = 2.0 + x2 * acc / fk;
440 fk -= 1.0;
441 }
442 return acc * x * exp(-x2) / sqrtpi;
443}
444
445/*
446 Complementary error function, via continued fraction expansion.
447
448 Given a positive float x, return an approximation to erfc(x). Converges
449 reasonably fast for x large (say, x > 2.0), and should be safe from
450 overflow if x and nterms are not too large. On an IEEE 754 machine, with x
451 <= 30.0, we're safe up to nterms = 100. For x >= 30.0, erfc(x) is smaller
452 than the smallest representable nonzero float. */
453
454static double
455m_erfc_contfrac(double x)
456{
457 double x2, a, da, p, p_last, q, q_last, b;
458 int i;
459
460 if (x >= ERFC_CONTFRAC_CUTOFF)
461 return 0.0;
462
463 x2 = x*x;
464 a = 0.0;
465 da = 0.5;
466 p = 1.0; p_last = 0.0;
467 q = da + x2; q_last = 1.0;
468 for (i = 0; i < ERFC_CONTFRAC_TERMS; i++) {
469 double temp;
470 a += da;
471 da += 2.0;
472 b = da + x2;
473 temp = p; p = b*p - a*p_last; p_last = temp;
474 temp = q; q = b*q - a*q_last; q_last = temp;
475 }
476 return p / q * x * exp(-x2) / sqrtpi;
477}
478
479/* Error function erf(x), for general x */
480
481static double
482m_erf(double x)
483{
484 double absx, cf;
485
486 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 }
495}
496
497/* Complementary error function erfc(x), for general x. */
498
499static double
500m_erfc(double x)
501{
502 double absx, cf;
503
504 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 }
513}
Mark Dickinson9be87bc2009-12-11 17:29:33 +0000514
515/*
Mark Dickinson92483cd2008-04-20 21:39:04 +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{
526 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);
549}
550
551/*
Mark Dickinson4c96fa52008-12-11 19:28:08 +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{
561 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 }
578}
579
580static double
581m_log10(double x)
582{
583 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 }
600}
601
602
Mark Dickinsonb93fff02009-09-28 18:54:55 +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{
610 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");
614
615 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;
641}
642
Mark Dickinson4c96fa52008-12-11 19:28:08 +0000643/*
Christian Heimes6f341092008-04-18 23:13:07 +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 *
Christian Heimes6f341092008-04-18 23:13:07 +0000674math_1(PyObject *arg, double (*func) (double), int can_overflow)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000675{
Christian Heimes6f341092008-04-18 23:13:07 +0000676 double x, r;
677 x = PyFloat_AsDouble(arg);
Neal Norwitz45e230a2006-11-19 21:26:53 +0000678 if (x == -1.0 && PyErr_Occurred())
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000679 return NULL;
680 errno = 0;
Christian Heimes6f341092008-04-18 23:13:07 +0000681 PyFPE_START_PROTECT("in math_1", return 0);
682 r = (*func)(x);
683 PyFPE_END_PROTECT(r);
684 if (Py_IS_NAN(r)) {
685 if (!Py_IS_NAN(x))
686 errno = EDOM;
687 else
688 errno = 0;
689 }
690 else if (Py_IS_INFINITY(r)) {
691 if (Py_IS_FINITE(x))
692 errno = can_overflow ? ERANGE : EDOM;
693 else
694 errno = 0;
695 }
696 if (errno && is_error(r))
Tim Peters1d120612000-10-12 06:10:25 +0000697 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000698 else
Christian Heimes6f341092008-04-18 23:13:07 +0000699 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000700}
701
Mark Dickinsonb93fff02009-09-28 18:54:55 +0000702/* variant of math_1, to be used when the function being wrapped is known to
703 set errno properly (that is, errno = EDOM for invalid or divide-by-zero,
704 errno = ERANGE for overflow). */
705
706static PyObject *
707math_1a(PyObject *arg, double (*func) (double))
708{
709 double x, r;
710 x = PyFloat_AsDouble(arg);
711 if (x == -1.0 && PyErr_Occurred())
712 return NULL;
713 errno = 0;
714 PyFPE_START_PROTECT("in math_1a", return 0);
715 r = (*func)(x);
716 PyFPE_END_PROTECT(r);
717 if (errno && is_error(r))
718 return NULL;
719 return PyFloat_FromDouble(r);
720}
721
Christian Heimes6f341092008-04-18 23:13:07 +0000722/*
723 math_2 is used to wrap a libm function f that takes two double
724 arguments and returns a double.
725
726 The error reporting follows these rules, which are designed to do
727 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
728 platforms.
729
730 - a NaN result from non-NaN inputs causes ValueError to be raised
731 - an infinite result from finite inputs causes OverflowError to be
732 raised.
733 - if the result is finite and errno == EDOM then ValueError is
734 raised
735 - if the result is finite and nonzero and errno == ERANGE then
736 OverflowError is raised
737
738 The last rule is used to catch overflow on platforms which follow
739 C89 but for which HUGE_VAL is not an infinity.
740
741 For most two-argument functions (copysign, fmod, hypot, atan2)
742 these rules are enough to ensure that Python's functions behave as
743 specified in 'Annex F' of the C99 standard, with the 'invalid' and
744 'divide-by-zero' floating-point exceptions mapping to Python's
745 ValueError and the 'overflow' floating-point exception mapping to
746 OverflowError.
747*/
748
Barry Warsaw8b43b191996-12-09 22:32:36 +0000749static PyObject *
Neal Norwitz45e230a2006-11-19 21:26:53 +0000750math_2(PyObject *args, double (*func) (double, double), char *funcname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000751{
Neal Norwitz45e230a2006-11-19 21:26:53 +0000752 PyObject *ox, *oy;
Christian Heimes6f341092008-04-18 23:13:07 +0000753 double x, y, r;
Neal Norwitz45e230a2006-11-19 21:26:53 +0000754 if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy))
755 return NULL;
756 x = PyFloat_AsDouble(ox);
757 y = PyFloat_AsDouble(oy);
758 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000759 return NULL;
760 errno = 0;
Christian Heimes6f341092008-04-18 23:13:07 +0000761 PyFPE_START_PROTECT("in math_2", return 0);
762 r = (*func)(x, y);
763 PyFPE_END_PROTECT(r);
764 if (Py_IS_NAN(r)) {
765 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
766 errno = EDOM;
767 else
768 errno = 0;
769 }
770 else if (Py_IS_INFINITY(r)) {
771 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
772 errno = ERANGE;
773 else
774 errno = 0;
775 }
776 if (errno && is_error(r))
Tim Peters1d120612000-10-12 06:10:25 +0000777 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000778 else
Christian Heimes6f341092008-04-18 23:13:07 +0000779 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000780}
781
Christian Heimes6f341092008-04-18 23:13:07 +0000782#define FUNC1(funcname, func, can_overflow, docstring) \
Fred Drake40c48682000-07-03 18:11:56 +0000783 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
Christian Heimes6f341092008-04-18 23:13:07 +0000784 return math_1(args, func, can_overflow); \
Guido van Rossumc6e22901998-12-04 19:26:43 +0000785 }\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000786 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000787
Mark Dickinsonb93fff02009-09-28 18:54:55 +0000788#define FUNC1A(funcname, func, docstring) \
789 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
790 return math_1a(args, func); \
791 }\
792 PyDoc_STRVAR(math_##funcname##_doc, docstring);
793
Fred Drake40c48682000-07-03 18:11:56 +0000794#define FUNC2(funcname, func, docstring) \
795 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
Neal Norwitz45e230a2006-11-19 21:26:53 +0000796 return math_2(args, func, #funcname); \
Guido van Rossumc6e22901998-12-04 19:26:43 +0000797 }\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000798 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000799
Christian Heimes6f341092008-04-18 23:13:07 +0000800FUNC1(acos, acos, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000801 "acos(x)\n\nReturn the arc cosine (measured in radians) of x.")
Christian Heimes6f341092008-04-18 23:13:07 +0000802FUNC1(acosh, acosh, 0,
803 "acosh(x)\n\nReturn the hyperbolic arc cosine (measured in radians) of x.")
804FUNC1(asin, asin, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000805 "asin(x)\n\nReturn the arc sine (measured in radians) of x.")
Christian Heimes6f341092008-04-18 23:13:07 +0000806FUNC1(asinh, asinh, 0,
807 "asinh(x)\n\nReturn the hyperbolic arc sine (measured in radians) of x.")
808FUNC1(atan, atan, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000809 "atan(x)\n\nReturn the arc tangent (measured in radians) of x.")
Mark Dickinson92483cd2008-04-20 21:39:04 +0000810FUNC2(atan2, m_atan2,
Tim Petersfe71f812001-08-07 22:10:00 +0000811 "atan2(y, x)\n\nReturn the arc tangent (measured in radians) of y/x.\n"
812 "Unlike atan(y/x), the signs of both x and y are considered.")
Christian Heimes6f341092008-04-18 23:13:07 +0000813FUNC1(atanh, atanh, 0,
814 "atanh(x)\n\nReturn the hyperbolic arc tangent (measured in radians) of x.")
815FUNC1(ceil, ceil, 0,
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +0000816 "ceil(x)\n\nReturn the ceiling of x as a float.\n"
817 "This is the smallest integral value >= x.")
Christian Heimeseebb79c2008-01-03 22:32:26 +0000818FUNC2(copysign, copysign,
Georg Brandla8f8bed22009-10-29 20:54:03 +0000819 "copysign(x, y)\n\nReturn x with the sign of y.")
Christian Heimes6f341092008-04-18 23:13:07 +0000820FUNC1(cos, cos, 0,
821 "cos(x)\n\nReturn the cosine of x (measured in radians).")
822FUNC1(cosh, cosh, 1,
823 "cosh(x)\n\nReturn the hyperbolic cosine of x.")
Mark Dickinson5ff37ae2009-12-19 11:07:23 +0000824FUNC1A(erf, m_erf,
825 "erf(x)\n\nError function at x.")
826FUNC1A(erfc, m_erfc,
827 "erfc(x)\n\nComplementary error function at x.")
Christian Heimes6f341092008-04-18 23:13:07 +0000828FUNC1(exp, exp, 1,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000829 "exp(x)\n\nReturn e raised to the power of x.")
Mark Dickinson9cae1782009-12-16 20:13:40 +0000830FUNC1(expm1, m_expm1, 1,
831 "expm1(x)\n\nReturn exp(x)-1.\n"
832 "This function avoids the loss of precision involved in the direct "
833 "evaluation of exp(x)-1 for small x.")
Christian Heimes6f341092008-04-18 23:13:07 +0000834FUNC1(fabs, fabs, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000835 "fabs(x)\n\nReturn the absolute value of the float x.")
Christian Heimes6f341092008-04-18 23:13:07 +0000836FUNC1(floor, floor, 0,
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +0000837 "floor(x)\n\nReturn the floor of x as a float.\n"
838 "This is the largest integral value <= x.")
Mark Dickinsonb93fff02009-09-28 18:54:55 +0000839FUNC1A(gamma, m_tgamma,
840 "gamma(x)\n\nGamma function at x.")
Mark Dickinson9be87bc2009-12-11 17:29:33 +0000841FUNC1A(lgamma, m_lgamma,
842 "lgamma(x)\n\nNatural logarithm of absolute value of Gamma function at x.")
Christian Heimes6f341092008-04-18 23:13:07 +0000843FUNC1(log1p, log1p, 1,
Georg Brandla8f8bed22009-10-29 20:54:03 +0000844 "log1p(x)\n\nReturn the natural logarithm of 1+x (base e).\n"
845 "The result is computed in a way which is accurate for x near zero.")
Christian Heimes6f341092008-04-18 23:13:07 +0000846FUNC1(sin, sin, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000847 "sin(x)\n\nReturn the sine of x (measured in radians).")
Christian Heimes6f341092008-04-18 23:13:07 +0000848FUNC1(sinh, sinh, 1,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000849 "sinh(x)\n\nReturn the hyperbolic sine of x.")
Christian Heimes6f341092008-04-18 23:13:07 +0000850FUNC1(sqrt, sqrt, 0,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000851 "sqrt(x)\n\nReturn the square root of x.")
Christian Heimes6f341092008-04-18 23:13:07 +0000852FUNC1(tan, tan, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000853 "tan(x)\n\nReturn the tangent of x (measured in radians).")
Christian Heimes6f341092008-04-18 23:13:07 +0000854FUNC1(tanh, tanh, 0,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000855 "tanh(x)\n\nReturn the hyperbolic tangent of x.")
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000856
Mark Dickinson99dfe922008-05-23 01:35:30 +0000857/* Precision summation function as msum() by Raymond Hettinger in
858 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
859 enhanced with the exact partials sum and roundoff from Mark
860 Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000861 See those links for more details, proofs and other references.
Mark Dickinson99dfe922008-05-23 01:35:30 +0000862
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000863 Note 1: IEEE 754R floating point semantics are assumed,
864 but the current implementation does not re-establish special
865 value semantics across iterations (i.e. handling -Inf + Inf).
Mark Dickinson99dfe922008-05-23 01:35:30 +0000866
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000867 Note 2: No provision is made for intermediate overflow handling;
Raymond Hettinger2a9179a2008-05-29 08:38:23 +0000868 therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000869 sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
870 overflow of the first partial sum.
Mark Dickinson99dfe922008-05-23 01:35:30 +0000871
Andrew M. Kuchling5f198be2008-06-20 02:11:42 +0000872 Note 3: The intermediate values lo, yr, and hi are declared volatile so
Mark Dickinson2fcd8c92008-06-20 15:26:19 +0000873 aggressive compilers won't algebraically reduce lo to always be exactly 0.0.
Raymond Hettingerd6234142008-06-09 11:24:47 +0000874 Also, the volatile declaration forces the values to be stored in memory as
875 regular doubles instead of extended long precision (80-bit) values. This
Andrew M. Kuchling5f198be2008-06-20 02:11:42 +0000876 prevents double rounding because any addition or subtraction of two doubles
Raymond Hettingerd6234142008-06-09 11:24:47 +0000877 can be resolved exactly into double-sized hi and lo values. As long as the
878 hi value gets forced into a double before yr and lo are computed, the extra
879 bits in downstream extended precision operations (x87 for example) will be
880 exactly zero and therefore can be losslessly stored back into a double,
881 thereby preventing double rounding.
Mark Dickinson99dfe922008-05-23 01:35:30 +0000882
Raymond Hettingerd6234142008-06-09 11:24:47 +0000883 Note 4: A similar implementation is in Modules/cmathmodule.c.
884 Be sure to update both when making changes.
Mark Dickinson99dfe922008-05-23 01:35:30 +0000885
Mark Dickinsonff3fdce2008-07-30 16:25:16 +0000886 Note 5: The signature of math.fsum() differs from __builtin__.sum()
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000887 because the start argument doesn't make sense in the context of
888 accurate summation. Since the partials table is collapsed before
889 returning a result, sum(seq2, start=sum(seq1)) may not equal the
890 accurate result returned by sum(itertools.chain(seq1, seq2)).
Mark Dickinson99dfe922008-05-23 01:35:30 +0000891*/
892
893#define NUM_PARTIALS 32 /* initial partials array size, on stack */
894
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000895/* Extend the partials array p[] by doubling its size. */
896static int /* non-zero on error */
Mark Dickinsonfef6b132008-07-30 16:20:10 +0000897_fsum_realloc(double **p_ptr, Py_ssize_t n,
Raymond Hettingerd6234142008-06-09 11:24:47 +0000898 double *ps, Py_ssize_t *m_ptr)
Mark Dickinson99dfe922008-05-23 01:35:30 +0000899{
900 void *v = NULL;
901 Py_ssize_t m = *m_ptr;
902
Raymond Hettingerd6234142008-06-09 11:24:47 +0000903 m += m; /* double */
904 if (n < m && m < (PY_SSIZE_T_MAX / sizeof(double))) {
905 double *p = *p_ptr;
Mark Dickinson99dfe922008-05-23 01:35:30 +0000906 if (p == ps) {
Raymond Hettingerd6234142008-06-09 11:24:47 +0000907 v = PyMem_Malloc(sizeof(double) * m);
Mark Dickinson99dfe922008-05-23 01:35:30 +0000908 if (v != NULL)
Raymond Hettingerd6234142008-06-09 11:24:47 +0000909 memcpy(v, ps, sizeof(double) * n);
Mark Dickinson99dfe922008-05-23 01:35:30 +0000910 }
911 else
Raymond Hettingerd6234142008-06-09 11:24:47 +0000912 v = PyMem_Realloc(p, sizeof(double) * m);
Mark Dickinson99dfe922008-05-23 01:35:30 +0000913 }
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000914 if (v == NULL) { /* size overflow or no memory */
Mark Dickinsonfef6b132008-07-30 16:20:10 +0000915 PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
Mark Dickinson99dfe922008-05-23 01:35:30 +0000916 return 1;
917 }
Raymond Hettingerd6234142008-06-09 11:24:47 +0000918 *p_ptr = (double*) v;
Mark Dickinson99dfe922008-05-23 01:35:30 +0000919 *m_ptr = m;
920 return 0;
921}
922
923/* Full precision summation of a sequence of floats.
924
925 def msum(iterable):
926 partials = [] # sorted, non-overlapping partial sums
927 for x in iterable:
928 i = 0
929 for y in partials:
930 if abs(x) < abs(y):
931 x, y = y, x
932 hi = x + y
933 lo = y - (hi - x)
934 if lo:
935 partials[i] = lo
936 i += 1
937 x = hi
938 partials[i:] = [x]
939 return sum_exact(partials)
940
941 Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
942 are exactly equal to x+y. The inner loop applies hi/lo summation to each
943 partial so that the list of partial sums remains exact.
944
945 Sum_exact() adds the partial sums exactly and correctly rounds the final
946 result (using the round-half-to-even rule). The items in partials remain
947 non-zero, non-special, non-overlapping and strictly increasing in
948 magnitude, but possibly not all having the same sign.
949
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000950 Depends on IEEE 754 arithmetic guarantees and half-even rounding.
951*/
952
Mark Dickinson99dfe922008-05-23 01:35:30 +0000953static PyObject*
Mark Dickinsonfef6b132008-07-30 16:20:10 +0000954math_fsum(PyObject *self, PyObject *seq)
Mark Dickinson99dfe922008-05-23 01:35:30 +0000955{
956 PyObject *item, *iter, *sum = NULL;
957 Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
Raymond Hettingerd6234142008-06-09 11:24:47 +0000958 double x, y, t, ps[NUM_PARTIALS], *p = ps;
Mark Dickinsonabe0aee2008-07-30 12:01:41 +0000959 double xsave, special_sum = 0.0, inf_sum = 0.0;
Raymond Hettingerd6234142008-06-09 11:24:47 +0000960 volatile double hi, yr, lo;
Mark Dickinson99dfe922008-05-23 01:35:30 +0000961
962 iter = PyObject_GetIter(seq);
963 if (iter == NULL)
964 return NULL;
965
Mark Dickinsonfef6b132008-07-30 16:20:10 +0000966 PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL)
Mark Dickinson99dfe922008-05-23 01:35:30 +0000967
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000968 for(;;) { /* for x in iterable */
Mark Dickinson99dfe922008-05-23 01:35:30 +0000969 assert(0 <= n && n <= m);
970 assert((m == NUM_PARTIALS && p == ps) ||
971 (m > NUM_PARTIALS && p != NULL));
972
973 item = PyIter_Next(iter);
974 if (item == NULL) {
975 if (PyErr_Occurred())
Mark Dickinsonfef6b132008-07-30 16:20:10 +0000976 goto _fsum_error;
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000977 break;
Mark Dickinson99dfe922008-05-23 01:35:30 +0000978 }
Raymond Hettingerd6234142008-06-09 11:24:47 +0000979 x = PyFloat_AsDouble(item);
Mark Dickinson99dfe922008-05-23 01:35:30 +0000980 Py_DECREF(item);
981 if (PyErr_Occurred())
Mark Dickinsonfef6b132008-07-30 16:20:10 +0000982 goto _fsum_error;
Mark Dickinson99dfe922008-05-23 01:35:30 +0000983
Mark Dickinsonabe0aee2008-07-30 12:01:41 +0000984 xsave = x;
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000985 for (i = j = 0; j < n; j++) { /* for y in partials */
Mark Dickinson99dfe922008-05-23 01:35:30 +0000986 y = p[j];
Raymond Hettingeref712d62008-05-30 18:20:50 +0000987 if (fabs(x) < fabs(y)) {
Mark Dickinsonabe0aee2008-07-30 12:01:41 +0000988 t = x; x = y; y = t;
Raymond Hettingeref712d62008-05-30 18:20:50 +0000989 }
Mark Dickinson99dfe922008-05-23 01:35:30 +0000990 hi = x + y;
Raymond Hettingeref712d62008-05-30 18:20:50 +0000991 yr = hi - x;
992 lo = y - yr;
Mark Dickinson99dfe922008-05-23 01:35:30 +0000993 if (lo != 0.0)
994 p[i++] = lo;
995 x = hi;
996 }
Mark Dickinsonabe0aee2008-07-30 12:01:41 +0000997
998 n = i; /* ps[i:] = [x] */
Mark Dickinson99dfe922008-05-23 01:35:30 +0000999 if (x != 0.0) {
Mark Dickinsonabe0aee2008-07-30 12:01:41 +00001000 if (! Py_IS_FINITE(x)) {
1001 /* a nonfinite x could arise either as
1002 a result of intermediate overflow, or
1003 as a result of a nan or inf in the
1004 summands */
1005 if (Py_IS_FINITE(xsave)) {
1006 PyErr_SetString(PyExc_OverflowError,
Mark Dickinsonfef6b132008-07-30 16:20:10 +00001007 "intermediate overflow in fsum");
1008 goto _fsum_error;
Mark Dickinsonabe0aee2008-07-30 12:01:41 +00001009 }
1010 if (Py_IS_INFINITY(xsave))
1011 inf_sum += xsave;
1012 special_sum += xsave;
1013 /* reset partials */
Mark Dickinson99dfe922008-05-23 01:35:30 +00001014 n = 0;
Mark Dickinsonabe0aee2008-07-30 12:01:41 +00001015 }
Mark Dickinsonfef6b132008-07-30 16:20:10 +00001016 else if (n >= m && _fsum_realloc(&p, n, ps, &m))
1017 goto _fsum_error;
Mark Dickinsonabe0aee2008-07-30 12:01:41 +00001018 else
1019 p[n++] = x;
Mark Dickinson99dfe922008-05-23 01:35:30 +00001020 }
1021 }
Mark Dickinson99dfe922008-05-23 01:35:30 +00001022
Mark Dickinsonabe0aee2008-07-30 12:01:41 +00001023 if (special_sum != 0.0) {
1024 if (Py_IS_NAN(inf_sum))
1025 PyErr_SetString(PyExc_ValueError,
Mark Dickinsonfef6b132008-07-30 16:20:10 +00001026 "-inf + inf in fsum");
Mark Dickinsonabe0aee2008-07-30 12:01:41 +00001027 else
1028 sum = PyFloat_FromDouble(special_sum);
Mark Dickinsonfef6b132008-07-30 16:20:10 +00001029 goto _fsum_error;
Mark Dickinsonabe0aee2008-07-30 12:01:41 +00001030 }
1031
Raymond Hettingeref712d62008-05-30 18:20:50 +00001032 hi = 0.0;
Mark Dickinson99dfe922008-05-23 01:35:30 +00001033 if (n > 0) {
1034 hi = p[--n];
Mark Dickinsonabe0aee2008-07-30 12:01:41 +00001035 /* sum_exact(ps, hi) from the top, stop when the sum becomes
1036 inexact. */
1037 while (n > 0) {
1038 x = hi;
1039 y = p[--n];
1040 assert(fabs(y) < fabs(x));
1041 hi = x + y;
1042 yr = hi - x;
1043 lo = y - yr;
1044 if (lo != 0.0)
1045 break;
Mark Dickinson99dfe922008-05-23 01:35:30 +00001046 }
Mark Dickinsonabe0aee2008-07-30 12:01:41 +00001047 /* Make half-even rounding work across multiple partials.
1048 Needed so that sum([1e-16, 1, 1e16]) will round-up the last
1049 digit to two instead of down to zero (the 1e-16 makes the 1
1050 slightly closer to two). With a potential 1 ULP rounding
Mark Dickinsonff3fdce2008-07-30 16:25:16 +00001051 error fixed-up, math.fsum() can guarantee commutativity. */
Mark Dickinsonabe0aee2008-07-30 12:01:41 +00001052 if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
1053 (lo > 0.0 && p[n-1] > 0.0))) {
1054 y = lo * 2.0;
1055 x = hi + y;
1056 yr = x - hi;
1057 if (y == yr)
1058 hi = x;
Mark Dickinson99dfe922008-05-23 01:35:30 +00001059 }
1060 }
Raymond Hettingerd6234142008-06-09 11:24:47 +00001061 sum = PyFloat_FromDouble(hi);
Mark Dickinson99dfe922008-05-23 01:35:30 +00001062
Mark Dickinsonfef6b132008-07-30 16:20:10 +00001063_fsum_error:
Mark Dickinson99dfe922008-05-23 01:35:30 +00001064 PyFPE_END_PROTECT(hi)
Mark Dickinson99dfe922008-05-23 01:35:30 +00001065 Py_DECREF(iter);
1066 if (p != ps)
1067 PyMem_Free(p);
1068 return sum;
1069}
1070
1071#undef NUM_PARTIALS
1072
Mark Dickinsonfef6b132008-07-30 16:20:10 +00001073PyDoc_STRVAR(math_fsum_doc,
Georg Brandl40777e62009-10-29 20:38:32 +00001074"fsum(iterable)\n\n\
Raymond Hettinger778d5cc2008-05-23 04:32:43 +00001075Return an accurate floating point sum of values in the iterable.\n\
1076Assumes IEEE-754 floating point arithmetic.");
Mark Dickinson99dfe922008-05-23 01:35:30 +00001077
Raymond Hettingerecbdd2e2008-06-09 06:54:45 +00001078static PyObject *
1079math_factorial(PyObject *self, PyObject *arg)
1080{
1081 long i, x;
1082 PyObject *result, *iobj, *newresult;
1083
1084 if (PyFloat_Check(arg)) {
1085 double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
1086 if (dx != floor(dx)) {
1087 PyErr_SetString(PyExc_ValueError,
1088 "factorial() only accepts integral values");
1089 return NULL;
1090 }
1091 }
1092
1093 x = PyInt_AsLong(arg);
1094 if (x == -1 && PyErr_Occurred())
1095 return NULL;
1096 if (x < 0) {
1097 PyErr_SetString(PyExc_ValueError,
1098 "factorial() not defined for negative values");
1099 return NULL;
1100 }
1101
1102 result = (PyObject *)PyInt_FromLong(1);
1103 if (result == NULL)
1104 return NULL;
1105 for (i=1 ; i<=x ; i++) {
1106 iobj = (PyObject *)PyInt_FromLong(i);
1107 if (iobj == NULL)
1108 goto error;
1109 newresult = PyNumber_Multiply(result, iobj);
1110 Py_DECREF(iobj);
1111 if (newresult == NULL)
1112 goto error;
1113 Py_DECREF(result);
1114 result = newresult;
1115 }
1116 return result;
1117
1118error:
1119 Py_DECREF(result);
Raymond Hettingerecbdd2e2008-06-09 06:54:45 +00001120 return NULL;
1121}
1122
Benjamin Petersonfed67fd2008-12-20 02:57:19 +00001123PyDoc_STRVAR(math_factorial_doc,
1124"factorial(x) -> Integral\n"
1125"\n"
1126"Find x!. Raise a ValueError if x is negative or non-integral.");
Raymond Hettingerecbdd2e2008-06-09 06:54:45 +00001127
Barry Warsaw8b43b191996-12-09 22:32:36 +00001128static PyObject *
Jeffrey Yasskinca2b69f2008-02-01 06:22:46 +00001129math_trunc(PyObject *self, PyObject *number)
1130{
Jeffrey Yasskinca2b69f2008-02-01 06:22:46 +00001131 return PyObject_CallMethod(number, "__trunc__", NULL);
1132}
1133
1134PyDoc_STRVAR(math_trunc_doc,
1135"trunc(x:Real) -> Integral\n"
1136"\n"
Raymond Hettingerfe424f72008-02-02 05:24:44 +00001137"Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.");
Jeffrey Yasskinca2b69f2008-02-01 06:22:46 +00001138
1139static PyObject *
Neal Norwitz45e230a2006-11-19 21:26:53 +00001140math_frexp(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001141{
Guido van Rossumd18ad581991-10-24 14:57:21 +00001142 int i;
Neal Norwitz45e230a2006-11-19 21:26:53 +00001143 double x = PyFloat_AsDouble(arg);
1144 if (x == -1.0 && PyErr_Occurred())
Guido van Rossumd18ad581991-10-24 14:57:21 +00001145 return NULL;
Christian Heimes6f341092008-04-18 23:13:07 +00001146 /* deal with special cases directly, to sidestep platform
1147 differences */
1148 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
1149 i = 0;
1150 }
1151 else {
1152 PyFPE_START_PROTECT("in math_frexp", return 0);
1153 x = frexp(x, &i);
1154 PyFPE_END_PROTECT(x);
1155 }
1156 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001157}
1158
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001159PyDoc_STRVAR(math_frexp_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001160"frexp(x)\n"
1161"\n"
1162"Return the mantissa and exponent of x, as pair (m, e).\n"
1163"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 +00001164"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 +00001165
Barry Warsaw8b43b191996-12-09 22:32:36 +00001166static PyObject *
Fred Drake40c48682000-07-03 18:11:56 +00001167math_ldexp(PyObject *self, PyObject *args)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001168{
Christian Heimes6f341092008-04-18 23:13:07 +00001169 double x, r;
Mark Dickinsonf8476c12008-05-09 17:54:23 +00001170 PyObject *oexp;
1171 long exp;
1172 if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp))
Guido van Rossumd18ad581991-10-24 14:57:21 +00001173 return NULL;
Mark Dickinsonf8476c12008-05-09 17:54:23 +00001174
1175 if (PyLong_Check(oexp)) {
1176 /* on overflow, replace exponent with either LONG_MAX
1177 or LONG_MIN, depending on the sign. */
1178 exp = PyLong_AsLong(oexp);
1179 if (exp == -1 && PyErr_Occurred()) {
1180 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1181 if (Py_SIZE(oexp) < 0) {
1182 exp = LONG_MIN;
1183 }
1184 else {
1185 exp = LONG_MAX;
1186 }
1187 PyErr_Clear();
1188 }
1189 else {
1190 /* propagate any unexpected exception */
1191 return NULL;
1192 }
1193 }
1194 }
1195 else if (PyInt_Check(oexp)) {
1196 exp = PyInt_AS_LONG(oexp);
1197 }
1198 else {
1199 PyErr_SetString(PyExc_TypeError,
1200 "Expected an int or long as second argument "
1201 "to ldexp.");
1202 return NULL;
1203 }
1204
1205 if (x == 0. || !Py_IS_FINITE(x)) {
1206 /* NaNs, zeros and infinities are returned unchanged */
1207 r = x;
Christian Heimes6f341092008-04-18 23:13:07 +00001208 errno = 0;
Mark Dickinsonf8476c12008-05-09 17:54:23 +00001209 } else if (exp > INT_MAX) {
1210 /* overflow */
1211 r = copysign(Py_HUGE_VAL, x);
1212 errno = ERANGE;
1213 } else if (exp < INT_MIN) {
1214 /* underflow to +-0 */
1215 r = copysign(0., x);
1216 errno = 0;
1217 } else {
1218 errno = 0;
1219 PyFPE_START_PROTECT("in math_ldexp", return 0);
1220 r = ldexp(x, (int)exp);
1221 PyFPE_END_PROTECT(r);
1222 if (Py_IS_INFINITY(r))
1223 errno = ERANGE;
1224 }
1225
Christian Heimes6f341092008-04-18 23:13:07 +00001226 if (errno && is_error(r))
Tim Peters1d120612000-10-12 06:10:25 +00001227 return NULL;
Mark Dickinsonf8476c12008-05-09 17:54:23 +00001228 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001229}
1230
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001231PyDoc_STRVAR(math_ldexp_doc,
Georg Brandla8f8bed22009-10-29 20:54:03 +00001232"ldexp(x, i)\n\n\
1233Return x * (2**i).");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001234
Barry Warsaw8b43b191996-12-09 22:32:36 +00001235static PyObject *
Neal Norwitz45e230a2006-11-19 21:26:53 +00001236math_modf(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001237{
Neal Norwitz45e230a2006-11-19 21:26:53 +00001238 double y, x = PyFloat_AsDouble(arg);
1239 if (x == -1.0 && PyErr_Occurred())
Guido van Rossumd18ad581991-10-24 14:57:21 +00001240 return NULL;
Mark Dickinsonb2f70902008-04-20 01:39:24 +00001241 /* some platforms don't do the right thing for NaNs and
1242 infinities, so we take care of special cases directly. */
1243 if (!Py_IS_FINITE(x)) {
1244 if (Py_IS_INFINITY(x))
1245 return Py_BuildValue("(dd)", copysign(0., x), x);
1246 else if (Py_IS_NAN(x))
1247 return Py_BuildValue("(dd)", x, x);
1248 }
1249
Guido van Rossumd18ad581991-10-24 14:57:21 +00001250 errno = 0;
Christian Heimes6f341092008-04-18 23:13:07 +00001251 PyFPE_START_PROTECT("in math_modf", return 0);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001252 x = modf(x, &y);
Christian Heimes6f341092008-04-18 23:13:07 +00001253 PyFPE_END_PROTECT(x);
1254 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001255}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001256
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001257PyDoc_STRVAR(math_modf_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001258"modf(x)\n"
1259"\n"
1260"Return the fractional and integer parts of x. Both results carry the sign\n"
Benjamin Peterson9de72982008-12-20 22:49:24 +00001261"of x and are floats.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001262
Tim Peters78526162001-09-05 00:53:45 +00001263/* A decent logarithm is easy to compute even for huge longs, but libm can't
1264 do that by itself -- loghelper can. func is log or log10, and name is
1265 "log" or "log10". Note that overflow isn't possible: a long can contain
1266 no more than INT_MAX * SHIFT bits, so has value certainly less than
1267 2**(2**64 * 2**16) == 2**2**80, and log2 of that is 2**80, which is
1268 small enough to fit in an IEEE single. log and log10 are even smaller.
1269*/
1270
1271static PyObject*
Neal Norwitz45e230a2006-11-19 21:26:53 +00001272loghelper(PyObject* arg, double (*func)(double), char *funcname)
Tim Peters78526162001-09-05 00:53:45 +00001273{
Tim Peters78526162001-09-05 00:53:45 +00001274 /* If it is long, do it ourselves. */
1275 if (PyLong_Check(arg)) {
1276 double x;
1277 int e;
1278 x = _PyLong_AsScaledDouble(arg, &e);
1279 if (x <= 0.0) {
1280 PyErr_SetString(PyExc_ValueError,
1281 "math domain error");
1282 return NULL;
1283 }
Christian Heimes543cabc2008-01-25 14:54:23 +00001284 /* Value is ~= x * 2**(e*PyLong_SHIFT), so the log ~=
1285 log(x) + log(2) * e * PyLong_SHIFT.
1286 CAUTION: e*PyLong_SHIFT may overflow using int arithmetic,
Tim Peters78526162001-09-05 00:53:45 +00001287 so force use of double. */
Christian Heimes543cabc2008-01-25 14:54:23 +00001288 x = func(x) + (e * (double)PyLong_SHIFT) * func(2.0);
Tim Peters78526162001-09-05 00:53:45 +00001289 return PyFloat_FromDouble(x);
1290 }
1291
1292 /* Else let libm handle it by itself. */
Christian Heimes6f341092008-04-18 23:13:07 +00001293 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +00001294}
1295
1296static PyObject *
1297math_log(PyObject *self, PyObject *args)
1298{
Raymond Hettinger866964c2002-12-14 19:51:34 +00001299 PyObject *arg;
1300 PyObject *base = NULL;
1301 PyObject *num, *den;
1302 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001303
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001304 if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base))
Raymond Hettinger866964c2002-12-14 19:51:34 +00001305 return NULL;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001306
Mark Dickinson4c96fa52008-12-11 19:28:08 +00001307 num = loghelper(arg, m_log, "log");
Neal Norwitz45e230a2006-11-19 21:26:53 +00001308 if (num == NULL || base == NULL)
1309 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001310
Mark Dickinson4c96fa52008-12-11 19:28:08 +00001311 den = loghelper(base, m_log, "log");
Raymond Hettinger866964c2002-12-14 19:51:34 +00001312 if (den == NULL) {
1313 Py_DECREF(num);
1314 return NULL;
1315 }
1316
1317 ans = PyNumber_Divide(num, den);
1318 Py_DECREF(num);
1319 Py_DECREF(den);
1320 return ans;
Tim Peters78526162001-09-05 00:53:45 +00001321}
1322
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001323PyDoc_STRVAR(math_log_doc,
Georg Brandla8f8bed22009-10-29 20:54:03 +00001324"log(x[, base])\n\n\
1325Return the logarithm of x to the given base.\n\
Raymond Hettinger866964c2002-12-14 19:51:34 +00001326If the base not specified, returns the natural logarithm (base e) of x.");
Tim Peters78526162001-09-05 00:53:45 +00001327
1328static PyObject *
Neal Norwitz45e230a2006-11-19 21:26:53 +00001329math_log10(PyObject *self, PyObject *arg)
Tim Peters78526162001-09-05 00:53:45 +00001330{
Mark Dickinson4c96fa52008-12-11 19:28:08 +00001331 return loghelper(arg, m_log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +00001332}
1333
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001334PyDoc_STRVAR(math_log10_doc,
Georg Brandla8f8bed22009-10-29 20:54:03 +00001335"log10(x)\n\nReturn the base 10 logarithm of x.");
Tim Peters78526162001-09-05 00:53:45 +00001336
Christian Heimes6f341092008-04-18 23:13:07 +00001337static PyObject *
1338math_fmod(PyObject *self, PyObject *args)
1339{
1340 PyObject *ox, *oy;
1341 double r, x, y;
1342 if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy))
1343 return NULL;
1344 x = PyFloat_AsDouble(ox);
1345 y = PyFloat_AsDouble(oy);
1346 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1347 return NULL;
1348 /* fmod(x, +/-Inf) returns x for finite x. */
1349 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
1350 return PyFloat_FromDouble(x);
1351 errno = 0;
1352 PyFPE_START_PROTECT("in math_fmod", return 0);
1353 r = fmod(x, y);
1354 PyFPE_END_PROTECT(r);
1355 if (Py_IS_NAN(r)) {
1356 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1357 errno = EDOM;
1358 else
1359 errno = 0;
1360 }
1361 if (errno && is_error(r))
1362 return NULL;
1363 else
1364 return PyFloat_FromDouble(r);
1365}
1366
1367PyDoc_STRVAR(math_fmod_doc,
Georg Brandla8f8bed22009-10-29 20:54:03 +00001368"fmod(x, y)\n\nReturn fmod(x, y), according to platform C."
Christian Heimes6f341092008-04-18 23:13:07 +00001369" x % y may differ.");
1370
1371static PyObject *
1372math_hypot(PyObject *self, PyObject *args)
1373{
1374 PyObject *ox, *oy;
1375 double r, x, y;
1376 if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy))
1377 return NULL;
1378 x = PyFloat_AsDouble(ox);
1379 y = PyFloat_AsDouble(oy);
1380 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1381 return NULL;
1382 /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */
1383 if (Py_IS_INFINITY(x))
1384 return PyFloat_FromDouble(fabs(x));
1385 if (Py_IS_INFINITY(y))
1386 return PyFloat_FromDouble(fabs(y));
1387 errno = 0;
1388 PyFPE_START_PROTECT("in math_hypot", return 0);
1389 r = hypot(x, y);
1390 PyFPE_END_PROTECT(r);
1391 if (Py_IS_NAN(r)) {
1392 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1393 errno = EDOM;
1394 else
1395 errno = 0;
1396 }
1397 else if (Py_IS_INFINITY(r)) {
1398 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
1399 errno = ERANGE;
1400 else
1401 errno = 0;
1402 }
1403 if (errno && is_error(r))
1404 return NULL;
1405 else
1406 return PyFloat_FromDouble(r);
1407}
1408
1409PyDoc_STRVAR(math_hypot_doc,
Georg Brandla8f8bed22009-10-29 20:54:03 +00001410"hypot(x, y)\n\nReturn the Euclidean distance, sqrt(x*x + y*y).");
Christian Heimes6f341092008-04-18 23:13:07 +00001411
1412/* pow can't use math_2, but needs its own wrapper: the problem is
1413 that an infinite result can arise either as a result of overflow
1414 (in which case OverflowError should be raised) or as a result of
1415 e.g. 0.**-5. (for which ValueError needs to be raised.)
1416*/
1417
1418static PyObject *
1419math_pow(PyObject *self, PyObject *args)
1420{
1421 PyObject *ox, *oy;
1422 double r, x, y;
Mark Dickinsoncec3f132008-04-20 04:13:13 +00001423 int odd_y;
Christian Heimes6f341092008-04-18 23:13:07 +00001424
1425 if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy))
1426 return NULL;
1427 x = PyFloat_AsDouble(ox);
1428 y = PyFloat_AsDouble(oy);
1429 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1430 return NULL;
Mark Dickinsona1293eb2008-04-19 19:41:52 +00001431
Mark Dickinsoncec3f132008-04-20 04:13:13 +00001432 /* deal directly with IEEE specials, to cope with problems on various
1433 platforms whose semantics don't exactly match C99 */
Mark Dickinson0da94c82008-04-21 01:55:50 +00001434 r = 0.; /* silence compiler warning */
Mark Dickinsoncec3f132008-04-20 04:13:13 +00001435 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
1436 errno = 0;
1437 if (Py_IS_NAN(x))
1438 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
1439 else if (Py_IS_NAN(y))
1440 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
1441 else if (Py_IS_INFINITY(x)) {
1442 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
1443 if (y > 0.)
1444 r = odd_y ? x : fabs(x);
1445 else if (y == 0.)
1446 r = 1.;
1447 else /* y < 0. */
1448 r = odd_y ? copysign(0., x) : 0.;
1449 }
1450 else if (Py_IS_INFINITY(y)) {
1451 if (fabs(x) == 1.0)
1452 r = 1.;
1453 else if (y > 0. && fabs(x) > 1.0)
1454 r = y;
1455 else if (y < 0. && fabs(x) < 1.0) {
1456 r = -y; /* result is +inf */
1457 if (x == 0.) /* 0**-inf: divide-by-zero */
1458 errno = EDOM;
1459 }
1460 else
1461 r = 0.;
1462 }
Mark Dickinsone941d972008-04-19 18:51:48 +00001463 }
Mark Dickinsoncec3f132008-04-20 04:13:13 +00001464 else {
1465 /* let libm handle finite**finite */
1466 errno = 0;
1467 PyFPE_START_PROTECT("in math_pow", return 0);
1468 r = pow(x, y);
1469 PyFPE_END_PROTECT(r);
1470 /* a NaN result should arise only from (-ve)**(finite
1471 non-integer); in this case we want to raise ValueError. */
1472 if (!Py_IS_FINITE(r)) {
1473 if (Py_IS_NAN(r)) {
1474 errno = EDOM;
1475 }
1476 /*
1477 an infinite result here arises either from:
1478 (A) (+/-0.)**negative (-> divide-by-zero)
1479 (B) overflow of x**y with x and y finite
1480 */
1481 else if (Py_IS_INFINITY(r)) {
1482 if (x == 0.)
1483 errno = EDOM;
1484 else
1485 errno = ERANGE;
1486 }
1487 }
Christian Heimes6f341092008-04-18 23:13:07 +00001488 }
1489
1490 if (errno && is_error(r))
1491 return NULL;
1492 else
1493 return PyFloat_FromDouble(r);
1494}
1495
1496PyDoc_STRVAR(math_pow_doc,
Georg Brandla8f8bed22009-10-29 20:54:03 +00001497"pow(x, y)\n\nReturn x**y (x to the power of y).");
Christian Heimes6f341092008-04-18 23:13:07 +00001498
Christian Heimese2ca4242008-01-03 20:23:15 +00001499static const double degToRad = Py_MATH_PI / 180.0;
1500static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001501
1502static PyObject *
Neal Norwitz45e230a2006-11-19 21:26:53 +00001503math_degrees(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001504{
Neal Norwitz45e230a2006-11-19 21:26:53 +00001505 double x = PyFloat_AsDouble(arg);
1506 if (x == -1.0 && PyErr_Occurred())
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001507 return NULL;
Christian Heimese2ca4242008-01-03 20:23:15 +00001508 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001509}
1510
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001511PyDoc_STRVAR(math_degrees_doc,
Georg Brandla8f8bed22009-10-29 20:54:03 +00001512"degrees(x)\n\n\
1513Convert angle x from radians to degrees.");
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001514
1515static PyObject *
Neal Norwitz45e230a2006-11-19 21:26:53 +00001516math_radians(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001517{
Neal Norwitz45e230a2006-11-19 21:26:53 +00001518 double x = PyFloat_AsDouble(arg);
1519 if (x == -1.0 && PyErr_Occurred())
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001520 return NULL;
1521 return PyFloat_FromDouble(x * degToRad);
1522}
1523
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001524PyDoc_STRVAR(math_radians_doc,
Georg Brandla8f8bed22009-10-29 20:54:03 +00001525"radians(x)\n\n\
1526Convert angle x from degrees to radians.");
Tim Peters78526162001-09-05 00:53:45 +00001527
Christian Heimese2ca4242008-01-03 20:23:15 +00001528static PyObject *
1529math_isnan(PyObject *self, PyObject *arg)
1530{
1531 double x = PyFloat_AsDouble(arg);
1532 if (x == -1.0 && PyErr_Occurred())
1533 return NULL;
1534 return PyBool_FromLong((long)Py_IS_NAN(x));
1535}
1536
1537PyDoc_STRVAR(math_isnan_doc,
Georg Brandla8f8bed22009-10-29 20:54:03 +00001538"isnan(x) -> bool\n\n\
1539Check if float x is not a number (NaN).");
Christian Heimese2ca4242008-01-03 20:23:15 +00001540
1541static PyObject *
1542math_isinf(PyObject *self, PyObject *arg)
1543{
1544 double x = PyFloat_AsDouble(arg);
1545 if (x == -1.0 && PyErr_Occurred())
1546 return NULL;
1547 return PyBool_FromLong((long)Py_IS_INFINITY(x));
1548}
1549
1550PyDoc_STRVAR(math_isinf_doc,
Georg Brandla8f8bed22009-10-29 20:54:03 +00001551"isinf(x) -> bool\n\n\
1552Check if float x is infinite (positive or negative).");
Christian Heimese2ca4242008-01-03 20:23:15 +00001553
Barry Warsaw8b43b191996-12-09 22:32:36 +00001554static PyMethodDef math_methods[] = {
Neal Norwitz45e230a2006-11-19 21:26:53 +00001555 {"acos", math_acos, METH_O, math_acos_doc},
Christian Heimes6f341092008-04-18 23:13:07 +00001556 {"acosh", math_acosh, METH_O, math_acosh_doc},
Neal Norwitz45e230a2006-11-19 21:26:53 +00001557 {"asin", math_asin, METH_O, math_asin_doc},
Christian Heimes6f341092008-04-18 23:13:07 +00001558 {"asinh", math_asinh, METH_O, math_asinh_doc},
Neal Norwitz45e230a2006-11-19 21:26:53 +00001559 {"atan", math_atan, METH_O, math_atan_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001560 {"atan2", math_atan2, METH_VARARGS, math_atan2_doc},
Christian Heimes6f341092008-04-18 23:13:07 +00001561 {"atanh", math_atanh, METH_O, math_atanh_doc},
Neal Norwitz45e230a2006-11-19 21:26:53 +00001562 {"ceil", math_ceil, METH_O, math_ceil_doc},
Christian Heimeseebb79c2008-01-03 22:32:26 +00001563 {"copysign", math_copysign, METH_VARARGS, math_copysign_doc},
Neal Norwitz45e230a2006-11-19 21:26:53 +00001564 {"cos", math_cos, METH_O, math_cos_doc},
1565 {"cosh", math_cosh, METH_O, math_cosh_doc},
1566 {"degrees", math_degrees, METH_O, math_degrees_doc},
Mark Dickinson5ff37ae2009-12-19 11:07:23 +00001567 {"erf", math_erf, METH_O, math_erf_doc},
1568 {"erfc", math_erfc, METH_O, math_erfc_doc},
Neal Norwitz45e230a2006-11-19 21:26:53 +00001569 {"exp", math_exp, METH_O, math_exp_doc},
Mark Dickinson9cae1782009-12-16 20:13:40 +00001570 {"expm1", math_expm1, METH_O, math_expm1_doc},
Neal Norwitz45e230a2006-11-19 21:26:53 +00001571 {"fabs", math_fabs, METH_O, math_fabs_doc},
Raymond Hettingerecbdd2e2008-06-09 06:54:45 +00001572 {"factorial", math_factorial, METH_O, math_factorial_doc},
Neal Norwitz45e230a2006-11-19 21:26:53 +00001573 {"floor", math_floor, METH_O, math_floor_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001574 {"fmod", math_fmod, METH_VARARGS, math_fmod_doc},
Neal Norwitz45e230a2006-11-19 21:26:53 +00001575 {"frexp", math_frexp, METH_O, math_frexp_doc},
Mark Dickinsonfef6b132008-07-30 16:20:10 +00001576 {"fsum", math_fsum, METH_O, math_fsum_doc},
Mark Dickinsonb93fff02009-09-28 18:54:55 +00001577 {"gamma", math_gamma, METH_O, math_gamma_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001578 {"hypot", math_hypot, METH_VARARGS, math_hypot_doc},
Christian Heimese2ca4242008-01-03 20:23:15 +00001579 {"isinf", math_isinf, METH_O, math_isinf_doc},
1580 {"isnan", math_isnan, METH_O, math_isnan_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001581 {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc},
Mark Dickinson9be87bc2009-12-11 17:29:33 +00001582 {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001583 {"log", math_log, METH_VARARGS, math_log_doc},
Christian Heimes6f341092008-04-18 23:13:07 +00001584 {"log1p", math_log1p, METH_O, math_log1p_doc},
Neal Norwitz45e230a2006-11-19 21:26:53 +00001585 {"log10", math_log10, METH_O, math_log10_doc},
1586 {"modf", math_modf, METH_O, math_modf_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001587 {"pow", math_pow, METH_VARARGS, math_pow_doc},
Neal Norwitz45e230a2006-11-19 21:26:53 +00001588 {"radians", math_radians, METH_O, math_radians_doc},
1589 {"sin", math_sin, METH_O, math_sin_doc},
1590 {"sinh", math_sinh, METH_O, math_sinh_doc},
1591 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
1592 {"tan", math_tan, METH_O, math_tan_doc},
1593 {"tanh", math_tanh, METH_O, math_tanh_doc},
Mark Dickinsonfef6b132008-07-30 16:20:10 +00001594 {"trunc", math_trunc, METH_O, math_trunc_doc},
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001595 {NULL, NULL} /* sentinel */
1596};
1597
Guido van Rossumc6e22901998-12-04 19:26:43 +00001598
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001599PyDoc_STRVAR(module_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001600"This module is always available. It provides access to the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001601"mathematical functions defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001602
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001603PyMODINIT_FUNC
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001604initmath(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001605{
Christian Heimes6f341092008-04-18 23:13:07 +00001606 PyObject *m;
Tim Petersfe71f812001-08-07 22:10:00 +00001607
Guido van Rossumc6e22901998-12-04 19:26:43 +00001608 m = Py_InitModule3("math", math_methods, module_doc);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00001609 if (m == NULL)
1610 goto finally;
Barry Warsawfc93f751996-12-17 00:47:03 +00001611
Christian Heimes6f341092008-04-18 23:13:07 +00001612 PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
1613 PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
Barry Warsawfc93f751996-12-17 00:47:03 +00001614
Christian Heimes6f341092008-04-18 23:13:07 +00001615 finally:
Barry Warsaw9bfd2bf2000-09-01 09:01:32 +00001616 return;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001617}