Use a more idiomatic check in check_truediv.
[python.git] / Modules / mathmodule.c
blob6eb9e9175defa5cbe39403676c3c896b42d3b62a
1 /* Math module -- standard C math library functions, pi and e */
3 /* 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.
9 These are the "spirit of 754" rules:
11 1. If the mathematical result is a real number, but of magnitude too
12 large to approximate by a machine float, overflow is signaled and the
13 result is an infinity (with the appropriate sign).
15 2. If the mathematical result is a real number, but of magnitude too
16 small to approximate by a machine float, underflow is signaled and the
17 result is a zero (with the appropriate sign).
19 3. At a singularity (a value x such that the limit of f(y) as y
20 approaches x exists and is an infinity), "divide by zero" is signaled
21 and the result is an infinity (with the appropriate sign). This is
22 complicated a little by that the left-side and right-side limits may
23 not be the same; e.g., 1/x approaches +inf or -inf as x approaches 0
24 from the positive or negative directions. In that specific case, the
25 sign of the zero determines the result of 1/0.
27 4. At a point where a function has no defined result in the extended
28 reals (i.e., the reals plus an infinity or two), invalid operation is
29 signaled and a NaN is returned.
31 And these are what Python has historically /tried/ to do (but not
32 always successfully, as platform libm behavior varies a lot):
34 For #1, raise OverflowError.
36 For #2, return a zero (with the appropriate sign if that happens by
37 accident ;-)).
39 For #3 and #4, raise ValueError. It may have made sense to raise
40 Python's ZeroDivisionError in #3, but historically that's only been
41 raised for division by zero and mod by zero.
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.
55 #include "Python.h"
56 #include "_math.h"
57 #include "longintrepr.h" /* just for SHIFT */
59 #ifdef _OSF_SOURCE
60 /* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
61 extern double copysign(double, double);
62 #endif
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.
71 static const double pi = 3.141592653589793238462643383279502884197;
72 static const double sqrtpi = 1.772453850905516027298167483341145182798;
74 static double
75 sinpi(double x)
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 */
106 return copysign(1.0, x)*r;
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.
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.
123 For x < 0.0 we use the reflection formula.
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:
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:
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,
142 where the correction_factor C is given by
144 C = pow(1-e/y, x-0.5) * exp(e)
146 Since e is tiny, pow(1-e/y, x-0.5) ~ 1-(x-0.5)*e/y, and exp(x) ~ 1+e, so:
148 C ~ (1-(x-0.5)*e/y) * (1+e) ~ 1 + e*(y-(x-0.5))/y
150 But y-(x-0.5) = g+e, and g+e ~ g. So we get C ~ 1 + e*g/y, and
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),
154 Note that for accuracy, when computing r*C it's better to do
156 r + e*g/y*r;
158 than
160 r * (1 + e*g/y);
162 since the addition in the latter throws away most of the bits of
163 information in e*g/y.
166 #define LANCZOS_N 13
167 static const double lanczos_g = 6.024680040776729583740234375;
168 static const double lanczos_g_minus_half = 5.524680040776729583740234375;
169 static 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
185 /* denominator is x*(x+1)*...*(x+LANCZOS_N-2) */
186 static 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};
190 /* gamma values for small positive integers, 1 though NGAMMA_INTEGRAL */
191 #define NGAMMA_INTEGRAL 23
192 static 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,
200 /* Lanczos' sum L_g(x), for positive x */
202 static double
203 lanczos_sum(double x)
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];
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];
228 return num/den;
231 static double
232 m_tgamma(double x)
234 double absx, r, y, z, sqrtpow;
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 */
245 if (x == 0.0) {
246 errno = EDOM;
247 return 1.0/x; /* tgamma(+-0.0) = +-inf, divide-by-zero */
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 */
256 if (x <= NGAMMA_INTEGRAL)
257 return gamma_integral[(int)x - 1];
259 absx = fabs(x);
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;
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);
276 else {
277 errno = ERANGE;
278 return Py_HUGE_VAL;
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;
292 else {
293 double q = y - lanczos_g_minus_half;
294 z = q - absx;
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);
303 else {
304 sqrtpow = pow(y, absx / 2.0 - 0.25);
305 r /= sqrtpow;
306 r /= sqrtpow;
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);
315 else {
316 sqrtpow = pow(y, absx / 2.0 - 0.25);
317 r *= sqrtpow;
318 r *= sqrtpow;
321 if (Py_IS_INFINITY(r))
322 errno = ERANGE;
323 return r;
327 lgamma: natural log of the absolute value of the Gamma function.
328 For large arguments, Lanczos' formula works extremely well here.
331 static double
332 m_lgamma(double x)
334 double r, absx;
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 */
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 */
350 else {
351 return 0.0; /* lgamma(1) = lgamma(2) = 0.0 */
355 absx = fabs(x);
356 /* tiny arguments: lgamma(x) ~ -log(fabs(x)) for small x */
357 if (absx < 1e-20)
358 return -log(absx);
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);
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));
374 if (Py_IS_INFINITY(r))
375 errno = ERANGE;
376 return r;
380 Implementations of the error function erf(x) and the complementary error
381 function erfc(x).
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.
389 The series expansion used is:
391 erf(x) = x*exp(-x*x)/sqrt(pi) * [
392 2/1 + 4/3 x**2 + 8/15 x**4 + 16/105 x**6 + ...]
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.
397 The continued fraction expansion used is:
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 - ) ...]
402 after the first term, the general term has the form:
404 k*(k-0.5)/(2*k+0.5 + x**2 - ...).
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).
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. */
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
423 Error function, via power series.
425 Given a finite float x, return an approximation to erf(x).
426 Converges reasonably fast for small x.
429 static double
430 m_erf_series(double x)
432 double x2, acc, fk;
433 int i;
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;
442 return acc * x * exp(-x2) / sqrtpi;
446 Complementary error function, via continued fraction expansion.
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. */
454 static double
455 m_erfc_contfrac(double x)
457 double x2, a, da, p, p_last, q, q_last, b;
458 int i;
460 if (x >= ERFC_CONTFRAC_CUTOFF)
461 return 0.0;
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;
476 return p / q * x * exp(-x2) / sqrtpi;
479 /* Error function erf(x), for general x */
481 static double
482 m_erf(double x)
484 double absx, cf;
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;
497 /* Complementary error function erfc(x), for general x. */
499 static double
500 m_erfc(double x)
502 double absx, cf;
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;
516 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.
523 static double
524 m_atan2(double y, double x)
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);
537 /* atan2(+-inf, x) == +-pi/2 for finite x */
538 return copysign(0.5*Py_MATH_PI, y);
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);
548 return atan2(y, x);
552 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.
558 static double
559 m_log(double x)
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 */
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 */
580 static double
581 m_log10(double x)
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 */
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 */
603 /* 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.
607 static int
608 is_error(double x)
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");
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).
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.
631 if (fabs(x) < 1.0)
632 result = 0;
633 else
634 PyErr_SetString(PyExc_OverflowError,
635 "math range error");
637 else
638 /* Unexpected math error */
639 PyErr_SetFromErrno(PyExc_ValueError);
640 return result;
644 math_1 is used to wrap a libm function f that takes a double
645 arguments and returns a double.
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.
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
660 The last rule is used to catch overflow on platforms which follow
661 C89 but for which HUGE_VAL is not an infinity.
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.
673 static PyObject *
674 math_1(PyObject *arg, double (*func) (double), int can_overflow)
676 double x, r;
677 x = PyFloat_AsDouble(arg);
678 if (x == -1.0 && PyErr_Occurred())
679 return NULL;
680 errno = 0;
681 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;
690 else if (Py_IS_INFINITY(r)) {
691 if (Py_IS_FINITE(x))
692 errno = can_overflow ? ERANGE : EDOM;
693 else
694 errno = 0;
696 if (errno && is_error(r))
697 return NULL;
698 else
699 return PyFloat_FromDouble(r);
702 /* 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). */
706 static PyObject *
707 math_1a(PyObject *arg, double (*func) (double))
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);
723 math_2 is used to wrap a libm function f that takes two double
724 arguments and returns a double.
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.
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
738 The last rule is used to catch overflow on platforms which follow
739 C89 but for which HUGE_VAL is not an infinity.
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.
749 static PyObject *
750 math_2(PyObject *args, double (*func) (double, double), char *funcname)
752 PyObject *ox, *oy;
753 double x, y, r;
754 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())
759 return NULL;
760 errno = 0;
761 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;
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;
776 if (errno && is_error(r))
777 return NULL;
778 else
779 return PyFloat_FromDouble(r);
782 #define FUNC1(funcname, func, can_overflow, docstring) \
783 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
784 return math_1(args, func, can_overflow); \
786 PyDoc_STRVAR(math_##funcname##_doc, docstring);
788 #define FUNC1A(funcname, func, docstring) \
789 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
790 return math_1a(args, func); \
792 PyDoc_STRVAR(math_##funcname##_doc, docstring);
794 #define FUNC2(funcname, func, docstring) \
795 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
796 return math_2(args, func, #funcname); \
798 PyDoc_STRVAR(math_##funcname##_doc, docstring);
800 FUNC1(acos, acos, 0,
801 "acos(x)\n\nReturn the arc cosine (measured in radians) of x.")
802 FUNC1(acosh, m_acosh, 0,
803 "acosh(x)\n\nReturn the hyperbolic arc cosine (measured in radians) of x.")
804 FUNC1(asin, asin, 0,
805 "asin(x)\n\nReturn the arc sine (measured in radians) of x.")
806 FUNC1(asinh, m_asinh, 0,
807 "asinh(x)\n\nReturn the hyperbolic arc sine (measured in radians) of x.")
808 FUNC1(atan, atan, 0,
809 "atan(x)\n\nReturn the arc tangent (measured in radians) of x.")
810 FUNC2(atan2, m_atan2,
811 "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.")
813 FUNC1(atanh, m_atanh, 0,
814 "atanh(x)\n\nReturn the hyperbolic arc tangent (measured in radians) of x.")
815 FUNC1(ceil, ceil, 0,
816 "ceil(x)\n\nReturn the ceiling of x as a float.\n"
817 "This is the smallest integral value >= x.")
818 FUNC2(copysign, copysign,
819 "copysign(x, y)\n\nReturn x with the sign of y.")
820 FUNC1(cos, cos, 0,
821 "cos(x)\n\nReturn the cosine of x (measured in radians).")
822 FUNC1(cosh, cosh, 1,
823 "cosh(x)\n\nReturn the hyperbolic cosine of x.")
824 FUNC1A(erf, m_erf,
825 "erf(x)\n\nError function at x.")
826 FUNC1A(erfc, m_erfc,
827 "erfc(x)\n\nComplementary error function at x.")
828 FUNC1(exp, exp, 1,
829 "exp(x)\n\nReturn e raised to the power of x.")
830 FUNC1(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.")
834 FUNC1(fabs, fabs, 0,
835 "fabs(x)\n\nReturn the absolute value of the float x.")
836 FUNC1(floor, floor, 0,
837 "floor(x)\n\nReturn the floor of x as a float.\n"
838 "This is the largest integral value <= x.")
839 FUNC1A(gamma, m_tgamma,
840 "gamma(x)\n\nGamma function at x.")
841 FUNC1A(lgamma, m_lgamma,
842 "lgamma(x)\n\nNatural logarithm of absolute value of Gamma function at x.")
843 FUNC1(log1p, m_log1p, 1,
844 "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.")
846 FUNC1(sin, sin, 0,
847 "sin(x)\n\nReturn the sine of x (measured in radians).")
848 FUNC1(sinh, sinh, 1,
849 "sinh(x)\n\nReturn the hyperbolic sine of x.")
850 FUNC1(sqrt, sqrt, 0,
851 "sqrt(x)\n\nReturn the square root of x.")
852 FUNC1(tan, tan, 0,
853 "tan(x)\n\nReturn the tangent of x (measured in radians).")
854 FUNC1(tanh, tanh, 0,
855 "tanh(x)\n\nReturn the hyperbolic tangent of x.")
857 /* 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>.
861 See those links for more details, proofs and other references.
863 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).
867 Note 2: No provision is made for intermediate overflow handling;
868 therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
869 sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
870 overflow of the first partial sum.
872 Note 3: The intermediate values lo, yr, and hi are declared volatile so
873 aggressive compilers won't algebraically reduce lo to always be exactly 0.0.
874 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
876 prevents double rounding because any addition or subtraction of two doubles
877 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.
883 Note 4: A similar implementation is in Modules/cmathmodule.c.
884 Be sure to update both when making changes.
886 Note 5: The signature of math.fsum() differs from __builtin__.sum()
887 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)).
893 #define NUM_PARTIALS 32 /* initial partials array size, on stack */
895 /* Extend the partials array p[] by doubling its size. */
896 static int /* non-zero on error */
897 _fsum_realloc(double **p_ptr, Py_ssize_t n,
898 double *ps, Py_ssize_t *m_ptr)
900 void *v = NULL;
901 Py_ssize_t m = *m_ptr;
903 m += m; /* double */
904 if (n < m && m < (PY_SSIZE_T_MAX / sizeof(double))) {
905 double *p = *p_ptr;
906 if (p == ps) {
907 v = PyMem_Malloc(sizeof(double) * m);
908 if (v != NULL)
909 memcpy(v, ps, sizeof(double) * n);
911 else
912 v = PyMem_Realloc(p, sizeof(double) * m);
914 if (v == NULL) { /* size overflow or no memory */
915 PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
916 return 1;
918 *p_ptr = (double*) v;
919 *m_ptr = m;
920 return 0;
923 /* Full precision summation of a sequence of floats.
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)
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.
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.
950 Depends on IEEE 754 arithmetic guarantees and half-even rounding.
953 static PyObject*
954 math_fsum(PyObject *self, PyObject *seq)
956 PyObject *item, *iter, *sum = NULL;
957 Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
958 double x, y, t, ps[NUM_PARTIALS], *p = ps;
959 double xsave, special_sum = 0.0, inf_sum = 0.0;
960 volatile double hi, yr, lo;
962 iter = PyObject_GetIter(seq);
963 if (iter == NULL)
964 return NULL;
966 PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL)
968 for(;;) { /* for x in iterable */
969 assert(0 <= n && n <= m);
970 assert((m == NUM_PARTIALS && p == ps) ||
971 (m > NUM_PARTIALS && p != NULL));
973 item = PyIter_Next(iter);
974 if (item == NULL) {
975 if (PyErr_Occurred())
976 goto _fsum_error;
977 break;
979 x = PyFloat_AsDouble(item);
980 Py_DECREF(item);
981 if (PyErr_Occurred())
982 goto _fsum_error;
984 xsave = x;
985 for (i = j = 0; j < n; j++) { /* for y in partials */
986 y = p[j];
987 if (fabs(x) < fabs(y)) {
988 t = x; x = y; y = t;
990 hi = x + y;
991 yr = hi - x;
992 lo = y - yr;
993 if (lo != 0.0)
994 p[i++] = lo;
995 x = hi;
998 n = i; /* ps[i:] = [x] */
999 if (x != 0.0) {
1000 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,
1007 "intermediate overflow in fsum");
1008 goto _fsum_error;
1010 if (Py_IS_INFINITY(xsave))
1011 inf_sum += xsave;
1012 special_sum += xsave;
1013 /* reset partials */
1014 n = 0;
1016 else if (n >= m && _fsum_realloc(&p, n, ps, &m))
1017 goto _fsum_error;
1018 else
1019 p[n++] = x;
1023 if (special_sum != 0.0) {
1024 if (Py_IS_NAN(inf_sum))
1025 PyErr_SetString(PyExc_ValueError,
1026 "-inf + inf in fsum");
1027 else
1028 sum = PyFloat_FromDouble(special_sum);
1029 goto _fsum_error;
1032 hi = 0.0;
1033 if (n > 0) {
1034 hi = p[--n];
1035 /* 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;
1047 /* 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
1051 error fixed-up, math.fsum() can guarantee commutativity. */
1052 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;
1061 sum = PyFloat_FromDouble(hi);
1063 _fsum_error:
1064 PyFPE_END_PROTECT(hi)
1065 Py_DECREF(iter);
1066 if (p != ps)
1067 PyMem_Free(p);
1068 return sum;
1071 #undef NUM_PARTIALS
1073 PyDoc_STRVAR(math_fsum_doc,
1074 "fsum(iterable)\n\n\
1075 Return an accurate floating point sum of values in the iterable.\n\
1076 Assumes IEEE-754 floating point arithmetic.");
1078 static PyObject *
1079 math_factorial(PyObject *self, PyObject *arg)
1081 long i, x;
1082 PyObject *result, *iobj, *newresult;
1084 if (PyFloat_Check(arg)) {
1085 PyObject *lx;
1086 double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
1087 if (!(Py_IS_FINITE(dx) && dx == floor(dx))) {
1088 PyErr_SetString(PyExc_ValueError,
1089 "factorial() only accepts integral values");
1090 return NULL;
1092 lx = PyLong_FromDouble(dx);
1093 if (lx == NULL)
1094 return NULL;
1095 x = PyLong_AsLong(lx);
1096 Py_DECREF(lx);
1098 else
1099 x = PyInt_AsLong(arg);
1101 if (x == -1 && PyErr_Occurred())
1102 return NULL;
1103 if (x < 0) {
1104 PyErr_SetString(PyExc_ValueError,
1105 "factorial() not defined for negative values");
1106 return NULL;
1109 result = (PyObject *)PyInt_FromLong(1);
1110 if (result == NULL)
1111 return NULL;
1112 for (i=1 ; i<=x ; i++) {
1113 iobj = (PyObject *)PyInt_FromLong(i);
1114 if (iobj == NULL)
1115 goto error;
1116 newresult = PyNumber_Multiply(result, iobj);
1117 Py_DECREF(iobj);
1118 if (newresult == NULL)
1119 goto error;
1120 Py_DECREF(result);
1121 result = newresult;
1123 return result;
1125 error:
1126 Py_DECREF(result);
1127 return NULL;
1130 PyDoc_STRVAR(math_factorial_doc,
1131 "factorial(x) -> Integral\n"
1132 "\n"
1133 "Find x!. Raise a ValueError if x is negative or non-integral.");
1135 static PyObject *
1136 math_trunc(PyObject *self, PyObject *number)
1138 return PyObject_CallMethod(number, "__trunc__", NULL);
1141 PyDoc_STRVAR(math_trunc_doc,
1142 "trunc(x:Real) -> Integral\n"
1143 "\n"
1144 "Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.");
1146 static PyObject *
1147 math_frexp(PyObject *self, PyObject *arg)
1149 int i;
1150 double x = PyFloat_AsDouble(arg);
1151 if (x == -1.0 && PyErr_Occurred())
1152 return NULL;
1153 /* deal with special cases directly, to sidestep platform
1154 differences */
1155 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
1156 i = 0;
1158 else {
1159 PyFPE_START_PROTECT("in math_frexp", return 0);
1160 x = frexp(x, &i);
1161 PyFPE_END_PROTECT(x);
1163 return Py_BuildValue("(di)", x, i);
1166 PyDoc_STRVAR(math_frexp_doc,
1167 "frexp(x)\n"
1168 "\n"
1169 "Return the mantissa and exponent of x, as pair (m, e).\n"
1170 "m is a float and e is an int, such that x = m * 2.**e.\n"
1171 "If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.");
1173 static PyObject *
1174 math_ldexp(PyObject *self, PyObject *args)
1176 double x, r;
1177 PyObject *oexp;
1178 long exp;
1179 if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp))
1180 return NULL;
1182 if (PyLong_Check(oexp)) {
1183 /* on overflow, replace exponent with either LONG_MAX
1184 or LONG_MIN, depending on the sign. */
1185 exp = PyLong_AsLong(oexp);
1186 if (exp == -1 && PyErr_Occurred()) {
1187 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1188 if (Py_SIZE(oexp) < 0) {
1189 exp = LONG_MIN;
1191 else {
1192 exp = LONG_MAX;
1194 PyErr_Clear();
1196 else {
1197 /* propagate any unexpected exception */
1198 return NULL;
1202 else if (PyInt_Check(oexp)) {
1203 exp = PyInt_AS_LONG(oexp);
1205 else {
1206 PyErr_SetString(PyExc_TypeError,
1207 "Expected an int or long as second argument "
1208 "to ldexp.");
1209 return NULL;
1212 if (x == 0. || !Py_IS_FINITE(x)) {
1213 /* NaNs, zeros and infinities are returned unchanged */
1214 r = x;
1215 errno = 0;
1216 } else if (exp > INT_MAX) {
1217 /* overflow */
1218 r = copysign(Py_HUGE_VAL, x);
1219 errno = ERANGE;
1220 } else if (exp < INT_MIN) {
1221 /* underflow to +-0 */
1222 r = copysign(0., x);
1223 errno = 0;
1224 } else {
1225 errno = 0;
1226 PyFPE_START_PROTECT("in math_ldexp", return 0);
1227 r = ldexp(x, (int)exp);
1228 PyFPE_END_PROTECT(r);
1229 if (Py_IS_INFINITY(r))
1230 errno = ERANGE;
1233 if (errno && is_error(r))
1234 return NULL;
1235 return PyFloat_FromDouble(r);
1238 PyDoc_STRVAR(math_ldexp_doc,
1239 "ldexp(x, i)\n\n\
1240 Return x * (2**i).");
1242 static PyObject *
1243 math_modf(PyObject *self, PyObject *arg)
1245 double y, x = PyFloat_AsDouble(arg);
1246 if (x == -1.0 && PyErr_Occurred())
1247 return NULL;
1248 /* some platforms don't do the right thing for NaNs and
1249 infinities, so we take care of special cases directly. */
1250 if (!Py_IS_FINITE(x)) {
1251 if (Py_IS_INFINITY(x))
1252 return Py_BuildValue("(dd)", copysign(0., x), x);
1253 else if (Py_IS_NAN(x))
1254 return Py_BuildValue("(dd)", x, x);
1257 errno = 0;
1258 PyFPE_START_PROTECT("in math_modf", return 0);
1259 x = modf(x, &y);
1260 PyFPE_END_PROTECT(x);
1261 return Py_BuildValue("(dd)", x, y);
1264 PyDoc_STRVAR(math_modf_doc,
1265 "modf(x)\n"
1266 "\n"
1267 "Return the fractional and integer parts of x. Both results carry the sign\n"
1268 "of x and are floats.");
1270 /* A decent logarithm is easy to compute even for huge longs, but libm can't
1271 do that by itself -- loghelper can. func is log or log10, and name is
1272 "log" or "log10". Note that overflow isn't possible: a long can contain
1273 no more than INT_MAX * SHIFT bits, so has value certainly less than
1274 2**(2**64 * 2**16) == 2**2**80, and log2 of that is 2**80, which is
1275 small enough to fit in an IEEE single. log and log10 are even smaller.
1278 static PyObject*
1279 loghelper(PyObject* arg, double (*func)(double), char *funcname)
1281 /* If it is long, do it ourselves. */
1282 if (PyLong_Check(arg)) {
1283 double x;
1284 int e;
1285 x = _PyLong_AsScaledDouble(arg, &e);
1286 if (x <= 0.0) {
1287 PyErr_SetString(PyExc_ValueError,
1288 "math domain error");
1289 return NULL;
1291 /* Value is ~= x * 2**(e*PyLong_SHIFT), so the log ~=
1292 log(x) + log(2) * e * PyLong_SHIFT.
1293 CAUTION: e*PyLong_SHIFT may overflow using int arithmetic,
1294 so force use of double. */
1295 x = func(x) + (e * (double)PyLong_SHIFT) * func(2.0);
1296 return PyFloat_FromDouble(x);
1299 /* Else let libm handle it by itself. */
1300 return math_1(arg, func, 0);
1303 static PyObject *
1304 math_log(PyObject *self, PyObject *args)
1306 PyObject *arg;
1307 PyObject *base = NULL;
1308 PyObject *num, *den;
1309 PyObject *ans;
1311 if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base))
1312 return NULL;
1314 num = loghelper(arg, m_log, "log");
1315 if (num == NULL || base == NULL)
1316 return num;
1318 den = loghelper(base, m_log, "log");
1319 if (den == NULL) {
1320 Py_DECREF(num);
1321 return NULL;
1324 ans = PyNumber_Divide(num, den);
1325 Py_DECREF(num);
1326 Py_DECREF(den);
1327 return ans;
1330 PyDoc_STRVAR(math_log_doc,
1331 "log(x[, base])\n\n\
1332 Return the logarithm of x to the given base.\n\
1333 If the base not specified, returns the natural logarithm (base e) of x.");
1335 static PyObject *
1336 math_log10(PyObject *self, PyObject *arg)
1338 return loghelper(arg, m_log10, "log10");
1341 PyDoc_STRVAR(math_log10_doc,
1342 "log10(x)\n\nReturn the base 10 logarithm of x.");
1344 static PyObject *
1345 math_fmod(PyObject *self, PyObject *args)
1347 PyObject *ox, *oy;
1348 double r, x, y;
1349 if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy))
1350 return NULL;
1351 x = PyFloat_AsDouble(ox);
1352 y = PyFloat_AsDouble(oy);
1353 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1354 return NULL;
1355 /* fmod(x, +/-Inf) returns x for finite x. */
1356 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
1357 return PyFloat_FromDouble(x);
1358 errno = 0;
1359 PyFPE_START_PROTECT("in math_fmod", return 0);
1360 r = fmod(x, y);
1361 PyFPE_END_PROTECT(r);
1362 if (Py_IS_NAN(r)) {
1363 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1364 errno = EDOM;
1365 else
1366 errno = 0;
1368 if (errno && is_error(r))
1369 return NULL;
1370 else
1371 return PyFloat_FromDouble(r);
1374 PyDoc_STRVAR(math_fmod_doc,
1375 "fmod(x, y)\n\nReturn fmod(x, y), according to platform C."
1376 " x % y may differ.");
1378 static PyObject *
1379 math_hypot(PyObject *self, PyObject *args)
1381 PyObject *ox, *oy;
1382 double r, x, y;
1383 if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy))
1384 return NULL;
1385 x = PyFloat_AsDouble(ox);
1386 y = PyFloat_AsDouble(oy);
1387 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1388 return NULL;
1389 /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */
1390 if (Py_IS_INFINITY(x))
1391 return PyFloat_FromDouble(fabs(x));
1392 if (Py_IS_INFINITY(y))
1393 return PyFloat_FromDouble(fabs(y));
1394 errno = 0;
1395 PyFPE_START_PROTECT("in math_hypot", return 0);
1396 r = hypot(x, y);
1397 PyFPE_END_PROTECT(r);
1398 if (Py_IS_NAN(r)) {
1399 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1400 errno = EDOM;
1401 else
1402 errno = 0;
1404 else if (Py_IS_INFINITY(r)) {
1405 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
1406 errno = ERANGE;
1407 else
1408 errno = 0;
1410 if (errno && is_error(r))
1411 return NULL;
1412 else
1413 return PyFloat_FromDouble(r);
1416 PyDoc_STRVAR(math_hypot_doc,
1417 "hypot(x, y)\n\nReturn the Euclidean distance, sqrt(x*x + y*y).");
1419 /* pow can't use math_2, but needs its own wrapper: the problem is
1420 that an infinite result can arise either as a result of overflow
1421 (in which case OverflowError should be raised) or as a result of
1422 e.g. 0.**-5. (for which ValueError needs to be raised.)
1425 static PyObject *
1426 math_pow(PyObject *self, PyObject *args)
1428 PyObject *ox, *oy;
1429 double r, x, y;
1430 int odd_y;
1432 if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy))
1433 return NULL;
1434 x = PyFloat_AsDouble(ox);
1435 y = PyFloat_AsDouble(oy);
1436 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1437 return NULL;
1439 /* deal directly with IEEE specials, to cope with problems on various
1440 platforms whose semantics don't exactly match C99 */
1441 r = 0.; /* silence compiler warning */
1442 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
1443 errno = 0;
1444 if (Py_IS_NAN(x))
1445 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
1446 else if (Py_IS_NAN(y))
1447 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
1448 else if (Py_IS_INFINITY(x)) {
1449 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
1450 if (y > 0.)
1451 r = odd_y ? x : fabs(x);
1452 else if (y == 0.)
1453 r = 1.;
1454 else /* y < 0. */
1455 r = odd_y ? copysign(0., x) : 0.;
1457 else if (Py_IS_INFINITY(y)) {
1458 if (fabs(x) == 1.0)
1459 r = 1.;
1460 else if (y > 0. && fabs(x) > 1.0)
1461 r = y;
1462 else if (y < 0. && fabs(x) < 1.0) {
1463 r = -y; /* result is +inf */
1464 if (x == 0.) /* 0**-inf: divide-by-zero */
1465 errno = EDOM;
1467 else
1468 r = 0.;
1471 else {
1472 /* let libm handle finite**finite */
1473 errno = 0;
1474 PyFPE_START_PROTECT("in math_pow", return 0);
1475 r = pow(x, y);
1476 PyFPE_END_PROTECT(r);
1477 /* a NaN result should arise only from (-ve)**(finite
1478 non-integer); in this case we want to raise ValueError. */
1479 if (!Py_IS_FINITE(r)) {
1480 if (Py_IS_NAN(r)) {
1481 errno = EDOM;
1484 an infinite result here arises either from:
1485 (A) (+/-0.)**negative (-> divide-by-zero)
1486 (B) overflow of x**y with x and y finite
1488 else if (Py_IS_INFINITY(r)) {
1489 if (x == 0.)
1490 errno = EDOM;
1491 else
1492 errno = ERANGE;
1497 if (errno && is_error(r))
1498 return NULL;
1499 else
1500 return PyFloat_FromDouble(r);
1503 PyDoc_STRVAR(math_pow_doc,
1504 "pow(x, y)\n\nReturn x**y (x to the power of y).");
1506 static const double degToRad = Py_MATH_PI / 180.0;
1507 static const double radToDeg = 180.0 / Py_MATH_PI;
1509 static PyObject *
1510 math_degrees(PyObject *self, PyObject *arg)
1512 double x = PyFloat_AsDouble(arg);
1513 if (x == -1.0 && PyErr_Occurred())
1514 return NULL;
1515 return PyFloat_FromDouble(x * radToDeg);
1518 PyDoc_STRVAR(math_degrees_doc,
1519 "degrees(x)\n\n\
1520 Convert angle x from radians to degrees.");
1522 static PyObject *
1523 math_radians(PyObject *self, PyObject *arg)
1525 double x = PyFloat_AsDouble(arg);
1526 if (x == -1.0 && PyErr_Occurred())
1527 return NULL;
1528 return PyFloat_FromDouble(x * degToRad);
1531 PyDoc_STRVAR(math_radians_doc,
1532 "radians(x)\n\n\
1533 Convert angle x from degrees to radians.");
1535 static PyObject *
1536 math_isnan(PyObject *self, PyObject *arg)
1538 double x = PyFloat_AsDouble(arg);
1539 if (x == -1.0 && PyErr_Occurred())
1540 return NULL;
1541 return PyBool_FromLong((long)Py_IS_NAN(x));
1544 PyDoc_STRVAR(math_isnan_doc,
1545 "isnan(x) -> bool\n\n\
1546 Check if float x is not a number (NaN).");
1548 static PyObject *
1549 math_isinf(PyObject *self, PyObject *arg)
1551 double x = PyFloat_AsDouble(arg);
1552 if (x == -1.0 && PyErr_Occurred())
1553 return NULL;
1554 return PyBool_FromLong((long)Py_IS_INFINITY(x));
1557 PyDoc_STRVAR(math_isinf_doc,
1558 "isinf(x) -> bool\n\n\
1559 Check if float x is infinite (positive or negative).");
1561 static PyMethodDef math_methods[] = {
1562 {"acos", math_acos, METH_O, math_acos_doc},
1563 {"acosh", math_acosh, METH_O, math_acosh_doc},
1564 {"asin", math_asin, METH_O, math_asin_doc},
1565 {"asinh", math_asinh, METH_O, math_asinh_doc},
1566 {"atan", math_atan, METH_O, math_atan_doc},
1567 {"atan2", math_atan2, METH_VARARGS, math_atan2_doc},
1568 {"atanh", math_atanh, METH_O, math_atanh_doc},
1569 {"ceil", math_ceil, METH_O, math_ceil_doc},
1570 {"copysign", math_copysign, METH_VARARGS, math_copysign_doc},
1571 {"cos", math_cos, METH_O, math_cos_doc},
1572 {"cosh", math_cosh, METH_O, math_cosh_doc},
1573 {"degrees", math_degrees, METH_O, math_degrees_doc},
1574 {"erf", math_erf, METH_O, math_erf_doc},
1575 {"erfc", math_erfc, METH_O, math_erfc_doc},
1576 {"exp", math_exp, METH_O, math_exp_doc},
1577 {"expm1", math_expm1, METH_O, math_expm1_doc},
1578 {"fabs", math_fabs, METH_O, math_fabs_doc},
1579 {"factorial", math_factorial, METH_O, math_factorial_doc},
1580 {"floor", math_floor, METH_O, math_floor_doc},
1581 {"fmod", math_fmod, METH_VARARGS, math_fmod_doc},
1582 {"frexp", math_frexp, METH_O, math_frexp_doc},
1583 {"fsum", math_fsum, METH_O, math_fsum_doc},
1584 {"gamma", math_gamma, METH_O, math_gamma_doc},
1585 {"hypot", math_hypot, METH_VARARGS, math_hypot_doc},
1586 {"isinf", math_isinf, METH_O, math_isinf_doc},
1587 {"isnan", math_isnan, METH_O, math_isnan_doc},
1588 {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc},
1589 {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
1590 {"log", math_log, METH_VARARGS, math_log_doc},
1591 {"log1p", math_log1p, METH_O, math_log1p_doc},
1592 {"log10", math_log10, METH_O, math_log10_doc},
1593 {"modf", math_modf, METH_O, math_modf_doc},
1594 {"pow", math_pow, METH_VARARGS, math_pow_doc},
1595 {"radians", math_radians, METH_O, math_radians_doc},
1596 {"sin", math_sin, METH_O, math_sin_doc},
1597 {"sinh", math_sinh, METH_O, math_sinh_doc},
1598 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
1599 {"tan", math_tan, METH_O, math_tan_doc},
1600 {"tanh", math_tanh, METH_O, math_tanh_doc},
1601 {"trunc", math_trunc, METH_O, math_trunc_doc},
1602 {NULL, NULL} /* sentinel */
1606 PyDoc_STRVAR(module_doc,
1607 "This module is always available. It provides access to the\n"
1608 "mathematical functions defined by the C standard.");
1610 PyMODINIT_FUNC
1611 initmath(void)
1613 PyObject *m;
1615 m = Py_InitModule3("math", math_methods, module_doc);
1616 if (m == NULL)
1617 goto finally;
1619 PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
1620 PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
1622 finally:
1623 return;