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