Home | History | Annotate | Download | only in Modules
      1 /* Math module -- standard C math library functions, pi and e */
      2 
      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.
      8 
      9 These are the "spirit of 754" rules:
     10 
     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).
     14 
     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).
     18 
     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.
     26 
     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.
     30 
     31 And these are what Python has historically /tried/ to do (but not
     32 always successfully, as platform libm behavior varies a lot):
     33 
     34 For #1, raise OverflowError.
     35 
     36 For #2, return a zero (with the appropriate sign if that happens by
     37 accident ;-)).
     38 
     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.
     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 
     55 #include "Python.h"
     56 #include "_math.h"
     57 
     58 /*
     59    sin(pi*x), giving accurate results for all finite x (especially x
     60    integral or close to an integer).  This is here for use in the
     61    reflection formula for the gamma function.  It conforms to IEEE
     62    754-2008 for finite arguments, but not for infinities or nans.
     63 */
     64 
     65 static const double pi = 3.141592653589793238462643383279502884197;
     66 static const double sqrtpi = 1.772453850905516027298167483341145182798;
     67 static const double logpi = 1.144729885849400174143427351353058711647;
     68 
     69 static double
     70 sinpi(double x)
     71 {
     72     double y, r;
     73     int n;
     74     /* this function should only ever be called for finite arguments */
     75     assert(Py_IS_FINITE(x));
     76     y = fmod(fabs(x), 2.0);
     77     n = (int)round(2.0*y);
     78     assert(0 <= n && n <= 4);
     79     switch (n) {
     80     case 0:
     81         r = sin(pi*y);
     82         break;
     83     case 1:
     84         r = cos(pi*(y-0.5));
     85         break;
     86     case 2:
     87         /* N.B. -sin(pi*(y-1.0)) is *not* equivalent: it would give
     88            -0.0 instead of 0.0 when y == 1.0. */
     89         r = sin(pi*(1.0-y));
     90         break;
     91     case 3:
     92         r = -cos(pi*(y-1.5));
     93         break;
     94     case 4:
     95         r = sin(pi*(y-2.0));
     96         break;
     97     default:
     98         assert(0);  /* should never get here */
     99         r = -1.23e200; /* silence gcc warning */
    100     }
    101     return copysign(1.0, x)*r;
    102 }
    103 
    104 /* Implementation of the real gamma function.  In extensive but non-exhaustive
    105    random tests, this function proved accurate to within <= 10 ulps across the
    106    entire float domain.  Note that accuracy may depend on the quality of the
    107    system math functions, the pow function in particular.  Special cases
    108    follow C99 annex F.  The parameters and method are tailored to platforms
    109    whose double format is the IEEE 754 binary64 format.
    110 
    111    Method: for x > 0.0 we use the Lanczos approximation with parameters N=13
    112    and g=6.024680040776729583740234375; these parameters are amongst those
    113    used by the Boost library.  Following Boost (again), we re-express the
    114    Lanczos sum as a rational function, and compute it that way.  The
    115    coefficients below were computed independently using MPFR, and have been
    116    double-checked against the coefficients in the Boost source code.
    117 
    118    For x < 0.0 we use the reflection formula.
    119 
    120    There's one minor tweak that deserves explanation: Lanczos' formula for
    121    Gamma(x) involves computing pow(x+g-0.5, x-0.5) / exp(x+g-0.5).  For many x
    122    values, x+g-0.5 can be represented exactly.  However, in cases where it
    123    can't be represented exactly the small error in x+g-0.5 can be magnified
    124    significantly by the pow and exp calls, especially for large x.  A cheap
    125    correction is to multiply by (1 + e*g/(x+g-0.5)), where e is the error
    126    involved in the computation of x+g-0.5 (that is, e = computed value of
    127    x+g-0.5 - exact value of x+g-0.5).  Here's the proof:
    128 
    129    Correction factor
    130    -----------------
    131    Write x+g-0.5 = y-e, where y is exactly representable as an IEEE 754
    132    double, and e is tiny.  Then:
    133 
    134      pow(x+g-0.5,x-0.5)/exp(x+g-0.5) = pow(y-e, x-0.5)/exp(y-e)
    135      = pow(y, x-0.5)/exp(y) * C,
    136 
    137    where the correction_factor C is given by
    138 
    139      C = pow(1-e/y, x-0.5) * exp(e)
    140 
    141    Since e is tiny, pow(1-e/y, x-0.5) ~ 1-(x-0.5)*e/y, and exp(x) ~ 1+e, so:
    142 
    143      C ~ (1-(x-0.5)*e/y) * (1+e) ~ 1 + e*(y-(x-0.5))/y
    144 
    145    But y-(x-0.5) = g+e, and g+e ~ g.  So we get C ~ 1 + e*g/y, and
    146 
    147      pow(x+g-0.5,x-0.5)/exp(x+g-0.5) ~ pow(y, x-0.5)/exp(y) * (1 + e*g/y),
    148 
    149    Note that for accuracy, when computing r*C it's better to do
    150 
    151      r + e*g/y*r;
    152 
    153    than
    154 
    155      r * (1 + e*g/y);
    156 
    157    since the addition in the latter throws away most of the bits of
    158    information in e*g/y.
    159 */
    160 
    161 #define LANCZOS_N 13
    162 static const double lanczos_g = 6.024680040776729583740234375;
    163 static const double lanczos_g_minus_half = 5.524680040776729583740234375;
    164 static const double lanczos_num_coeffs[LANCZOS_N] = {
    165     23531376880.410759688572007674451636754734846804940,
    166     42919803642.649098768957899047001988850926355848959,
    167     35711959237.355668049440185451547166705960488635843,
    168     17921034426.037209699919755754458931112671403265390,
    169     6039542586.3520280050642916443072979210699388420708,
    170     1439720407.3117216736632230727949123939715485786772,
    171     248874557.86205415651146038641322942321632125127801,
    172     31426415.585400194380614231628318205362874684987640,
    173     2876370.6289353724412254090516208496135991145378768,
    174     186056.26539522349504029498971604569928220784236328,
    175     8071.6720023658162106380029022722506138218516325024,
    176     210.82427775157934587250973392071336271166969580291,
    177     2.5066282746310002701649081771338373386264310793408
    178 };
    179 
    180 /* denominator is x*(x+1)*...*(x+LANCZOS_N-2) */
    181 static const double lanczos_den_coeffs[LANCZOS_N] = {
    182     0.0, 39916800.0, 120543840.0, 150917976.0, 105258076.0, 45995730.0,
    183     13339535.0, 2637558.0, 357423.0, 32670.0, 1925.0, 66.0, 1.0};
    184 
    185 /* gamma values for small positive integers, 1 though NGAMMA_INTEGRAL */
    186 #define NGAMMA_INTEGRAL 23
    187 static const double gamma_integral[NGAMMA_INTEGRAL] = {
    188     1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0,
    189     3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0,
    190     1307674368000.0, 20922789888000.0, 355687428096000.0,
    191     6402373705728000.0, 121645100408832000.0, 2432902008176640000.0,
    192     51090942171709440000.0, 1124000727777607680000.0,
    193 };
    194 
    195 /* Lanczos' sum L_g(x), for positive x */
    196 
    197 static double
    198 lanczos_sum(double x)
    199 {
    200     double num = 0.0, den = 0.0;
    201     int i;
    202     assert(x > 0.0);
    203     /* evaluate the rational function lanczos_sum(x).  For large
    204        x, the obvious algorithm risks overflow, so we instead
    205        rescale the denominator and numerator of the rational
    206        function by x**(1-LANCZOS_N) and treat this as a
    207        rational function in 1/x.  This also reduces the error for
    208        larger x values.  The choice of cutoff point (5.0 below) is
    209        somewhat arbitrary; in tests, smaller cutoff values than
    210        this resulted in lower accuracy. */
    211     if (x < 5.0) {
    212         for (i = LANCZOS_N; --i >= 0; ) {
    213             num = num * x + lanczos_num_coeffs[i];
    214             den = den * x + lanczos_den_coeffs[i];
    215         }
    216     }
    217     else {
    218         for (i = 0; i < LANCZOS_N; i++) {
    219             num = num / x + lanczos_num_coeffs[i];
    220             den = den / x + lanczos_den_coeffs[i];
    221         }
    222     }
    223     return num/den;
    224 }
    225 
    226 /* Constant for +infinity, generated in the same way as float('inf'). */
    227 
    228 static double
    229 m_inf(void)
    230 {
    231 #ifndef PY_NO_SHORT_FLOAT_REPR
    232     return _Py_dg_infinity(0);
    233 #else
    234     return Py_HUGE_VAL;
    235 #endif
    236 }
    237 
    238 /* Constant nan value, generated in the same way as float('nan'). */
    239 /* We don't currently assume that Py_NAN is defined everywhere. */
    240 
    241 #if !defined(PY_NO_SHORT_FLOAT_REPR) || defined(Py_NAN)
    242 
    243 static double
    244 m_nan(void)
    245 {
    246 #ifndef PY_NO_SHORT_FLOAT_REPR
    247     return _Py_dg_stdnan(0);
    248 #else
    249     return Py_NAN;
    250 #endif
    251 }
    252 
    253 #endif
    254 
    255 static double
    256 m_tgamma(double x)
    257 {
    258     double absx, r, y, z, sqrtpow;
    259 
    260     /* special cases */
    261     if (!Py_IS_FINITE(x)) {
    262         if (Py_IS_NAN(x) || x > 0.0)
    263             return x;  /* tgamma(nan) = nan, tgamma(inf) = inf */
    264         else {
    265             errno = EDOM;
    266             return Py_NAN;  /* tgamma(-inf) = nan, invalid */
    267         }
    268     }
    269     if (x == 0.0) {
    270         errno = EDOM;
    271         /* tgamma(+-0.0) = +-inf, divide-by-zero */
    272         return copysign(Py_HUGE_VAL, x);
    273     }
    274 
    275     /* integer arguments */
    276     if (x == floor(x)) {
    277         if (x < 0.0) {
    278             errno = EDOM;  /* tgamma(n) = nan, invalid for */
    279             return Py_NAN; /* negative integers n */
    280         }
    281         if (x <= NGAMMA_INTEGRAL)
    282             return gamma_integral[(int)x - 1];
    283     }
    284     absx = fabs(x);
    285 
    286     /* tiny arguments:  tgamma(x) ~ 1/x for x near 0 */
    287     if (absx < 1e-20) {
    288         r = 1.0/x;
    289         if (Py_IS_INFINITY(r))
    290             errno = ERANGE;
    291         return r;
    292     }
    293 
    294     /* large arguments: assuming IEEE 754 doubles, tgamma(x) overflows for
    295        x > 200, and underflows to +-0.0 for x < -200, not a negative
    296        integer. */
    297     if (absx > 200.0) {
    298         if (x < 0.0) {
    299             return 0.0/sinpi(x);
    300         }
    301         else {
    302             errno = ERANGE;
    303             return Py_HUGE_VAL;
    304         }
    305     }
    306 
    307     y = absx + lanczos_g_minus_half;
    308     /* compute error in sum */
    309     if (absx > lanczos_g_minus_half) {
    310         /* note: the correction can be foiled by an optimizing
    311            compiler that (incorrectly) thinks that an expression like
    312            a + b - a - b can be optimized to 0.0.  This shouldn't
    313            happen in a standards-conforming compiler. */
    314         double q = y - absx;
    315         z = q - lanczos_g_minus_half;
    316     }
    317     else {
    318         double q = y - lanczos_g_minus_half;
    319         z = q - absx;
    320     }
    321     z = z * lanczos_g / y;
    322     if (x < 0.0) {
    323         r = -pi / sinpi(absx) / absx * exp(y) / lanczos_sum(absx);
    324         r -= z * r;
    325         if (absx < 140.0) {
    326             r /= pow(y, absx - 0.5);
    327         }
    328         else {
    329             sqrtpow = pow(y, absx / 2.0 - 0.25);
    330             r /= sqrtpow;
    331             r /= sqrtpow;
    332         }
    333     }
    334     else {
    335         r = lanczos_sum(absx) / exp(y);
    336         r += z * r;
    337         if (absx < 140.0) {
    338             r *= pow(y, absx - 0.5);
    339         }
    340         else {
    341             sqrtpow = pow(y, absx / 2.0 - 0.25);
    342             r *= sqrtpow;
    343             r *= sqrtpow;
    344         }
    345     }
    346     if (Py_IS_INFINITY(r))
    347         errno = ERANGE;
    348     return r;
    349 }
    350 
    351 /*
    352    lgamma:  natural log of the absolute value of the Gamma function.
    353    For large arguments, Lanczos' formula works extremely well here.
    354 */
    355 
    356 static double
    357 m_lgamma(double x)
    358 {
    359     double r, absx;
    360 
    361     /* special cases */
    362     if (!Py_IS_FINITE(x)) {
    363         if (Py_IS_NAN(x))
    364             return x;  /* lgamma(nan) = nan */
    365         else
    366             return Py_HUGE_VAL; /* lgamma(+-inf) = +inf */
    367     }
    368 
    369     /* integer arguments */
    370     if (x == floor(x) && x <= 2.0) {
    371         if (x <= 0.0) {
    372             errno = EDOM;  /* lgamma(n) = inf, divide-by-zero for */
    373             return Py_HUGE_VAL; /* integers n <= 0 */
    374         }
    375         else {
    376             return 0.0; /* lgamma(1) = lgamma(2) = 0.0 */
    377         }
    378     }
    379 
    380     absx = fabs(x);
    381     /* tiny arguments: lgamma(x) ~ -log(fabs(x)) for small x */
    382     if (absx < 1e-20)
    383         return -log(absx);
    384 
    385     /* Lanczos' formula.  We could save a fraction of a ulp in accuracy by
    386        having a second set of numerator coefficients for lanczos_sum that
    387        absorbed the exp(-lanczos_g) term, and throwing out the lanczos_g
    388        subtraction below; it's probably not worth it. */
    389     r = log(lanczos_sum(absx)) - lanczos_g;
    390     r += (absx - 0.5) * (log(absx + lanczos_g - 0.5) - 1);
    391     if (x < 0.0)
    392         /* Use reflection formula to get value for negative x. */
    393         r = logpi - log(fabs(sinpi(absx))) - log(absx) - r;
    394     if (Py_IS_INFINITY(r))
    395         errno = ERANGE;
    396     return r;
    397 }
    398 
    399 /*
    400    Implementations of the error function erf(x) and the complementary error
    401    function erfc(x).
    402 
    403    Method: we use a series approximation for erf for small x, and a continued
    404    fraction approximation for erfc(x) for larger x;
    405    combined with the relations erf(-x) = -erf(x) and erfc(x) = 1.0 - erf(x),
    406    this gives us erf(x) and erfc(x) for all x.
    407 
    408    The series expansion used is:
    409 
    410       erf(x) = x*exp(-x*x)/sqrt(pi) * [
    411                      2/1 + 4/3 x**2 + 8/15 x**4 + 16/105 x**6 + ...]
    412 
    413    The coefficient of x**(2k-2) here is 4**k*factorial(k)/factorial(2*k).
    414    This series converges well for smallish x, but slowly for larger x.
    415 
    416    The continued fraction expansion used is:
    417 
    418       erfc(x) = x*exp(-x*x)/sqrt(pi) * [1/(0.5 + x**2 -) 0.5/(2.5 + x**2 - )
    419                               3.0/(4.5 + x**2 - ) 7.5/(6.5 + x**2 - ) ...]
    420 
    421    after the first term, the general term has the form:
    422 
    423       k*(k-0.5)/(2*k+0.5 + x**2 - ...).
    424 
    425    This expansion converges fast for larger x, but convergence becomes
    426    infinitely slow as x approaches 0.0.  The (somewhat naive) continued
    427    fraction evaluation algorithm used below also risks overflow for large x;
    428    but for large x, erfc(x) == 0.0 to within machine precision.  (For
    429    example, erfc(30.0) is approximately 2.56e-393).
    430 
    431    Parameters: use series expansion for abs(x) < ERF_SERIES_CUTOFF and
    432    continued fraction expansion for ERF_SERIES_CUTOFF <= abs(x) <
    433    ERFC_CONTFRAC_CUTOFF.  ERFC_SERIES_TERMS and ERFC_CONTFRAC_TERMS are the
    434    numbers of terms to use for the relevant expansions.  */
    435 
    436 #define ERF_SERIES_CUTOFF 1.5
    437 #define ERF_SERIES_TERMS 25
    438 #define ERFC_CONTFRAC_CUTOFF 30.0
    439 #define ERFC_CONTFRAC_TERMS 50
    440 
    441 /*
    442    Error function, via power series.
    443 
    444    Given a finite float x, return an approximation to erf(x).
    445    Converges reasonably fast for small x.
    446 */
    447 
    448 static double
    449 m_erf_series(double x)
    450 {
    451     double x2, acc, fk, result;
    452     int i, saved_errno;
    453 
    454     x2 = x * x;
    455     acc = 0.0;
    456     fk = (double)ERF_SERIES_TERMS + 0.5;
    457     for (i = 0; i < ERF_SERIES_TERMS; i++) {
    458         acc = 2.0 + x2 * acc / fk;
    459         fk -= 1.0;
    460     }
    461     /* Make sure the exp call doesn't affect errno;
    462        see m_erfc_contfrac for more. */
    463     saved_errno = errno;
    464     result = acc * x * exp(-x2) / sqrtpi;
    465     errno = saved_errno;
    466     return result;
    467 }
    468 
    469 /*
    470    Complementary error function, via continued fraction expansion.
    471 
    472    Given a positive float x, return an approximation to erfc(x).  Converges
    473    reasonably fast for x large (say, x > 2.0), and should be safe from
    474    overflow if x and nterms are not too large.  On an IEEE 754 machine, with x
    475    <= 30.0, we're safe up to nterms = 100.  For x >= 30.0, erfc(x) is smaller
    476    than the smallest representable nonzero float.  */
    477 
    478 static double
    479 m_erfc_contfrac(double x)
    480 {
    481     double x2, a, da, p, p_last, q, q_last, b, result;
    482     int i, saved_errno;
    483 
    484     if (x >= ERFC_CONTFRAC_CUTOFF)
    485         return 0.0;
    486 
    487     x2 = x*x;
    488     a = 0.0;
    489     da = 0.5;
    490     p = 1.0; p_last = 0.0;
    491     q = da + x2; q_last = 1.0;
    492     for (i = 0; i < ERFC_CONTFRAC_TERMS; i++) {
    493         double temp;
    494         a += da;
    495         da += 2.0;
    496         b = da + x2;
    497         temp = p; p = b*p - a*p_last; p_last = temp;
    498         temp = q; q = b*q - a*q_last; q_last = temp;
    499     }
    500     /* Issue #8986: On some platforms, exp sets errno on underflow to zero;
    501        save the current errno value so that we can restore it later. */
    502     saved_errno = errno;
    503     result = p / q * x * exp(-x2) / sqrtpi;
    504     errno = saved_errno;
    505     return result;
    506 }
    507 
    508 /* Error function erf(x), for general x */
    509 
    510 static double
    511 m_erf(double x)
    512 {
    513     double absx, cf;
    514 
    515     if (Py_IS_NAN(x))
    516         return x;
    517     absx = fabs(x);
    518     if (absx < ERF_SERIES_CUTOFF)
    519         return m_erf_series(x);
    520     else {
    521         cf = m_erfc_contfrac(absx);
    522         return x > 0.0 ? 1.0 - cf : cf - 1.0;
    523     }
    524 }
    525 
    526 /* Complementary error function erfc(x), for general x. */
    527 
    528 static double
    529 m_erfc(double x)
    530 {
    531     double absx, cf;
    532 
    533     if (Py_IS_NAN(x))
    534         return x;
    535     absx = fabs(x);
    536     if (absx < ERF_SERIES_CUTOFF)
    537         return 1.0 - m_erf_series(x);
    538     else {
    539         cf = m_erfc_contfrac(absx);
    540         return x > 0.0 ? cf : 2.0 - cf;
    541     }
    542 }
    543 
    544 /*
    545    wrapper for atan2 that deals directly with special cases before
    546    delegating to the platform libm for the remaining cases.  This
    547    is necessary to get consistent behaviour across platforms.
    548    Windows, FreeBSD and alpha Tru64 are amongst platforms that don't
    549    always follow C99.
    550 */
    551 
    552 static double
    553 m_atan2(double y, double x)
    554 {
    555     if (Py_IS_NAN(x) || Py_IS_NAN(y))
    556         return Py_NAN;
    557     if (Py_IS_INFINITY(y)) {
    558         if (Py_IS_INFINITY(x)) {
    559             if (copysign(1., x) == 1.)
    560                 /* atan2(+-inf, +inf) == +-pi/4 */
    561                 return copysign(0.25*Py_MATH_PI, y);
    562             else
    563                 /* atan2(+-inf, -inf) == +-pi*3/4 */
    564                 return copysign(0.75*Py_MATH_PI, y);
    565         }
    566         /* atan2(+-inf, x) == +-pi/2 for finite x */
    567         return copysign(0.5*Py_MATH_PI, y);
    568     }
    569     if (Py_IS_INFINITY(x) || y == 0.) {
    570         if (copysign(1., x) == 1.)
    571             /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */
    572             return copysign(0., y);
    573         else
    574             /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */
    575             return copysign(Py_MATH_PI, y);
    576     }
    577     return atan2(y, x);
    578 }
    579 
    580 /*
    581     Various platforms (Solaris, OpenBSD) do nonstandard things for log(0),
    582     log(-ve), log(NaN).  Here are wrappers for log and log10 that deal with
    583     special values directly, passing positive non-special values through to
    584     the system log/log10.
    585  */
    586 
    587 static double
    588 m_log(double x)
    589 {
    590     if (Py_IS_FINITE(x)) {
    591         if (x > 0.0)
    592             return log(x);
    593         errno = EDOM;
    594         if (x == 0.0)
    595             return -Py_HUGE_VAL; /* log(0) = -inf */
    596         else
    597             return Py_NAN; /* log(-ve) = nan */
    598     }
    599     else if (Py_IS_NAN(x))
    600         return x; /* log(nan) = nan */
    601     else if (x > 0.0)
    602         return x; /* log(inf) = inf */
    603     else {
    604         errno = EDOM;
    605         return Py_NAN; /* log(-inf) = nan */
    606     }
    607 }
    608 
    609 /*
    610    log2: log to base 2.
    611 
    612    Uses an algorithm that should:
    613 
    614      (a) produce exact results for powers of 2, and
    615      (b) give a monotonic log2 (for positive finite floats),
    616          assuming that the system log is monotonic.
    617 */
    618 
    619 static double
    620 m_log2(double x)
    621 {
    622     if (!Py_IS_FINITE(x)) {
    623         if (Py_IS_NAN(x))
    624             return x; /* log2(nan) = nan */
    625         else if (x > 0.0)
    626             return x; /* log2(+inf) = +inf */
    627         else {
    628             errno = EDOM;
    629             return Py_NAN; /* log2(-inf) = nan, invalid-operation */
    630         }
    631     }
    632 
    633     if (x > 0.0) {
    634 #ifdef HAVE_LOG2
    635         return log2(x);
    636 #else
    637         double m;
    638         int e;
    639         m = frexp(x, &e);
    640         /* We want log2(m * 2**e) == log(m) / log(2) + e.  Care is needed when
    641          * x is just greater than 1.0: in that case e is 1, log(m) is negative,
    642          * and we get significant cancellation error from the addition of
    643          * log(m) / log(2) to e.  The slight rewrite of the expression below
    644          * avoids this problem.
    645          */
    646         if (x >= 1.0) {
    647             return log(2.0 * m) / log(2.0) + (e - 1);
    648         }
    649         else {
    650             return log(m) / log(2.0) + e;
    651         }
    652 #endif
    653     }
    654     else if (x == 0.0) {
    655         errno = EDOM;
    656         return -Py_HUGE_VAL; /* log2(0) = -inf, divide-by-zero */
    657     }
    658     else {
    659         errno = EDOM;
    660         return Py_NAN; /* log2(-inf) = nan, invalid-operation */
    661     }
    662 }
    663 
    664 static double
    665 m_log10(double x)
    666 {
    667     if (Py_IS_FINITE(x)) {
    668         if (x > 0.0)
    669             return log10(x);
    670         errno = EDOM;
    671         if (x == 0.0)
    672             return -Py_HUGE_VAL; /* log10(0) = -inf */
    673         else
    674             return Py_NAN; /* log10(-ve) = nan */
    675     }
    676     else if (Py_IS_NAN(x))
    677         return x; /* log10(nan) = nan */
    678     else if (x > 0.0)
    679         return x; /* log10(inf) = inf */
    680     else {
    681         errno = EDOM;
    682         return Py_NAN; /* log10(-inf) = nan */
    683     }
    684 }
    685 
    686 
    687 static PyObject *
    688 math_gcd(PyObject *self, PyObject *args)
    689 {
    690     PyObject *a, *b, *g;
    691 
    692     if (!PyArg_ParseTuple(args, "OO:gcd", &a, &b))
    693         return NULL;
    694 
    695     a = PyNumber_Index(a);
    696     if (a == NULL)
    697         return NULL;
    698     b = PyNumber_Index(b);
    699     if (b == NULL) {
    700         Py_DECREF(a);
    701         return NULL;
    702     }
    703     g = _PyLong_GCD(a, b);
    704     Py_DECREF(a);
    705     Py_DECREF(b);
    706     return g;
    707 }
    708 
    709 PyDoc_STRVAR(math_gcd_doc,
    710 "gcd(x, y) -> int\n\
    711 greatest common divisor of x and y");
    712 
    713 
    714 /* Call is_error when errno != 0, and where x is the result libm
    715  * returned.  is_error will usually set up an exception and return
    716  * true (1), but may return false (0) without setting up an exception.
    717  */
    718 static int
    719 is_error(double x)
    720 {
    721     int result = 1;     /* presumption of guilt */
    722     assert(errno);      /* non-zero errno is a precondition for calling */
    723     if (errno == EDOM)
    724         PyErr_SetString(PyExc_ValueError, "math domain error");
    725 
    726     else if (errno == ERANGE) {
    727         /* ANSI C generally requires libm functions to set ERANGE
    728          * on overflow, but also generally *allows* them to set
    729          * ERANGE on underflow too.  There's no consistency about
    730          * the latter across platforms.
    731          * Alas, C99 never requires that errno be set.
    732          * Here we suppress the underflow errors (libm functions
    733          * should return a zero on underflow, and +- HUGE_VAL on
    734          * overflow, so testing the result for zero suffices to
    735          * distinguish the cases).
    736          *
    737          * On some platforms (Ubuntu/ia64) it seems that errno can be
    738          * set to ERANGE for subnormal results that do *not* underflow
    739          * to zero.  So to be safe, we'll ignore ERANGE whenever the
    740          * function result is less than one in absolute value.
    741          */
    742         if (fabs(x) < 1.0)
    743             result = 0;
    744         else
    745             PyErr_SetString(PyExc_OverflowError,
    746                             "math range error");
    747     }
    748     else
    749         /* Unexpected math error */
    750         PyErr_SetFromErrno(PyExc_ValueError);
    751     return result;
    752 }
    753 
    754 /*
    755    math_1 is used to wrap a libm function f that takes a double
    756    arguments and returns a double.
    757 
    758    The error reporting follows these rules, which are designed to do
    759    the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
    760    platforms.
    761 
    762    - a NaN result from non-NaN inputs causes ValueError to be raised
    763    - an infinite result from finite inputs causes OverflowError to be
    764      raised if can_overflow is 1, or raises ValueError if can_overflow
    765      is 0.
    766    - if the result is finite and errno == EDOM then ValueError is
    767      raised
    768    - if the result is finite and nonzero and errno == ERANGE then
    769      OverflowError is raised
    770 
    771    The last rule is used to catch overflow on platforms which follow
    772    C89 but for which HUGE_VAL is not an infinity.
    773 
    774    For the majority of one-argument functions these rules are enough
    775    to ensure that Python's functions behave as specified in 'Annex F'
    776    of the C99 standard, with the 'invalid' and 'divide-by-zero'
    777    floating-point exceptions mapping to Python's ValueError and the
    778    'overflow' floating-point exception mapping to OverflowError.
    779    math_1 only works for functions that don't have singularities *and*
    780    the possibility of overflow; fortunately, that covers everything we
    781    care about right now.
    782 */
    783 
    784 static PyObject *
    785 math_1_to_whatever(PyObject *arg, double (*func) (double),
    786                    PyObject *(*from_double_func) (double),
    787                    int can_overflow)
    788 {
    789     double x, r;
    790     x = PyFloat_AsDouble(arg);
    791     if (x == -1.0 && PyErr_Occurred())
    792         return NULL;
    793     errno = 0;
    794     PyFPE_START_PROTECT("in math_1", return 0);
    795     r = (*func)(x);
    796     PyFPE_END_PROTECT(r);
    797     if (Py_IS_NAN(r) && !Py_IS_NAN(x)) {
    798         PyErr_SetString(PyExc_ValueError,
    799                         "math domain error"); /* invalid arg */
    800         return NULL;
    801     }
    802     if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) {
    803         if (can_overflow)
    804             PyErr_SetString(PyExc_OverflowError,
    805                             "math range error"); /* overflow */
    806         else
    807             PyErr_SetString(PyExc_ValueError,
    808                             "math domain error"); /* singularity */
    809         return NULL;
    810     }
    811     if (Py_IS_FINITE(r) && errno && is_error(r))
    812         /* this branch unnecessary on most platforms */
    813         return NULL;
    814 
    815     return (*from_double_func)(r);
    816 }
    817 
    818 /* variant of math_1, to be used when the function being wrapped is known to
    819    set errno properly (that is, errno = EDOM for invalid or divide-by-zero,
    820    errno = ERANGE for overflow). */
    821 
    822 static PyObject *
    823 math_1a(PyObject *arg, double (*func) (double))
    824 {
    825     double x, r;
    826     x = PyFloat_AsDouble(arg);
    827     if (x == -1.0 && PyErr_Occurred())
    828         return NULL;
    829     errno = 0;
    830     PyFPE_START_PROTECT("in math_1a", return 0);
    831     r = (*func)(x);
    832     PyFPE_END_PROTECT(r);
    833     if (errno && is_error(r))
    834         return NULL;
    835     return PyFloat_FromDouble(r);
    836 }
    837 
    838 /*
    839    math_2 is used to wrap a libm function f that takes two double
    840    arguments and returns a double.
    841 
    842    The error reporting follows these rules, which are designed to do
    843    the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
    844    platforms.
    845 
    846    - a NaN result from non-NaN inputs causes ValueError to be raised
    847    - an infinite result from finite inputs causes OverflowError to be
    848      raised.
    849    - if the result is finite and errno == EDOM then ValueError is
    850      raised
    851    - if the result is finite and nonzero and errno == ERANGE then
    852      OverflowError is raised
    853 
    854    The last rule is used to catch overflow on platforms which follow
    855    C89 but for which HUGE_VAL is not an infinity.
    856 
    857    For most two-argument functions (copysign, fmod, hypot, atan2)
    858    these rules are enough to ensure that Python's functions behave as
    859    specified in 'Annex F' of the C99 standard, with the 'invalid' and
    860    'divide-by-zero' floating-point exceptions mapping to Python's
    861    ValueError and the 'overflow' floating-point exception mapping to
    862    OverflowError.
    863 */
    864 
    865 static PyObject *
    866 math_1(PyObject *arg, double (*func) (double), int can_overflow)
    867 {
    868     return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow);
    869 }
    870 
    871 static PyObject *
    872 math_1_to_int(PyObject *arg, double (*func) (double), int can_overflow)
    873 {
    874     return math_1_to_whatever(arg, func, PyLong_FromDouble, can_overflow);
    875 }
    876 
    877 static PyObject *
    878 math_2(PyObject *args, double (*func) (double, double), const char *funcname)
    879 {
    880     PyObject *ox, *oy;
    881     double x, y, r;
    882     if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy))
    883         return NULL;
    884     x = PyFloat_AsDouble(ox);
    885     y = PyFloat_AsDouble(oy);
    886     if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
    887         return NULL;
    888     errno = 0;
    889     PyFPE_START_PROTECT("in math_2", return 0);
    890     r = (*func)(x, y);
    891     PyFPE_END_PROTECT(r);
    892     if (Py_IS_NAN(r)) {
    893         if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
    894             errno = EDOM;
    895         else
    896             errno = 0;
    897     }
    898     else if (Py_IS_INFINITY(r)) {
    899         if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
    900             errno = ERANGE;
    901         else
    902             errno = 0;
    903     }
    904     if (errno && is_error(r))
    905         return NULL;
    906     else
    907         return PyFloat_FromDouble(r);
    908 }
    909 
    910 #define FUNC1(funcname, func, can_overflow, docstring)                  \
    911     static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
    912         return math_1(args, func, can_overflow);                            \
    913     }\
    914     PyDoc_STRVAR(math_##funcname##_doc, docstring);
    915 
    916 #define FUNC1A(funcname, func, docstring)                               \
    917     static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
    918         return math_1a(args, func);                                     \
    919     }\
    920     PyDoc_STRVAR(math_##funcname##_doc, docstring);
    921 
    922 #define FUNC2(funcname, func, docstring) \
    923     static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
    924         return math_2(args, func, #funcname); \
    925     }\
    926     PyDoc_STRVAR(math_##funcname##_doc, docstring);
    927 
    928 FUNC1(acos, acos, 0,
    929       "acos(x)\n\nReturn the arc cosine (measured in radians) of x.")
    930 FUNC1(acosh, m_acosh, 0,
    931       "acosh(x)\n\nReturn the inverse hyperbolic cosine of x.")
    932 FUNC1(asin, asin, 0,
    933       "asin(x)\n\nReturn the arc sine (measured in radians) of x.")
    934 FUNC1(asinh, m_asinh, 0,
    935       "asinh(x)\n\nReturn the inverse hyperbolic sine of x.")
    936 FUNC1(atan, atan, 0,
    937       "atan(x)\n\nReturn the arc tangent (measured in radians) of x.")
    938 FUNC2(atan2, m_atan2,
    939       "atan2(y, x)\n\nReturn the arc tangent (measured in radians) of y/x.\n"
    940       "Unlike atan(y/x), the signs of both x and y are considered.")
    941 FUNC1(atanh, m_atanh, 0,
    942       "atanh(x)\n\nReturn the inverse hyperbolic tangent of x.")
    943 
    944 static PyObject * math_ceil(PyObject *self, PyObject *number) {
    945     _Py_IDENTIFIER(__ceil__);
    946     PyObject *method, *result;
    947 
    948     method = _PyObject_LookupSpecial(number, &PyId___ceil__);
    949     if (method == NULL) {
    950         if (PyErr_Occurred())
    951             return NULL;
    952         return math_1_to_int(number, ceil, 0);
    953     }
    954     result = PyObject_CallFunctionObjArgs(method, NULL);
    955     Py_DECREF(method);
    956     return result;
    957 }
    958 
    959 PyDoc_STRVAR(math_ceil_doc,
    960              "ceil(x)\n\nReturn the ceiling of x as an Integral.\n"
    961              "This is the smallest integer >= x.");
    962 
    963 FUNC2(copysign, copysign,
    964       "copysign(x, y)\n\nReturn a float with the magnitude (absolute value) "
    965       "of x but the sign \nof y. On platforms that support signed zeros, "
    966       "copysign(1.0, -0.0) \nreturns -1.0.\n")
    967 FUNC1(cos, cos, 0,
    968       "cos(x)\n\nReturn the cosine of x (measured in radians).")
    969 FUNC1(cosh, cosh, 1,
    970       "cosh(x)\n\nReturn the hyperbolic cosine of x.")
    971 FUNC1A(erf, m_erf,
    972        "erf(x)\n\nError function at x.")
    973 FUNC1A(erfc, m_erfc,
    974        "erfc(x)\n\nComplementary error function at x.")
    975 FUNC1(exp, exp, 1,
    976       "exp(x)\n\nReturn e raised to the power of x.")
    977 FUNC1(expm1, m_expm1, 1,
    978       "expm1(x)\n\nReturn exp(x)-1.\n"
    979       "This function avoids the loss of precision involved in the direct "
    980       "evaluation of exp(x)-1 for small x.")
    981 FUNC1(fabs, fabs, 0,
    982       "fabs(x)\n\nReturn the absolute value of the float x.")
    983 
    984 static PyObject * math_floor(PyObject *self, PyObject *number) {
    985     _Py_IDENTIFIER(__floor__);
    986     PyObject *method, *result;
    987 
    988     method = _PyObject_LookupSpecial(number, &PyId___floor__);
    989     if (method == NULL) {
    990         if (PyErr_Occurred())
    991             return NULL;
    992         return math_1_to_int(number, floor, 0);
    993     }
    994     result = PyObject_CallFunctionObjArgs(method, NULL);
    995     Py_DECREF(method);
    996     return result;
    997 }
    998 
    999 PyDoc_STRVAR(math_floor_doc,
   1000              "floor(x)\n\nReturn the floor of x as an Integral.\n"
   1001              "This is the largest integer <= x.");
   1002 
   1003 FUNC1A(gamma, m_tgamma,
   1004       "gamma(x)\n\nGamma function at x.")
   1005 FUNC1A(lgamma, m_lgamma,
   1006       "lgamma(x)\n\nNatural logarithm of absolute value of Gamma function at x.")
   1007 FUNC1(log1p, m_log1p, 0,
   1008       "log1p(x)\n\nReturn the natural logarithm of 1+x (base e).\n"
   1009       "The result is computed in a way which is accurate for x near zero.")
   1010 FUNC1(sin, sin, 0,
   1011       "sin(x)\n\nReturn the sine of x (measured in radians).")
   1012 FUNC1(sinh, sinh, 1,
   1013       "sinh(x)\n\nReturn the hyperbolic sine of x.")
   1014 FUNC1(sqrt, sqrt, 0,
   1015       "sqrt(x)\n\nReturn the square root of x.")
   1016 FUNC1(tan, tan, 0,
   1017       "tan(x)\n\nReturn the tangent of x (measured in radians).")
   1018 FUNC1(tanh, tanh, 0,
   1019       "tanh(x)\n\nReturn the hyperbolic tangent of x.")
   1020 
   1021 /* Precision summation function as msum() by Raymond Hettinger in
   1022    <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
   1023    enhanced with the exact partials sum and roundoff from Mark
   1024    Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
   1025    See those links for more details, proofs and other references.
   1026 
   1027    Note 1: IEEE 754R floating point semantics are assumed,
   1028    but the current implementation does not re-establish special
   1029    value semantics across iterations (i.e. handling -Inf + Inf).
   1030 
   1031    Note 2:  No provision is made for intermediate overflow handling;
   1032    therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
   1033    sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
   1034    overflow of the first partial sum.
   1035 
   1036    Note 3: The intermediate values lo, yr, and hi are declared volatile so
   1037    aggressive compilers won't algebraically reduce lo to always be exactly 0.0.
   1038    Also, the volatile declaration forces the values to be stored in memory as
   1039    regular doubles instead of extended long precision (80-bit) values.  This
   1040    prevents double rounding because any addition or subtraction of two doubles
   1041    can be resolved exactly into double-sized hi and lo values.  As long as the
   1042    hi value gets forced into a double before yr and lo are computed, the extra
   1043    bits in downstream extended precision operations (x87 for example) will be
   1044    exactly zero and therefore can be losslessly stored back into a double,
   1045    thereby preventing double rounding.
   1046 
   1047    Note 4: A similar implementation is in Modules/cmathmodule.c.
   1048    Be sure to update both when making changes.
   1049 
   1050    Note 5: The signature of math.fsum() differs from builtins.sum()
   1051    because the start argument doesn't make sense in the context of
   1052    accurate summation.  Since the partials table is collapsed before
   1053    returning a result, sum(seq2, start=sum(seq1)) may not equal the
   1054    accurate result returned by sum(itertools.chain(seq1, seq2)).
   1055 */
   1056 
   1057 #define NUM_PARTIALS  32  /* initial partials array size, on stack */
   1058 
   1059 /* Extend the partials array p[] by doubling its size. */
   1060 static int                          /* non-zero on error */
   1061 _fsum_realloc(double **p_ptr, Py_ssize_t  n,
   1062              double  *ps,    Py_ssize_t *m_ptr)
   1063 {
   1064     void *v = NULL;
   1065     Py_ssize_t m = *m_ptr;
   1066 
   1067     m += m;  /* double */
   1068     if (n < m && (size_t)m < ((size_t)PY_SSIZE_T_MAX / sizeof(double))) {
   1069         double *p = *p_ptr;
   1070         if (p == ps) {
   1071             v = PyMem_Malloc(sizeof(double) * m);
   1072             if (v != NULL)
   1073                 memcpy(v, ps, sizeof(double) * n);
   1074         }
   1075         else
   1076             v = PyMem_Realloc(p, sizeof(double) * m);
   1077     }
   1078     if (v == NULL) {        /* size overflow or no memory */
   1079         PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
   1080         return 1;
   1081     }
   1082     *p_ptr = (double*) v;
   1083     *m_ptr = m;
   1084     return 0;
   1085 }
   1086 
   1087 /* Full precision summation of a sequence of floats.
   1088 
   1089    def msum(iterable):
   1090        partials = []  # sorted, non-overlapping partial sums
   1091        for x in iterable:
   1092            i = 0
   1093            for y in partials:
   1094                if abs(x) < abs(y):
   1095                    x, y = y, x
   1096                hi = x + y
   1097                lo = y - (hi - x)
   1098                if lo:
   1099                    partials[i] = lo
   1100                    i += 1
   1101                x = hi
   1102            partials[i:] = [x]
   1103        return sum_exact(partials)
   1104 
   1105    Rounded x+y stored in hi with the roundoff stored in lo.  Together hi+lo
   1106    are exactly equal to x+y.  The inner loop applies hi/lo summation to each
   1107    partial so that the list of partial sums remains exact.
   1108 
   1109    Sum_exact() adds the partial sums exactly and correctly rounds the final
   1110    result (using the round-half-to-even rule).  The items in partials remain
   1111    non-zero, non-special, non-overlapping and strictly increasing in
   1112    magnitude, but possibly not all having the same sign.
   1113 
   1114    Depends on IEEE 754 arithmetic guarantees and half-even rounding.
   1115 */
   1116 
   1117 static PyObject*
   1118 math_fsum(PyObject *self, PyObject *seq)
   1119 {
   1120     PyObject *item, *iter, *sum = NULL;
   1121     Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
   1122     double x, y, t, ps[NUM_PARTIALS], *p = ps;
   1123     double xsave, special_sum = 0.0, inf_sum = 0.0;
   1124     volatile double hi, yr, lo;
   1125 
   1126     iter = PyObject_GetIter(seq);
   1127     if (iter == NULL)
   1128         return NULL;
   1129 
   1130     PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL)
   1131 
   1132     for(;;) {           /* for x in iterable */
   1133         assert(0 <= n && n <= m);
   1134         assert((m == NUM_PARTIALS && p == ps) ||
   1135                (m >  NUM_PARTIALS && p != NULL));
   1136 
   1137         item = PyIter_Next(iter);
   1138         if (item == NULL) {
   1139             if (PyErr_Occurred())
   1140                 goto _fsum_error;
   1141             break;
   1142         }
   1143         x = PyFloat_AsDouble(item);
   1144         Py_DECREF(item);
   1145         if (PyErr_Occurred())
   1146             goto _fsum_error;
   1147 
   1148         xsave = x;
   1149         for (i = j = 0; j < n; j++) {       /* for y in partials */
   1150             y = p[j];
   1151             if (fabs(x) < fabs(y)) {
   1152                 t = x; x = y; y = t;
   1153             }
   1154             hi = x + y;
   1155             yr = hi - x;
   1156             lo = y - yr;
   1157             if (lo != 0.0)
   1158                 p[i++] = lo;
   1159             x = hi;
   1160         }
   1161 
   1162         n = i;                              /* ps[i:] = [x] */
   1163         if (x != 0.0) {
   1164             if (! Py_IS_FINITE(x)) {
   1165                 /* a nonfinite x could arise either as
   1166                    a result of intermediate overflow, or
   1167                    as a result of a nan or inf in the
   1168                    summands */
   1169                 if (Py_IS_FINITE(xsave)) {
   1170                     PyErr_SetString(PyExc_OverflowError,
   1171                           "intermediate overflow in fsum");
   1172                     goto _fsum_error;
   1173                 }
   1174                 if (Py_IS_INFINITY(xsave))
   1175                     inf_sum += xsave;
   1176                 special_sum += xsave;
   1177                 /* reset partials */
   1178                 n = 0;
   1179             }
   1180             else if (n >= m && _fsum_realloc(&p, n, ps, &m))
   1181                 goto _fsum_error;
   1182             else
   1183                 p[n++] = x;
   1184         }
   1185     }
   1186 
   1187     if (special_sum != 0.0) {
   1188         if (Py_IS_NAN(inf_sum))
   1189             PyErr_SetString(PyExc_ValueError,
   1190                             "-inf + inf in fsum");
   1191         else
   1192             sum = PyFloat_FromDouble(special_sum);
   1193         goto _fsum_error;
   1194     }
   1195 
   1196     hi = 0.0;
   1197     if (n > 0) {
   1198         hi = p[--n];
   1199         /* sum_exact(ps, hi) from the top, stop when the sum becomes
   1200            inexact. */
   1201         while (n > 0) {
   1202             x = hi;
   1203             y = p[--n];
   1204             assert(fabs(y) < fabs(x));
   1205             hi = x + y;
   1206             yr = hi - x;
   1207             lo = y - yr;
   1208             if (lo != 0.0)
   1209                 break;
   1210         }
   1211         /* Make half-even rounding work across multiple partials.
   1212            Needed so that sum([1e-16, 1, 1e16]) will round-up the last
   1213            digit to two instead of down to zero (the 1e-16 makes the 1
   1214            slightly closer to two).  With a potential 1 ULP rounding
   1215            error fixed-up, math.fsum() can guarantee commutativity. */
   1216         if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
   1217                       (lo > 0.0 && p[n-1] > 0.0))) {
   1218             y = lo * 2.0;
   1219             x = hi + y;
   1220             yr = x - hi;
   1221             if (y == yr)
   1222                 hi = x;
   1223         }
   1224     }
   1225     sum = PyFloat_FromDouble(hi);
   1226 
   1227 _fsum_error:
   1228     PyFPE_END_PROTECT(hi)
   1229     Py_DECREF(iter);
   1230     if (p != ps)
   1231         PyMem_Free(p);
   1232     return sum;
   1233 }
   1234 
   1235 #undef NUM_PARTIALS
   1236 
   1237 PyDoc_STRVAR(math_fsum_doc,
   1238 "fsum(iterable)\n\n\
   1239 Return an accurate floating point sum of values in the iterable.\n\
   1240 Assumes IEEE-754 floating point arithmetic.");
   1241 
   1242 /* Return the smallest integer k such that n < 2**k, or 0 if n == 0.
   1243  * Equivalent to floor(lg(x))+1.  Also equivalent to: bitwidth_of_type -
   1244  * count_leading_zero_bits(x)
   1245  */
   1246 
   1247 /* XXX: This routine does more or less the same thing as
   1248  * bits_in_digit() in Objects/longobject.c.  Someday it would be nice to
   1249  * consolidate them.  On BSD, there's a library function called fls()
   1250  * that we could use, and GCC provides __builtin_clz().
   1251  */
   1252 
   1253 static unsigned long
   1254 bit_length(unsigned long n)
   1255 {
   1256     unsigned long len = 0;
   1257     while (n != 0) {
   1258         ++len;
   1259         n >>= 1;
   1260     }
   1261     return len;
   1262 }
   1263 
   1264 static unsigned long
   1265 count_set_bits(unsigned long n)
   1266 {
   1267     unsigned long count = 0;
   1268     while (n != 0) {
   1269         ++count;
   1270         n &= n - 1; /* clear least significant bit */
   1271     }
   1272     return count;
   1273 }
   1274 
   1275 /* Divide-and-conquer factorial algorithm
   1276  *
   1277  * Based on the formula and pseudo-code provided at:
   1278  * http://www.luschny.de/math/factorial/binarysplitfact.html
   1279  *
   1280  * Faster algorithms exist, but they're more complicated and depend on
   1281  * a fast prime factorization algorithm.
   1282  *
   1283  * Notes on the algorithm
   1284  * ----------------------
   1285  *
   1286  * factorial(n) is written in the form 2**k * m, with m odd.  k and m are
   1287  * computed separately, and then combined using a left shift.
   1288  *
   1289  * The function factorial_odd_part computes the odd part m (i.e., the greatest
   1290  * odd divisor) of factorial(n), using the formula:
   1291  *
   1292  *   factorial_odd_part(n) =
   1293  *
   1294  *        product_{i >= 0} product_{0 < j <= n / 2**i, j odd} j
   1295  *
   1296  * Example: factorial_odd_part(20) =
   1297  *
   1298  *        (1) *
   1299  *        (1) *
   1300  *        (1 * 3 * 5) *
   1301  *        (1 * 3 * 5 * 7 * 9)
   1302  *        (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
   1303  *
   1304  * Here i goes from large to small: the first term corresponds to i=4 (any
   1305  * larger i gives an empty product), and the last term corresponds to i=0.
   1306  * Each term can be computed from the last by multiplying by the extra odd
   1307  * numbers required: e.g., to get from the penultimate term to the last one,
   1308  * we multiply by (11 * 13 * 15 * 17 * 19).
   1309  *
   1310  * To see a hint of why this formula works, here are the same numbers as above
   1311  * but with the even parts (i.e., the appropriate powers of 2) included.  For
   1312  * each subterm in the product for i, we multiply that subterm by 2**i:
   1313  *
   1314  *   factorial(20) =
   1315  *
   1316  *        (16) *
   1317  *        (8) *
   1318  *        (4 * 12 * 20) *
   1319  *        (2 * 6 * 10 * 14 * 18) *
   1320  *        (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
   1321  *
   1322  * The factorial_partial_product function computes the product of all odd j in
   1323  * range(start, stop) for given start and stop.  It's used to compute the
   1324  * partial products like (11 * 13 * 15 * 17 * 19) in the example above.  It
   1325  * operates recursively, repeatedly splitting the range into two roughly equal
   1326  * pieces until the subranges are small enough to be computed using only C
   1327  * integer arithmetic.
   1328  *
   1329  * The two-valuation k (i.e., the exponent of the largest power of 2 dividing
   1330  * the factorial) is computed independently in the main math_factorial
   1331  * function.  By standard results, its value is:
   1332  *
   1333  *    two_valuation = n//2 + n//4 + n//8 + ....
   1334  *
   1335  * It can be shown (e.g., by complete induction on n) that two_valuation is
   1336  * equal to n - count_set_bits(n), where count_set_bits(n) gives the number of
   1337  * '1'-bits in the binary expansion of n.
   1338  */
   1339 
   1340 /* factorial_partial_product: Compute product(range(start, stop, 2)) using
   1341  * divide and conquer.  Assumes start and stop are odd and stop > start.
   1342  * max_bits must be >= bit_length(stop - 2). */
   1343 
   1344 static PyObject *
   1345 factorial_partial_product(unsigned long start, unsigned long stop,
   1346                           unsigned long max_bits)
   1347 {
   1348     unsigned long midpoint, num_operands;
   1349     PyObject *left = NULL, *right = NULL, *result = NULL;
   1350 
   1351     /* If the return value will fit an unsigned long, then we can
   1352      * multiply in a tight, fast loop where each multiply is O(1).
   1353      * Compute an upper bound on the number of bits required to store
   1354      * the answer.
   1355      *
   1356      * Storing some integer z requires floor(lg(z))+1 bits, which is
   1357      * conveniently the value returned by bit_length(z).  The
   1358      * product x*y will require at most
   1359      * bit_length(x) + bit_length(y) bits to store, based
   1360      * on the idea that lg product = lg x + lg y.
   1361      *
   1362      * We know that stop - 2 is the largest number to be multiplied.  From
   1363      * there, we have: bit_length(answer) <= num_operands *
   1364      * bit_length(stop - 2)
   1365      */
   1366 
   1367     num_operands = (stop - start) / 2;
   1368     /* The "num_operands <= 8 * SIZEOF_LONG" check guards against the
   1369      * unlikely case of an overflow in num_operands * max_bits. */
   1370     if (num_operands <= 8 * SIZEOF_LONG &&
   1371         num_operands * max_bits <= 8 * SIZEOF_LONG) {
   1372         unsigned long j, total;
   1373         for (total = start, j = start + 2; j < stop; j += 2)
   1374             total *= j;
   1375         return PyLong_FromUnsignedLong(total);
   1376     }
   1377 
   1378     /* find midpoint of range(start, stop), rounded up to next odd number. */
   1379     midpoint = (start + num_operands) | 1;
   1380     left = factorial_partial_product(start, midpoint,
   1381                                      bit_length(midpoint - 2));
   1382     if (left == NULL)
   1383         goto error;
   1384     right = factorial_partial_product(midpoint, stop, max_bits);
   1385     if (right == NULL)
   1386         goto error;
   1387     result = PyNumber_Multiply(left, right);
   1388 
   1389   error:
   1390     Py_XDECREF(left);
   1391     Py_XDECREF(right);
   1392     return result;
   1393 }
   1394 
   1395 /* factorial_odd_part:  compute the odd part of factorial(n). */
   1396 
   1397 static PyObject *
   1398 factorial_odd_part(unsigned long n)
   1399 {
   1400     long i;
   1401     unsigned long v, lower, upper;
   1402     PyObject *partial, *tmp, *inner, *outer;
   1403 
   1404     inner = PyLong_FromLong(1);
   1405     if (inner == NULL)
   1406         return NULL;
   1407     outer = inner;
   1408     Py_INCREF(outer);
   1409 
   1410     upper = 3;
   1411     for (i = bit_length(n) - 2; i >= 0; i--) {
   1412         v = n >> i;
   1413         if (v <= 2)
   1414             continue;
   1415         lower = upper;
   1416         /* (v + 1) | 1 = least odd integer strictly larger than n / 2**i */
   1417         upper = (v + 1) | 1;
   1418         /* Here inner is the product of all odd integers j in the range (0,
   1419            n/2**(i+1)].  The factorial_partial_product call below gives the
   1420            product of all odd integers j in the range (n/2**(i+1), n/2**i]. */
   1421         partial = factorial_partial_product(lower, upper, bit_length(upper-2));
   1422         /* inner *= partial */
   1423         if (partial == NULL)
   1424             goto error;
   1425         tmp = PyNumber_Multiply(inner, partial);
   1426         Py_DECREF(partial);
   1427         if (tmp == NULL)
   1428             goto error;
   1429         Py_DECREF(inner);
   1430         inner = tmp;
   1431         /* Now inner is the product of all odd integers j in the range (0,
   1432            n/2**i], giving the inner product in the formula above. */
   1433 
   1434         /* outer *= inner; */
   1435         tmp = PyNumber_Multiply(outer, inner);
   1436         if (tmp == NULL)
   1437             goto error;
   1438         Py_DECREF(outer);
   1439         outer = tmp;
   1440     }
   1441     Py_DECREF(inner);
   1442     return outer;
   1443 
   1444   error:
   1445     Py_DECREF(outer);
   1446     Py_DECREF(inner);
   1447     return NULL;
   1448 }
   1449 
   1450 /* Lookup table for small factorial values */
   1451 
   1452 static const unsigned long SmallFactorials[] = {
   1453     1, 1, 2, 6, 24, 120, 720, 5040, 40320,
   1454     362880, 3628800, 39916800, 479001600,
   1455 #if SIZEOF_LONG >= 8
   1456     6227020800, 87178291200, 1307674368000,
   1457     20922789888000, 355687428096000, 6402373705728000,
   1458     121645100408832000, 2432902008176640000
   1459 #endif
   1460 };
   1461 
   1462 static PyObject *
   1463 math_factorial(PyObject *self, PyObject *arg)
   1464 {
   1465     long x;
   1466     int overflow;
   1467     PyObject *result, *odd_part, *two_valuation;
   1468 
   1469     if (PyFloat_Check(arg)) {
   1470         PyObject *lx;
   1471         double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
   1472         if (!(Py_IS_FINITE(dx) && dx == floor(dx))) {
   1473             PyErr_SetString(PyExc_ValueError,
   1474                             "factorial() only accepts integral values");
   1475             return NULL;
   1476         }
   1477         lx = PyLong_FromDouble(dx);
   1478         if (lx == NULL)
   1479             return NULL;
   1480         x = PyLong_AsLongAndOverflow(lx, &overflow);
   1481         Py_DECREF(lx);
   1482     }
   1483     else
   1484         x = PyLong_AsLongAndOverflow(arg, &overflow);
   1485 
   1486     if (x == -1 && PyErr_Occurred()) {
   1487         return NULL;
   1488     }
   1489     else if (overflow == 1) {
   1490         PyErr_Format(PyExc_OverflowError,
   1491                      "factorial() argument should not exceed %ld",
   1492                      LONG_MAX);
   1493         return NULL;
   1494     }
   1495     else if (overflow == -1 || x < 0) {
   1496         PyErr_SetString(PyExc_ValueError,
   1497                         "factorial() not defined for negative values");
   1498         return NULL;
   1499     }
   1500 
   1501     /* use lookup table if x is small */
   1502     if (x < (long)Py_ARRAY_LENGTH(SmallFactorials))
   1503         return PyLong_FromUnsignedLong(SmallFactorials[x]);
   1504 
   1505     /* else express in the form odd_part * 2**two_valuation, and compute as
   1506        odd_part << two_valuation. */
   1507     odd_part = factorial_odd_part(x);
   1508     if (odd_part == NULL)
   1509         return NULL;
   1510     two_valuation = PyLong_FromLong(x - count_set_bits(x));
   1511     if (two_valuation == NULL) {
   1512         Py_DECREF(odd_part);
   1513         return NULL;
   1514     }
   1515     result = PyNumber_Lshift(odd_part, two_valuation);
   1516     Py_DECREF(two_valuation);
   1517     Py_DECREF(odd_part);
   1518     return result;
   1519 }
   1520 
   1521 PyDoc_STRVAR(math_factorial_doc,
   1522 "factorial(x) -> Integral\n"
   1523 "\n"
   1524 "Find x!. Raise a ValueError if x is negative or non-integral.");
   1525 
   1526 static PyObject *
   1527 math_trunc(PyObject *self, PyObject *number)
   1528 {
   1529     _Py_IDENTIFIER(__trunc__);
   1530     PyObject *trunc, *result;
   1531 
   1532     if (Py_TYPE(number)->tp_dict == NULL) {
   1533         if (PyType_Ready(Py_TYPE(number)) < 0)
   1534             return NULL;
   1535     }
   1536 
   1537     trunc = _PyObject_LookupSpecial(number, &PyId___trunc__);
   1538     if (trunc == NULL) {
   1539         if (!PyErr_Occurred())
   1540             PyErr_Format(PyExc_TypeError,
   1541                          "type %.100s doesn't define __trunc__ method",
   1542                          Py_TYPE(number)->tp_name);
   1543         return NULL;
   1544     }
   1545     result = PyObject_CallFunctionObjArgs(trunc, NULL);
   1546     Py_DECREF(trunc);
   1547     return result;
   1548 }
   1549 
   1550 PyDoc_STRVAR(math_trunc_doc,
   1551 "trunc(x:Real) -> Integral\n"
   1552 "\n"
   1553 "Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.");
   1554 
   1555 static PyObject *
   1556 math_frexp(PyObject *self, PyObject *arg)
   1557 {
   1558     int i;
   1559     double x = PyFloat_AsDouble(arg);
   1560     if (x == -1.0 && PyErr_Occurred())
   1561         return NULL;
   1562     /* deal with special cases directly, to sidestep platform
   1563        differences */
   1564     if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
   1565         i = 0;
   1566     }
   1567     else {
   1568         PyFPE_START_PROTECT("in math_frexp", return 0);
   1569         x = frexp(x, &i);
   1570         PyFPE_END_PROTECT(x);
   1571     }
   1572     return Py_BuildValue("(di)", x, i);
   1573 }
   1574 
   1575 PyDoc_STRVAR(math_frexp_doc,
   1576 "frexp(x)\n"
   1577 "\n"
   1578 "Return the mantissa and exponent of x, as pair (m, e).\n"
   1579 "m is a float and e is an int, such that x = m * 2.**e.\n"
   1580 "If x is 0, m and e are both 0.  Else 0.5 <= abs(m) < 1.0.");
   1581 
   1582 static PyObject *
   1583 math_ldexp(PyObject *self, PyObject *args)
   1584 {
   1585     double x, r;
   1586     PyObject *oexp;
   1587     long exp;
   1588     int overflow;
   1589     if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp))
   1590         return NULL;
   1591 
   1592     if (PyLong_Check(oexp)) {
   1593         /* on overflow, replace exponent with either LONG_MAX
   1594            or LONG_MIN, depending on the sign. */
   1595         exp = PyLong_AsLongAndOverflow(oexp, &overflow);
   1596         if (exp == -1 && PyErr_Occurred())
   1597             return NULL;
   1598         if (overflow)
   1599             exp = overflow < 0 ? LONG_MIN : LONG_MAX;
   1600     }
   1601     else {
   1602         PyErr_SetString(PyExc_TypeError,
   1603                         "Expected an int as second argument to ldexp.");
   1604         return NULL;
   1605     }
   1606 
   1607     if (x == 0. || !Py_IS_FINITE(x)) {
   1608         /* NaNs, zeros and infinities are returned unchanged */
   1609         r = x;
   1610         errno = 0;
   1611     } else if (exp > INT_MAX) {
   1612         /* overflow */
   1613         r = copysign(Py_HUGE_VAL, x);
   1614         errno = ERANGE;
   1615     } else if (exp < INT_MIN) {
   1616         /* underflow to +-0 */
   1617         r = copysign(0., x);
   1618         errno = 0;
   1619     } else {
   1620         errno = 0;
   1621         PyFPE_START_PROTECT("in math_ldexp", return 0);
   1622         r = ldexp(x, (int)exp);
   1623         PyFPE_END_PROTECT(r);
   1624         if (Py_IS_INFINITY(r))
   1625             errno = ERANGE;
   1626     }
   1627 
   1628     if (errno && is_error(r))
   1629         return NULL;
   1630     return PyFloat_FromDouble(r);
   1631 }
   1632 
   1633 PyDoc_STRVAR(math_ldexp_doc,
   1634 "ldexp(x, i)\n\n\
   1635 Return x * (2**i).");
   1636 
   1637 static PyObject *
   1638 math_modf(PyObject *self, PyObject *arg)
   1639 {
   1640     double y, x = PyFloat_AsDouble(arg);
   1641     if (x == -1.0 && PyErr_Occurred())
   1642         return NULL;
   1643     /* some platforms don't do the right thing for NaNs and
   1644        infinities, so we take care of special cases directly. */
   1645     if (!Py_IS_FINITE(x)) {
   1646         if (Py_IS_INFINITY(x))
   1647             return Py_BuildValue("(dd)", copysign(0., x), x);
   1648         else if (Py_IS_NAN(x))
   1649             return Py_BuildValue("(dd)", x, x);
   1650     }
   1651 
   1652     errno = 0;
   1653     PyFPE_START_PROTECT("in math_modf", return 0);
   1654     x = modf(x, &y);
   1655     PyFPE_END_PROTECT(x);
   1656     return Py_BuildValue("(dd)", x, y);
   1657 }
   1658 
   1659 PyDoc_STRVAR(math_modf_doc,
   1660 "modf(x)\n"
   1661 "\n"
   1662 "Return the fractional and integer parts of x.  Both results carry the sign\n"
   1663 "of x and are floats.");
   1664 
   1665 /* A decent logarithm is easy to compute even for huge ints, but libm can't
   1666    do that by itself -- loghelper can.  func is log or log10, and name is
   1667    "log" or "log10".  Note that overflow of the result isn't possible: an int
   1668    can contain no more than INT_MAX * SHIFT bits, so has value certainly less
   1669    than 2**(2**64 * 2**16) == 2**2**80, and log2 of that is 2**80, which is
   1670    small enough to fit in an IEEE single.  log and log10 are even smaller.
   1671    However, intermediate overflow is possible for an int if the number of bits
   1672    in that int is larger than PY_SSIZE_T_MAX. */
   1673 
   1674 static PyObject*
   1675 loghelper(PyObject* arg, double (*func)(double), const char *funcname)
   1676 {
   1677     /* If it is int, do it ourselves. */
   1678     if (PyLong_Check(arg)) {
   1679         double x, result;
   1680         Py_ssize_t e;
   1681 
   1682         /* Negative or zero inputs give a ValueError. */
   1683         if (Py_SIZE(arg) <= 0) {
   1684             PyErr_SetString(PyExc_ValueError,
   1685                             "math domain error");
   1686             return NULL;
   1687         }
   1688 
   1689         x = PyLong_AsDouble(arg);
   1690         if (x == -1.0 && PyErr_Occurred()) {
   1691             if (!PyErr_ExceptionMatches(PyExc_OverflowError))
   1692                 return NULL;
   1693             /* Here the conversion to double overflowed, but it's possible
   1694                to compute the log anyway.  Clear the exception and continue. */
   1695             PyErr_Clear();
   1696             x = _PyLong_Frexp((PyLongObject *)arg, &e);
   1697             if (x == -1.0 && PyErr_Occurred())
   1698                 return NULL;
   1699             /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */
   1700             result = func(x) + func(2.0) * e;
   1701         }
   1702         else
   1703             /* Successfully converted x to a double. */
   1704             result = func(x);
   1705         return PyFloat_FromDouble(result);
   1706     }
   1707 
   1708     /* Else let libm handle it by itself. */
   1709     return math_1(arg, func, 0);
   1710 }
   1711 
   1712 static PyObject *
   1713 math_log(PyObject *self, PyObject *args)
   1714 {
   1715     PyObject *arg;
   1716     PyObject *base = NULL;
   1717     PyObject *num, *den;
   1718     PyObject *ans;
   1719 
   1720     if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base))
   1721         return NULL;
   1722 
   1723     num = loghelper(arg, m_log, "log");
   1724     if (num == NULL || base == NULL)
   1725         return num;
   1726 
   1727     den = loghelper(base, m_log, "log");
   1728     if (den == NULL) {
   1729         Py_DECREF(num);
   1730         return NULL;
   1731     }
   1732 
   1733     ans = PyNumber_TrueDivide(num, den);
   1734     Py_DECREF(num);
   1735     Py_DECREF(den);
   1736     return ans;
   1737 }
   1738 
   1739 PyDoc_STRVAR(math_log_doc,
   1740 "log(x[, base])\n\n\
   1741 Return the logarithm of x to the given base.\n\
   1742 If the base not specified, returns the natural logarithm (base e) of x.");
   1743 
   1744 static PyObject *
   1745 math_log2(PyObject *self, PyObject *arg)
   1746 {
   1747     return loghelper(arg, m_log2, "log2");
   1748 }
   1749 
   1750 PyDoc_STRVAR(math_log2_doc,
   1751 "log2(x)\n\nReturn the base 2 logarithm of x.");
   1752 
   1753 static PyObject *
   1754 math_log10(PyObject *self, PyObject *arg)
   1755 {
   1756     return loghelper(arg, m_log10, "log10");
   1757 }
   1758 
   1759 PyDoc_STRVAR(math_log10_doc,
   1760 "log10(x)\n\nReturn the base 10 logarithm of x.");
   1761 
   1762 static PyObject *
   1763 math_fmod(PyObject *self, PyObject *args)
   1764 {
   1765     PyObject *ox, *oy;
   1766     double r, x, y;
   1767     if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy))
   1768         return NULL;
   1769     x = PyFloat_AsDouble(ox);
   1770     y = PyFloat_AsDouble(oy);
   1771     if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
   1772         return NULL;
   1773     /* fmod(x, +/-Inf) returns x for finite x. */
   1774     if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
   1775         return PyFloat_FromDouble(x);
   1776     errno = 0;
   1777     PyFPE_START_PROTECT("in math_fmod", return 0);
   1778     r = fmod(x, y);
   1779     PyFPE_END_PROTECT(r);
   1780     if (Py_IS_NAN(r)) {
   1781         if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
   1782             errno = EDOM;
   1783         else
   1784             errno = 0;
   1785     }
   1786     if (errno && is_error(r))
   1787         return NULL;
   1788     else
   1789         return PyFloat_FromDouble(r);
   1790 }
   1791 
   1792 PyDoc_STRVAR(math_fmod_doc,
   1793 "fmod(x, y)\n\nReturn fmod(x, y), according to platform C."
   1794 "  x % y may differ.");
   1795 
   1796 static PyObject *
   1797 math_hypot(PyObject *self, PyObject *args)
   1798 {
   1799     PyObject *ox, *oy;
   1800     double r, x, y;
   1801     if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy))
   1802         return NULL;
   1803     x = PyFloat_AsDouble(ox);
   1804     y = PyFloat_AsDouble(oy);
   1805     if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
   1806         return NULL;
   1807     /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */
   1808     if (Py_IS_INFINITY(x))
   1809         return PyFloat_FromDouble(fabs(x));
   1810     if (Py_IS_INFINITY(y))
   1811         return PyFloat_FromDouble(fabs(y));
   1812     errno = 0;
   1813     PyFPE_START_PROTECT("in math_hypot", return 0);
   1814     r = hypot(x, y);
   1815     PyFPE_END_PROTECT(r);
   1816     if (Py_IS_NAN(r)) {
   1817         if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
   1818             errno = EDOM;
   1819         else
   1820             errno = 0;
   1821     }
   1822     else if (Py_IS_INFINITY(r)) {
   1823         if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
   1824             errno = ERANGE;
   1825         else
   1826             errno = 0;
   1827     }
   1828     if (errno && is_error(r))
   1829         return NULL;
   1830     else
   1831         return PyFloat_FromDouble(r);
   1832 }
   1833 
   1834 PyDoc_STRVAR(math_hypot_doc,
   1835 "hypot(x, y)\n\nReturn the Euclidean distance, sqrt(x*x + y*y).");
   1836 
   1837 /* pow can't use math_2, but needs its own wrapper: the problem is
   1838    that an infinite result can arise either as a result of overflow
   1839    (in which case OverflowError should be raised) or as a result of
   1840    e.g. 0.**-5. (for which ValueError needs to be raised.)
   1841 */
   1842 
   1843 static PyObject *
   1844 math_pow(PyObject *self, PyObject *args)
   1845 {
   1846     PyObject *ox, *oy;
   1847     double r, x, y;
   1848     int odd_y;
   1849 
   1850     if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy))
   1851         return NULL;
   1852     x = PyFloat_AsDouble(ox);
   1853     y = PyFloat_AsDouble(oy);
   1854     if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
   1855         return NULL;
   1856 
   1857     /* deal directly with IEEE specials, to cope with problems on various
   1858        platforms whose semantics don't exactly match C99 */
   1859     r = 0.; /* silence compiler warning */
   1860     if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
   1861         errno = 0;
   1862         if (Py_IS_NAN(x))
   1863             r = y == 0. ? 1. : x; /* NaN**0 = 1 */
   1864         else if (Py_IS_NAN(y))
   1865             r = x == 1. ? 1. : y; /* 1**NaN = 1 */
   1866         else if (Py_IS_INFINITY(x)) {
   1867             odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
   1868             if (y > 0.)
   1869                 r = odd_y ? x : fabs(x);
   1870             else if (y == 0.)
   1871                 r = 1.;
   1872             else /* y < 0. */
   1873                 r = odd_y ? copysign(0., x) : 0.;
   1874         }
   1875         else if (Py_IS_INFINITY(y)) {
   1876             if (fabs(x) == 1.0)
   1877                 r = 1.;
   1878             else if (y > 0. && fabs(x) > 1.0)
   1879                 r = y;
   1880             else if (y < 0. && fabs(x) < 1.0) {
   1881                 r = -y; /* result is +inf */
   1882                 if (x == 0.) /* 0**-inf: divide-by-zero */
   1883                     errno = EDOM;
   1884             }
   1885             else
   1886                 r = 0.;
   1887         }
   1888     }
   1889     else {
   1890         /* let libm handle finite**finite */
   1891         errno = 0;
   1892         PyFPE_START_PROTECT("in math_pow", return 0);
   1893         r = pow(x, y);
   1894         PyFPE_END_PROTECT(r);
   1895         /* a NaN result should arise only from (-ve)**(finite
   1896            non-integer); in this case we want to raise ValueError. */
   1897         if (!Py_IS_FINITE(r)) {
   1898             if (Py_IS_NAN(r)) {
   1899                 errno = EDOM;
   1900             }
   1901             /*
   1902                an infinite result here arises either from:
   1903                (A) (+/-0.)**negative (-> divide-by-zero)
   1904                (B) overflow of x**y with x and y finite
   1905             */
   1906             else if (Py_IS_INFINITY(r)) {
   1907                 if (x == 0.)
   1908                     errno = EDOM;
   1909                 else
   1910                     errno = ERANGE;
   1911             }
   1912         }
   1913     }
   1914 
   1915     if (errno && is_error(r))
   1916         return NULL;
   1917     else
   1918         return PyFloat_FromDouble(r);
   1919 }
   1920 
   1921 PyDoc_STRVAR(math_pow_doc,
   1922 "pow(x, y)\n\nReturn x**y (x to the power of y).");
   1923 
   1924 static const double degToRad = Py_MATH_PI / 180.0;
   1925 static const double radToDeg = 180.0 / Py_MATH_PI;
   1926 
   1927 static PyObject *
   1928 math_degrees(PyObject *self, PyObject *arg)
   1929 {
   1930     double x = PyFloat_AsDouble(arg);
   1931     if (x == -1.0 && PyErr_Occurred())
   1932         return NULL;
   1933     return PyFloat_FromDouble(x * radToDeg);
   1934 }
   1935 
   1936 PyDoc_STRVAR(math_degrees_doc,
   1937 "degrees(x)\n\n\
   1938 Convert angle x from radians to degrees.");
   1939 
   1940 static PyObject *
   1941 math_radians(PyObject *self, PyObject *arg)
   1942 {
   1943     double x = PyFloat_AsDouble(arg);
   1944     if (x == -1.0 && PyErr_Occurred())
   1945         return NULL;
   1946     return PyFloat_FromDouble(x * degToRad);
   1947 }
   1948 
   1949 PyDoc_STRVAR(math_radians_doc,
   1950 "radians(x)\n\n\
   1951 Convert angle x from degrees to radians.");
   1952 
   1953 static PyObject *
   1954 math_isfinite(PyObject *self, PyObject *arg)
   1955 {
   1956     double x = PyFloat_AsDouble(arg);
   1957     if (x == -1.0 && PyErr_Occurred())
   1958         return NULL;
   1959     return PyBool_FromLong((long)Py_IS_FINITE(x));
   1960 }
   1961 
   1962 PyDoc_STRVAR(math_isfinite_doc,
   1963 "isfinite(x) -> bool\n\n\
   1964 Return True if x is neither an infinity nor a NaN, and False otherwise.");
   1965 
   1966 static PyObject *
   1967 math_isnan(PyObject *self, PyObject *arg)
   1968 {
   1969     double x = PyFloat_AsDouble(arg);
   1970     if (x == -1.0 && PyErr_Occurred())
   1971         return NULL;
   1972     return PyBool_FromLong((long)Py_IS_NAN(x));
   1973 }
   1974 
   1975 PyDoc_STRVAR(math_isnan_doc,
   1976 "isnan(x) -> bool\n\n\
   1977 Return True if x is a NaN (not a number), and False otherwise.");
   1978 
   1979 static PyObject *
   1980 math_isinf(PyObject *self, PyObject *arg)
   1981 {
   1982     double x = PyFloat_AsDouble(arg);
   1983     if (x == -1.0 && PyErr_Occurred())
   1984         return NULL;
   1985     return PyBool_FromLong((long)Py_IS_INFINITY(x));
   1986 }
   1987 
   1988 PyDoc_STRVAR(math_isinf_doc,
   1989 "isinf(x) -> bool\n\n\
   1990 Return True if x is a positive or negative infinity, and False otherwise.");
   1991 
   1992 static PyObject *
   1993 math_isclose(PyObject *self, PyObject *args, PyObject *kwargs)
   1994 {
   1995     double a, b;
   1996     double rel_tol = 1e-9;
   1997     double abs_tol = 0.0;
   1998     double diff = 0.0;
   1999     long result = 0;
   2000 
   2001     static char *keywords[] = {"a", "b", "rel_tol", "abs_tol", NULL};
   2002 
   2003 
   2004     if (!PyArg_ParseTupleAndKeywords(args, kwargs, "dd|$dd:isclose",
   2005                                      keywords,
   2006                                      &a, &b, &rel_tol, &abs_tol
   2007                                      ))
   2008         return NULL;
   2009 
   2010     /* sanity check on the inputs */
   2011     if (rel_tol < 0.0 || abs_tol < 0.0 ) {
   2012         PyErr_SetString(PyExc_ValueError,
   2013                         "tolerances must be non-negative");
   2014         return NULL;
   2015     }
   2016 
   2017     if ( a == b ) {
   2018         /* short circuit exact equality -- needed to catch two infinities of
   2019            the same sign. And perhaps speeds things up a bit sometimes.
   2020         */
   2021         Py_RETURN_TRUE;
   2022     }
   2023 
   2024     /* This catches the case of two infinities of opposite sign, or
   2025        one infinity and one finite number. Two infinities of opposite
   2026        sign would otherwise have an infinite relative tolerance.
   2027        Two infinities of the same sign are caught by the equality check
   2028        above.
   2029     */
   2030 
   2031     if (Py_IS_INFINITY(a) || Py_IS_INFINITY(b)) {
   2032         Py_RETURN_FALSE;
   2033     }
   2034 
   2035     /* now do the regular computation
   2036        this is essentially the "weak" test from the Boost library
   2037     */
   2038 
   2039     diff = fabs(b - a);
   2040 
   2041     result = (((diff <= fabs(rel_tol * b)) ||
   2042                (diff <= fabs(rel_tol * a))) ||
   2043               (diff <= abs_tol));
   2044 
   2045     return PyBool_FromLong(result);
   2046 }
   2047 
   2048 PyDoc_STRVAR(math_isclose_doc,
   2049 "isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0) -> bool\n"
   2050 "\n"
   2051 "Determine whether two floating point numbers are close in value.\n"
   2052 "\n"
   2053 "   rel_tol\n"
   2054 "       maximum difference for being considered \"close\", relative to the\n"
   2055 "       magnitude of the input values\n"
   2056 "    abs_tol\n"
   2057 "       maximum difference for being considered \"close\", regardless of the\n"
   2058 "       magnitude of the input values\n"
   2059 "\n"
   2060 "Return True if a is close in value to b, and False otherwise.\n"
   2061 "\n"
   2062 "For the values to be considered close, the difference between them\n"
   2063 "must be smaller than at least one of the tolerances.\n"
   2064 "\n"
   2065 "-inf, inf and NaN behave similarly to the IEEE 754 Standard.  That\n"
   2066 "is, NaN is not close to anything, even itself.  inf and -inf are\n"
   2067 "only close to themselves.");
   2068 
   2069 static PyMethodDef math_methods[] = {
   2070     {"acos",            math_acos,      METH_O,         math_acos_doc},
   2071     {"acosh",           math_acosh,     METH_O,         math_acosh_doc},
   2072     {"asin",            math_asin,      METH_O,         math_asin_doc},
   2073     {"asinh",           math_asinh,     METH_O,         math_asinh_doc},
   2074     {"atan",            math_atan,      METH_O,         math_atan_doc},
   2075     {"atan2",           math_atan2,     METH_VARARGS,   math_atan2_doc},
   2076     {"atanh",           math_atanh,     METH_O,         math_atanh_doc},
   2077     {"ceil",            math_ceil,      METH_O,         math_ceil_doc},
   2078     {"copysign",        math_copysign,  METH_VARARGS,   math_copysign_doc},
   2079     {"cos",             math_cos,       METH_O,         math_cos_doc},
   2080     {"cosh",            math_cosh,      METH_O,         math_cosh_doc},
   2081     {"degrees",         math_degrees,   METH_O,         math_degrees_doc},
   2082     {"erf",             math_erf,       METH_O,         math_erf_doc},
   2083     {"erfc",            math_erfc,      METH_O,         math_erfc_doc},
   2084     {"exp",             math_exp,       METH_O,         math_exp_doc},
   2085     {"expm1",           math_expm1,     METH_O,         math_expm1_doc},
   2086     {"fabs",            math_fabs,      METH_O,         math_fabs_doc},
   2087     {"factorial",       math_factorial, METH_O,         math_factorial_doc},
   2088     {"floor",           math_floor,     METH_O,         math_floor_doc},
   2089     {"fmod",            math_fmod,      METH_VARARGS,   math_fmod_doc},
   2090     {"frexp",           math_frexp,     METH_O,         math_frexp_doc},
   2091     {"fsum",            math_fsum,      METH_O,         math_fsum_doc},
   2092     {"gamma",           math_gamma,     METH_O,         math_gamma_doc},
   2093     {"gcd",             math_gcd,       METH_VARARGS,   math_gcd_doc},
   2094     {"hypot",           math_hypot,     METH_VARARGS,   math_hypot_doc},
   2095     {"isclose", (PyCFunction) math_isclose, METH_VARARGS | METH_KEYWORDS,
   2096     math_isclose_doc},
   2097     {"isfinite",        math_isfinite,  METH_O,         math_isfinite_doc},
   2098     {"isinf",           math_isinf,     METH_O,         math_isinf_doc},
   2099     {"isnan",           math_isnan,     METH_O,         math_isnan_doc},
   2100     {"ldexp",           math_ldexp,     METH_VARARGS,   math_ldexp_doc},
   2101     {"lgamma",          math_lgamma,    METH_O,         math_lgamma_doc},
   2102     {"log",             math_log,       METH_VARARGS,   math_log_doc},
   2103     {"log1p",           math_log1p,     METH_O,         math_log1p_doc},
   2104     {"log10",           math_log10,     METH_O,         math_log10_doc},
   2105     {"log2",            math_log2,      METH_O,         math_log2_doc},
   2106     {"modf",            math_modf,      METH_O,         math_modf_doc},
   2107     {"pow",             math_pow,       METH_VARARGS,   math_pow_doc},
   2108     {"radians",         math_radians,   METH_O,         math_radians_doc},
   2109     {"sin",             math_sin,       METH_O,         math_sin_doc},
   2110     {"sinh",            math_sinh,      METH_O,         math_sinh_doc},
   2111     {"sqrt",            math_sqrt,      METH_O,         math_sqrt_doc},
   2112     {"tan",             math_tan,       METH_O,         math_tan_doc},
   2113     {"tanh",            math_tanh,      METH_O,         math_tanh_doc},
   2114     {"trunc",           math_trunc,     METH_O,         math_trunc_doc},
   2115     {NULL,              NULL}           /* sentinel */
   2116 };
   2117 
   2118 
   2119 PyDoc_STRVAR(module_doc,
   2120 "This module is always available.  It provides access to the\n"
   2121 "mathematical functions defined by the C standard.");
   2122 
   2123 
   2124 static struct PyModuleDef mathmodule = {
   2125     PyModuleDef_HEAD_INIT,
   2126     "math",
   2127     module_doc,
   2128     -1,
   2129     math_methods,
   2130     NULL,
   2131     NULL,
   2132     NULL,
   2133     NULL
   2134 };
   2135 
   2136 PyMODINIT_FUNC
   2137 PyInit_math(void)
   2138 {
   2139     PyObject *m;
   2140 
   2141     m = PyModule_Create(&mathmodule);
   2142     if (m == NULL)
   2143         goto finally;
   2144 
   2145     PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
   2146     PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
   2147     PyModule_AddObject(m, "tau", PyFloat_FromDouble(Py_MATH_TAU));  /* 2pi */
   2148     PyModule_AddObject(m, "inf", PyFloat_FromDouble(m_inf()));
   2149 #if !defined(PY_NO_SHORT_FLOAT_REPR) || defined(Py_NAN)
   2150     PyModule_AddObject(m, "nan", PyFloat_FromDouble(m_nan()));
   2151 #endif
   2152 
   2153   finally:
   2154     return m;
   2155 }
   2156