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