blob: 92f5f42ece9587283f1de4fafea6ae94adcc56b1 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Math module -- standard C math library functions, pi and e */
2
Christian Heimes53876d92008-04-19 00:31:39 +00003/* Here are some comments from Tim Peters, extracted from the
4 discussion attached to http://bugs.python.org/issue1640. They
5 describe the general aims of the math module with respect to
6 special values, IEEE-754 floating-point exceptions, and Python
7 exceptions.
8
9These are the "spirit of 754" rules:
10
111. If the mathematical result is a real number, but of magnitude too
12large to approximate by a machine float, overflow is signaled and the
13result is an infinity (with the appropriate sign).
14
152. If the mathematical result is a real number, but of magnitude too
16small to approximate by a machine float, underflow is signaled and the
17result is a zero (with the appropriate sign).
18
193. At a singularity (a value x such that the limit of f(y) as y
20approaches x exists and is an infinity), "divide by zero" is signaled
21and the result is an infinity (with the appropriate sign). This is
22complicated a little by that the left-side and right-side limits may
23not be the same; e.g., 1/x approaches +inf or -inf as x approaches 0
24from the positive or negative directions. In that specific case, the
25sign of the zero determines the result of 1/0.
26
274. At a point where a function has no defined result in the extended
28reals (i.e., the reals plus an infinity or two), invalid operation is
29signaled and a NaN is returned.
30
31And these are what Python has historically /tried/ to do (but not
32always successfully, as platform libm behavior varies a lot):
33
34For #1, raise OverflowError.
35
36For #2, return a zero (with the appropriate sign if that happens by
37accident ;-)).
38
39For #3 and #4, raise ValueError. It may have made sense to raise
40Python's ZeroDivisionError in #3, but historically that's only been
41raised for division by zero and mod by zero.
42
43*/
44
45/*
46 In general, on an IEEE-754 platform the aim is to follow the C99
47 standard, including Annex 'F', whenever possible. Where the
48 standard recommends raising the 'divide-by-zero' or 'invalid'
49 floating-point exceptions, Python should raise a ValueError. Where
50 the standard recommends raising 'overflow', Python should raise an
51 OverflowError. In all other circumstances a value should be
52 returned.
53 */
54
Barry Warsaw8b43b191996-12-09 22:32:36 +000055#include "Python.h"
Mark Dickinson664b5112009-12-16 20:23:42 +000056#include "_math.h"
Michael W. Hudson9ef852c2005-04-06 13:05:18 +000057#include "longintrepr.h" /* just for SHIFT */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000058
Christian Heimes969fe572008-01-25 11:23:10 +000059#ifdef _OSF_SOURCE
60/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
61extern double copysign(double, double);
62#endif
63
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000064/*
65 sin(pi*x), giving accurate results for all finite x (especially x
66 integral or close to an integer). This is here for use in the
67 reflection formula for the gamma function. It conforms to IEEE
68 754-2008 for finite arguments, but not for infinities or nans.
69*/
Tim Petersa40c7932001-09-05 22:36:56 +000070
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000071static const double pi = 3.141592653589793238462643383279502884197;
Mark Dickinson45f992a2009-12-19 11:20:49 +000072static const double sqrtpi = 1.772453850905516027298167483341145182798;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000073
74static double
75sinpi(double x)
76{
77 double y, r;
78 int n;
79 /* this function should only ever be called for finite arguments */
80 assert(Py_IS_FINITE(x));
81 y = fmod(fabs(x), 2.0);
82 n = (int)round(2.0*y);
83 assert(0 <= n && n <= 4);
84 switch (n) {
85 case 0:
86 r = sin(pi*y);
87 break;
88 case 1:
89 r = cos(pi*(y-0.5));
90 break;
91 case 2:
92 /* N.B. -sin(pi*(y-1.0)) is *not* equivalent: it would give
93 -0.0 instead of 0.0 when y == 1.0. */
94 r = sin(pi*(1.0-y));
95 break;
96 case 3:
97 r = -cos(pi*(y-1.5));
98 break;
99 case 4:
100 r = sin(pi*(y-2.0));
101 break;
102 default:
103 assert(0); /* should never get here */
104 r = -1.23e200; /* silence gcc warning */
Tim Peters1d120612000-10-12 06:10:25 +0000105 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000106 return copysign(1.0, x)*r;
107}
108
109/* Implementation of the real gamma function. In extensive but non-exhaustive
110 random tests, this function proved accurate to within <= 10 ulps across the
111 entire float domain. Note that accuracy may depend on the quality of the
112 system math functions, the pow function in particular. Special cases
113 follow C99 annex F. The parameters and method are tailored to platforms
114 whose double format is the IEEE 754 binary64 format.
115
116 Method: for x > 0.0 we use the Lanczos approximation with parameters N=13
117 and g=6.024680040776729583740234375; these parameters are amongst those
118 used by the Boost library. Following Boost (again), we re-express the
119 Lanczos sum as a rational function, and compute it that way. The
120 coefficients below were computed independently using MPFR, and have been
121 double-checked against the coefficients in the Boost source code.
122
123 For x < 0.0 we use the reflection formula.
124
125 There's one minor tweak that deserves explanation: Lanczos' formula for
126 Gamma(x) involves computing pow(x+g-0.5, x-0.5) / exp(x+g-0.5). For many x
127 values, x+g-0.5 can be represented exactly. However, in cases where it
128 can't be represented exactly the small error in x+g-0.5 can be magnified
129 significantly by the pow and exp calls, especially for large x. A cheap
130 correction is to multiply by (1 + e*g/(x+g-0.5)), where e is the error
131 involved in the computation of x+g-0.5 (that is, e = computed value of
132 x+g-0.5 - exact value of x+g-0.5). Here's the proof:
133
134 Correction factor
135 -----------------
136 Write x+g-0.5 = y-e, where y is exactly representable as an IEEE 754
137 double, and e is tiny. Then:
138
139 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) = pow(y-e, x-0.5)/exp(y-e)
140 = pow(y, x-0.5)/exp(y) * C,
141
142 where the correction_factor C is given by
143
144 C = pow(1-e/y, x-0.5) * exp(e)
145
146 Since e is tiny, pow(1-e/y, x-0.5) ~ 1-(x-0.5)*e/y, and exp(x) ~ 1+e, so:
147
148 C ~ (1-(x-0.5)*e/y) * (1+e) ~ 1 + e*(y-(x-0.5))/y
149
150 But y-(x-0.5) = g+e, and g+e ~ g. So we get C ~ 1 + e*g/y, and
151
152 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) ~ pow(y, x-0.5)/exp(y) * (1 + e*g/y),
153
154 Note that for accuracy, when computing r*C it's better to do
155
156 r + e*g/y*r;
157
158 than
159
160 r * (1 + e*g/y);
161
162 since the addition in the latter throws away most of the bits of
163 information in e*g/y.
164*/
165
166#define LANCZOS_N 13
167static const double lanczos_g = 6.024680040776729583740234375;
168static const double lanczos_g_minus_half = 5.524680040776729583740234375;
169static const double lanczos_num_coeffs[LANCZOS_N] = {
170 23531376880.410759688572007674451636754734846804940,
171 42919803642.649098768957899047001988850926355848959,
172 35711959237.355668049440185451547166705960488635843,
173 17921034426.037209699919755754458931112671403265390,
174 6039542586.3520280050642916443072979210699388420708,
175 1439720407.3117216736632230727949123939715485786772,
176 248874557.86205415651146038641322942321632125127801,
177 31426415.585400194380614231628318205362874684987640,
178 2876370.6289353724412254090516208496135991145378768,
179 186056.26539522349504029498971604569928220784236328,
180 8071.6720023658162106380029022722506138218516325024,
181 210.82427775157934587250973392071336271166969580291,
182 2.5066282746310002701649081771338373386264310793408
183};
184
185/* denominator is x*(x+1)*...*(x+LANCZOS_N-2) */
186static const double lanczos_den_coeffs[LANCZOS_N] = {
187 0.0, 39916800.0, 120543840.0, 150917976.0, 105258076.0, 45995730.0,
188 13339535.0, 2637558.0, 357423.0, 32670.0, 1925.0, 66.0, 1.0};
189
190/* gamma values for small positive integers, 1 though NGAMMA_INTEGRAL */
191#define NGAMMA_INTEGRAL 23
192static const double gamma_integral[NGAMMA_INTEGRAL] = {
193 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0,
194 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0,
195 1307674368000.0, 20922789888000.0, 355687428096000.0,
196 6402373705728000.0, 121645100408832000.0, 2432902008176640000.0,
197 51090942171709440000.0, 1124000727777607680000.0,
198};
199
200/* Lanczos' sum L_g(x), for positive x */
201
202static double
203lanczos_sum(double x)
204{
205 double num = 0.0, den = 0.0;
206 int i;
207 assert(x > 0.0);
208 /* evaluate the rational function lanczos_sum(x). For large
209 x, the obvious algorithm risks overflow, so we instead
210 rescale the denominator and numerator of the rational
211 function by x**(1-LANCZOS_N) and treat this as a
212 rational function in 1/x. This also reduces the error for
213 larger x values. The choice of cutoff point (5.0 below) is
214 somewhat arbitrary; in tests, smaller cutoff values than
215 this resulted in lower accuracy. */
216 if (x < 5.0) {
217 for (i = LANCZOS_N; --i >= 0; ) {
218 num = num * x + lanczos_num_coeffs[i];
219 den = den * x + lanczos_den_coeffs[i];
220 }
221 }
222 else {
223 for (i = 0; i < LANCZOS_N; i++) {
224 num = num / x + lanczos_num_coeffs[i];
225 den = den / x + lanczos_den_coeffs[i];
226 }
227 }
228 return num/den;
229}
230
231static double
232m_tgamma(double x)
233{
234 double absx, r, y, z, sqrtpow;
235
236 /* special cases */
237 if (!Py_IS_FINITE(x)) {
238 if (Py_IS_NAN(x) || x > 0.0)
239 return x; /* tgamma(nan) = nan, tgamma(inf) = inf */
240 else {
241 errno = EDOM;
242 return Py_NAN; /* tgamma(-inf) = nan, invalid */
243 }
244 }
245 if (x == 0.0) {
246 errno = EDOM;
247 return 1.0/x; /* tgamma(+-0.0) = +-inf, divide-by-zero */
248 }
249
250 /* integer arguments */
251 if (x == floor(x)) {
252 if (x < 0.0) {
253 errno = EDOM; /* tgamma(n) = nan, invalid for */
254 return Py_NAN; /* negative integers n */
255 }
256 if (x <= NGAMMA_INTEGRAL)
257 return gamma_integral[(int)x - 1];
258 }
259 absx = fabs(x);
260
261 /* tiny arguments: tgamma(x) ~ 1/x for x near 0 */
262 if (absx < 1e-20) {
263 r = 1.0/x;
264 if (Py_IS_INFINITY(r))
265 errno = ERANGE;
266 return r;
267 }
268
269 /* large arguments: assuming IEEE 754 doubles, tgamma(x) overflows for
270 x > 200, and underflows to +-0.0 for x < -200, not a negative
271 integer. */
272 if (absx > 200.0) {
273 if (x < 0.0) {
274 return 0.0/sinpi(x);
275 }
276 else {
277 errno = ERANGE;
278 return Py_HUGE_VAL;
279 }
280 }
281
282 y = absx + lanczos_g_minus_half;
283 /* compute error in sum */
284 if (absx > lanczos_g_minus_half) {
285 /* note: the correction can be foiled by an optimizing
286 compiler that (incorrectly) thinks that an expression like
287 a + b - a - b can be optimized to 0.0. This shouldn't
288 happen in a standards-conforming compiler. */
289 double q = y - absx;
290 z = q - lanczos_g_minus_half;
291 }
292 else {
293 double q = y - lanczos_g_minus_half;
294 z = q - absx;
295 }
296 z = z * lanczos_g / y;
297 if (x < 0.0) {
298 r = -pi / sinpi(absx) / absx * exp(y) / lanczos_sum(absx);
299 r -= z * r;
300 if (absx < 140.0) {
301 r /= pow(y, absx - 0.5);
302 }
303 else {
304 sqrtpow = pow(y, absx / 2.0 - 0.25);
305 r /= sqrtpow;
306 r /= sqrtpow;
307 }
308 }
309 else {
310 r = lanczos_sum(absx) / exp(y);
311 r += z * r;
312 if (absx < 140.0) {
313 r *= pow(y, absx - 0.5);
314 }
315 else {
316 sqrtpow = pow(y, absx / 2.0 - 0.25);
317 r *= sqrtpow;
318 r *= sqrtpow;
319 }
320 }
321 if (Py_IS_INFINITY(r))
322 errno = ERANGE;
323 return r;
Guido van Rossum8832b621991-12-16 15:44:24 +0000324}
325
Christian Heimes53876d92008-04-19 00:31:39 +0000326/*
Mark Dickinson05d2e082009-12-11 20:17:17 +0000327 lgamma: natural log of the absolute value of the Gamma function.
328 For large arguments, Lanczos' formula works extremely well here.
329*/
330
331static double
332m_lgamma(double x)
333{
334 double r, absx;
335
336 /* special cases */
337 if (!Py_IS_FINITE(x)) {
338 if (Py_IS_NAN(x))
339 return x; /* lgamma(nan) = nan */
340 else
341 return Py_HUGE_VAL; /* lgamma(+-inf) = +inf */
342 }
343
344 /* integer arguments */
345 if (x == floor(x) && x <= 2.0) {
346 if (x <= 0.0) {
347 errno = EDOM; /* lgamma(n) = inf, divide-by-zero for */
348 return Py_HUGE_VAL; /* integers n <= 0 */
349 }
350 else {
351 return 0.0; /* lgamma(1) = lgamma(2) = 0.0 */
352 }
353 }
354
355 absx = fabs(x);
356 /* tiny arguments: lgamma(x) ~ -log(fabs(x)) for small x */
357 if (absx < 1e-20)
358 return -log(absx);
359
360 /* Lanczos' formula */
361 if (x > 0.0) {
362 /* we could save a fraction of a ulp in accuracy by having a
363 second set of numerator coefficients for lanczos_sum that
364 absorbed the exp(-lanczos_g) term, and throwing out the
365 lanczos_g subtraction below; it's probably not worth it. */
366 r = log(lanczos_sum(x)) - lanczos_g +
367 (x-0.5)*(log(x+lanczos_g-0.5)-1);
368 }
369 else {
370 r = log(pi) - log(fabs(sinpi(absx))) - log(absx) -
371 (log(lanczos_sum(absx)) - lanczos_g +
372 (absx-0.5)*(log(absx+lanczos_g-0.5)-1));
373 }
374 if (Py_IS_INFINITY(r))
375 errno = ERANGE;
376 return r;
377}
378
Mark Dickinson45f992a2009-12-19 11:20:49 +0000379/*
380 Implementations of the error function erf(x) and the complementary error
381 function erfc(x).
382
383 Method: following 'Numerical Recipes' by Flannery, Press et. al. (2nd ed.,
384 Cambridge University Press), we use a series approximation for erf for
385 small x, and a continued fraction approximation for erfc(x) for larger x;
386 combined with the relations erf(-x) = -erf(x) and erfc(x) = 1.0 - erf(x),
387 this gives us erf(x) and erfc(x) for all x.
388
389 The series expansion used is:
390
391 erf(x) = x*exp(-x*x)/sqrt(pi) * [
392 2/1 + 4/3 x**2 + 8/15 x**4 + 16/105 x**6 + ...]
393
394 The coefficient of x**(2k-2) here is 4**k*factorial(k)/factorial(2*k).
395 This series converges well for smallish x, but slowly for larger x.
396
397 The continued fraction expansion used is:
398
399 erfc(x) = x*exp(-x*x)/sqrt(pi) * [1/(0.5 + x**2 -) 0.5/(2.5 + x**2 - )
400 3.0/(4.5 + x**2 - ) 7.5/(6.5 + x**2 - ) ...]
401
402 after the first term, the general term has the form:
403
404 k*(k-0.5)/(2*k+0.5 + x**2 - ...).
405
406 This expansion converges fast for larger x, but convergence becomes
407 infinitely slow as x approaches 0.0. The (somewhat naive) continued
408 fraction evaluation algorithm used below also risks overflow for large x;
409 but for large x, erfc(x) == 0.0 to within machine precision. (For
410 example, erfc(30.0) is approximately 2.56e-393).
411
412 Parameters: use series expansion for abs(x) < ERF_SERIES_CUTOFF and
413 continued fraction expansion for ERF_SERIES_CUTOFF <= abs(x) <
414 ERFC_CONTFRAC_CUTOFF. ERFC_SERIES_TERMS and ERFC_CONTFRAC_TERMS are the
415 numbers of terms to use for the relevant expansions. */
416
417#define ERF_SERIES_CUTOFF 1.5
418#define ERF_SERIES_TERMS 25
419#define ERFC_CONTFRAC_CUTOFF 30.0
420#define ERFC_CONTFRAC_TERMS 50
421
422/*
423 Error function, via power series.
424
425 Given a finite float x, return an approximation to erf(x).
426 Converges reasonably fast for small x.
427*/
428
429static double
430m_erf_series(double x)
431{
432 double x2, acc, fk;
433 int i;
434
435 x2 = x * x;
436 acc = 0.0;
437 fk = (double)ERF_SERIES_TERMS + 0.5;
438 for (i = 0; i < ERF_SERIES_TERMS; i++) {
439 acc = 2.0 + x2 * acc / fk;
440 fk -= 1.0;
441 }
442 return acc * x * exp(-x2) / sqrtpi;
443}
444
445/*
446 Complementary error function, via continued fraction expansion.
447
448 Given a positive float x, return an approximation to erfc(x). Converges
449 reasonably fast for x large (say, x > 2.0), and should be safe from
450 overflow if x and nterms are not too large. On an IEEE 754 machine, with x
451 <= 30.0, we're safe up to nterms = 100. For x >= 30.0, erfc(x) is smaller
452 than the smallest representable nonzero float. */
453
454static double
455m_erfc_contfrac(double x)
456{
457 double x2, a, da, p, p_last, q, q_last, b;
458 int i;
459
460 if (x >= ERFC_CONTFRAC_CUTOFF)
461 return 0.0;
462
463 x2 = x*x;
464 a = 0.0;
465 da = 0.5;
466 p = 1.0; p_last = 0.0;
467 q = da + x2; q_last = 1.0;
468 for (i = 0; i < ERFC_CONTFRAC_TERMS; i++) {
469 double temp;
470 a += da;
471 da += 2.0;
472 b = da + x2;
473 temp = p; p = b*p - a*p_last; p_last = temp;
474 temp = q; q = b*q - a*q_last; q_last = temp;
475 }
476 return p / q * x * exp(-x2) / sqrtpi;
477}
478
479/* Error function erf(x), for general x */
480
481static double
482m_erf(double x)
483{
484 double absx, cf;
485
486 if (Py_IS_NAN(x))
487 return x;
488 absx = fabs(x);
489 if (absx < ERF_SERIES_CUTOFF)
490 return m_erf_series(x);
491 else {
492 cf = m_erfc_contfrac(absx);
493 return x > 0.0 ? 1.0 - cf : cf - 1.0;
494 }
495}
496
497/* Complementary error function erfc(x), for general x. */
498
499static double
500m_erfc(double x)
501{
502 double absx, cf;
503
504 if (Py_IS_NAN(x))
505 return x;
506 absx = fabs(x);
507 if (absx < ERF_SERIES_CUTOFF)
508 return 1.0 - m_erf_series(x);
509 else {
510 cf = m_erfc_contfrac(absx);
511 return x > 0.0 ? cf : 2.0 - cf;
512 }
513}
Mark Dickinson05d2e082009-12-11 20:17:17 +0000514
515/*
Christian Heimese57950f2008-04-21 13:08:03 +0000516 wrapper for atan2 that deals directly with special cases before
517 delegating to the platform libm for the remaining cases. This
518 is necessary to get consistent behaviour across platforms.
519 Windows, FreeBSD and alpha Tru64 are amongst platforms that don't
520 always follow C99.
521*/
522
523static double
524m_atan2(double y, double x)
525{
526 if (Py_IS_NAN(x) || Py_IS_NAN(y))
527 return Py_NAN;
528 if (Py_IS_INFINITY(y)) {
529 if (Py_IS_INFINITY(x)) {
530 if (copysign(1., x) == 1.)
531 /* atan2(+-inf, +inf) == +-pi/4 */
532 return copysign(0.25*Py_MATH_PI, y);
533 else
534 /* atan2(+-inf, -inf) == +-pi*3/4 */
535 return copysign(0.75*Py_MATH_PI, y);
536 }
537 /* atan2(+-inf, x) == +-pi/2 for finite x */
538 return copysign(0.5*Py_MATH_PI, y);
539 }
540 if (Py_IS_INFINITY(x) || y == 0.) {
541 if (copysign(1., x) == 1.)
542 /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */
543 return copysign(0., y);
544 else
545 /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */
546 return copysign(Py_MATH_PI, y);
547 }
548 return atan2(y, x);
549}
550
551/*
Mark Dickinsone675f082008-12-11 21:56:00 +0000552 Various platforms (Solaris, OpenBSD) do nonstandard things for log(0),
553 log(-ve), log(NaN). Here are wrappers for log and log10 that deal with
554 special values directly, passing positive non-special values through to
555 the system log/log10.
556 */
557
558static double
559m_log(double x)
560{
561 if (Py_IS_FINITE(x)) {
562 if (x > 0.0)
563 return log(x);
564 errno = EDOM;
565 if (x == 0.0)
566 return -Py_HUGE_VAL; /* log(0) = -inf */
567 else
568 return Py_NAN; /* log(-ve) = nan */
569 }
570 else if (Py_IS_NAN(x))
571 return x; /* log(nan) = nan */
572 else if (x > 0.0)
573 return x; /* log(inf) = inf */
574 else {
575 errno = EDOM;
576 return Py_NAN; /* log(-inf) = nan */
577 }
578}
579
580static double
581m_log10(double x)
582{
583 if (Py_IS_FINITE(x)) {
584 if (x > 0.0)
585 return log10(x);
586 errno = EDOM;
587 if (x == 0.0)
588 return -Py_HUGE_VAL; /* log10(0) = -inf */
589 else
590 return Py_NAN; /* log10(-ve) = nan */
591 }
592 else if (Py_IS_NAN(x))
593 return x; /* log10(nan) = nan */
594 else if (x > 0.0)
595 return x; /* log10(inf) = inf */
596 else {
597 errno = EDOM;
598 return Py_NAN; /* log10(-inf) = nan */
599 }
600}
601
602
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000603/* Call is_error when errno != 0, and where x is the result libm
604 * returned. is_error will usually set up an exception and return
605 * true (1), but may return false (0) without setting up an exception.
606 */
607static int
608is_error(double x)
609{
610 int result = 1; /* presumption of guilt */
611 assert(errno); /* non-zero errno is a precondition for calling */
612 if (errno == EDOM)
613 PyErr_SetString(PyExc_ValueError, "math domain error");
614
615 else if (errno == ERANGE) {
616 /* ANSI C generally requires libm functions to set ERANGE
617 * on overflow, but also generally *allows* them to set
618 * ERANGE on underflow too. There's no consistency about
619 * the latter across platforms.
620 * Alas, C99 never requires that errno be set.
621 * Here we suppress the underflow errors (libm functions
622 * should return a zero on underflow, and +- HUGE_VAL on
623 * overflow, so testing the result for zero suffices to
624 * distinguish the cases).
625 *
626 * On some platforms (Ubuntu/ia64) it seems that errno can be
627 * set to ERANGE for subnormal results that do *not* underflow
628 * to zero. So to be safe, we'll ignore ERANGE whenever the
629 * function result is less than one in absolute value.
630 */
631 if (fabs(x) < 1.0)
632 result = 0;
633 else
634 PyErr_SetString(PyExc_OverflowError,
635 "math range error");
636 }
637 else
638 /* Unexpected math error */
639 PyErr_SetFromErrno(PyExc_ValueError);
640 return result;
641}
642
Mark Dickinsone675f082008-12-11 21:56:00 +0000643/*
Christian Heimes53876d92008-04-19 00:31:39 +0000644 math_1 is used to wrap a libm function f that takes a double
645 arguments and returns a double.
646
647 The error reporting follows these rules, which are designed to do
648 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
649 platforms.
650
651 - a NaN result from non-NaN inputs causes ValueError to be raised
652 - an infinite result from finite inputs causes OverflowError to be
653 raised if can_overflow is 1, or raises ValueError if can_overflow
654 is 0.
655 - if the result is finite and errno == EDOM then ValueError is
656 raised
657 - if the result is finite and nonzero and errno == ERANGE then
658 OverflowError is raised
659
660 The last rule is used to catch overflow on platforms which follow
661 C89 but for which HUGE_VAL is not an infinity.
662
663 For the majority of one-argument functions these rules are enough
664 to ensure that Python's functions behave as specified in 'Annex F'
665 of the C99 standard, with the 'invalid' and 'divide-by-zero'
666 floating-point exceptions mapping to Python's ValueError and the
667 'overflow' floating-point exception mapping to OverflowError.
668 math_1 only works for functions that don't have singularities *and*
669 the possibility of overflow; fortunately, that covers everything we
670 care about right now.
671*/
672
Barry Warsaw8b43b191996-12-09 22:32:36 +0000673static PyObject *
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000674math_1_to_whatever(PyObject *arg, double (*func) (double),
Christian Heimes53876d92008-04-19 00:31:39 +0000675 PyObject *(*from_double_func) (double),
676 int can_overflow)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000677{
Christian Heimes53876d92008-04-19 00:31:39 +0000678 double x, r;
679 x = PyFloat_AsDouble(arg);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000680 if (x == -1.0 && PyErr_Occurred())
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000681 return NULL;
682 errno = 0;
Christian Heimes53876d92008-04-19 00:31:39 +0000683 PyFPE_START_PROTECT("in math_1", return 0);
684 r = (*func)(x);
685 PyFPE_END_PROTECT(r);
Mark Dickinsona0de26c2008-04-30 23:30:57 +0000686 if (Py_IS_NAN(r) && !Py_IS_NAN(x)) {
687 PyErr_SetString(PyExc_ValueError,
Mark Dickinson66bada52008-06-18 10:04:31 +0000688 "math domain error"); /* invalid arg */
Mark Dickinsona0de26c2008-04-30 23:30:57 +0000689 return NULL;
Christian Heimes53876d92008-04-19 00:31:39 +0000690 }
Mark Dickinsona0de26c2008-04-30 23:30:57 +0000691 if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) {
692 if (can_overflow)
693 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson66bada52008-06-18 10:04:31 +0000694 "math range error"); /* overflow */
Mark Dickinsonb63aff12008-05-09 14:10:27 +0000695 else
696 PyErr_SetString(PyExc_ValueError,
Mark Dickinson66bada52008-06-18 10:04:31 +0000697 "math domain error"); /* singularity */
Mark Dickinsona0de26c2008-04-30 23:30:57 +0000698 return NULL;
Christian Heimes53876d92008-04-19 00:31:39 +0000699 }
Mark Dickinsonde429622008-05-01 00:19:23 +0000700 if (Py_IS_FINITE(r) && errno && is_error(r))
701 /* this branch unnecessary on most platforms */
Tim Peters1d120612000-10-12 06:10:25 +0000702 return NULL;
Mark Dickinsonde429622008-05-01 00:19:23 +0000703
704 return (*from_double_func)(r);
Christian Heimes53876d92008-04-19 00:31:39 +0000705}
706
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000707/* variant of math_1, to be used when the function being wrapped is known to
708 set errno properly (that is, errno = EDOM for invalid or divide-by-zero,
709 errno = ERANGE for overflow). */
710
711static PyObject *
712math_1a(PyObject *arg, double (*func) (double))
713{
714 double x, r;
715 x = PyFloat_AsDouble(arg);
716 if (x == -1.0 && PyErr_Occurred())
717 return NULL;
718 errno = 0;
719 PyFPE_START_PROTECT("in math_1a", return 0);
720 r = (*func)(x);
721 PyFPE_END_PROTECT(r);
722 if (errno && is_error(r))
723 return NULL;
724 return PyFloat_FromDouble(r);
725}
726
Christian Heimes53876d92008-04-19 00:31:39 +0000727/*
728 math_2 is used to wrap a libm function f that takes two double
729 arguments and returns a double.
730
731 The error reporting follows these rules, which are designed to do
732 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
733 platforms.
734
735 - a NaN result from non-NaN inputs causes ValueError to be raised
736 - an infinite result from finite inputs causes OverflowError to be
737 raised.
738 - if the result is finite and errno == EDOM then ValueError is
739 raised
740 - if the result is finite and nonzero and errno == ERANGE then
741 OverflowError is raised
742
743 The last rule is used to catch overflow on platforms which follow
744 C89 but for which HUGE_VAL is not an infinity.
745
746 For most two-argument functions (copysign, fmod, hypot, atan2)
747 these rules are enough to ensure that Python's functions behave as
748 specified in 'Annex F' of the C99 standard, with the 'invalid' and
749 'divide-by-zero' floating-point exceptions mapping to Python's
750 ValueError and the 'overflow' floating-point exception mapping to
751 OverflowError.
752*/
753
754static PyObject *
755math_1(PyObject *arg, double (*func) (double), int can_overflow)
756{
757 return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow);
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000758}
759
760static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000761math_1_to_int(PyObject *arg, double (*func) (double), int can_overflow)
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000762{
Christian Heimes53876d92008-04-19 00:31:39 +0000763 return math_1_to_whatever(arg, func, PyLong_FromDouble, can_overflow);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000764}
765
Barry Warsaw8b43b191996-12-09 22:32:36 +0000766static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +0000767math_2(PyObject *args, double (*func) (double, double), char *funcname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000768{
Thomas Wouters89f507f2006-12-13 04:49:30 +0000769 PyObject *ox, *oy;
Christian Heimes53876d92008-04-19 00:31:39 +0000770 double x, y, r;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000771 if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy))
772 return NULL;
773 x = PyFloat_AsDouble(ox);
774 y = PyFloat_AsDouble(oy);
775 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000776 return NULL;
777 errno = 0;
Christian Heimes53876d92008-04-19 00:31:39 +0000778 PyFPE_START_PROTECT("in math_2", return 0);
779 r = (*func)(x, y);
780 PyFPE_END_PROTECT(r);
781 if (Py_IS_NAN(r)) {
782 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
783 errno = EDOM;
784 else
785 errno = 0;
786 }
787 else if (Py_IS_INFINITY(r)) {
788 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
789 errno = ERANGE;
790 else
791 errno = 0;
792 }
793 if (errno && is_error(r))
Tim Peters1d120612000-10-12 06:10:25 +0000794 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000795 else
Christian Heimes53876d92008-04-19 00:31:39 +0000796 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000797}
798
Christian Heimes53876d92008-04-19 00:31:39 +0000799#define FUNC1(funcname, func, can_overflow, docstring) \
Fred Drake40c48682000-07-03 18:11:56 +0000800 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
Christian Heimes53876d92008-04-19 00:31:39 +0000801 return math_1(args, func, can_overflow); \
Guido van Rossumc6e22901998-12-04 19:26:43 +0000802 }\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000803 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000804
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000805#define FUNC1A(funcname, func, docstring) \
806 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
807 return math_1a(args, func); \
808 }\
809 PyDoc_STRVAR(math_##funcname##_doc, docstring);
810
Fred Drake40c48682000-07-03 18:11:56 +0000811#define FUNC2(funcname, func, docstring) \
812 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
Thomas Wouters89f507f2006-12-13 04:49:30 +0000813 return math_2(args, func, #funcname); \
Guido van Rossumc6e22901998-12-04 19:26:43 +0000814 }\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000815 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000816
Christian Heimes53876d92008-04-19 00:31:39 +0000817FUNC1(acos, acos, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000818 "acos(x)\n\nReturn the arc cosine (measured in radians) of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000819FUNC1(acosh, acosh, 0,
820 "acosh(x)\n\nReturn the hyperbolic arc cosine (measured in radians) of x.")
821FUNC1(asin, asin, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000822 "asin(x)\n\nReturn the arc sine (measured in radians) of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000823FUNC1(asinh, asinh, 0,
824 "asinh(x)\n\nReturn the hyperbolic arc sine (measured in radians) of x.")
825FUNC1(atan, atan, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000826 "atan(x)\n\nReturn the arc tangent (measured in radians) of x.")
Christian Heimese57950f2008-04-21 13:08:03 +0000827FUNC2(atan2, m_atan2,
Tim Petersfe71f812001-08-07 22:10:00 +0000828 "atan2(y, x)\n\nReturn the arc tangent (measured in radians) of y/x.\n"
829 "Unlike atan(y/x), the signs of both x and y are considered.")
Christian Heimes53876d92008-04-19 00:31:39 +0000830FUNC1(atanh, atanh, 0,
831 "atanh(x)\n\nReturn the hyperbolic arc tangent (measured in radians) of x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +0000832
833static PyObject * math_ceil(PyObject *self, PyObject *number) {
834 static PyObject *ceil_str = NULL;
835 PyObject *method;
836
837 if (ceil_str == NULL) {
Christian Heimesfe82e772008-01-28 02:38:20 +0000838 ceil_str = PyUnicode_InternFromString("__ceil__");
Guido van Rossum13e05de2007-08-23 22:56:55 +0000839 if (ceil_str == NULL)
840 return NULL;
841 }
842
Christian Heimes90aa7642007-12-19 02:45:37 +0000843 method = _PyType_Lookup(Py_TYPE(number), ceil_str);
Guido van Rossum13e05de2007-08-23 22:56:55 +0000844 if (method == NULL)
Christian Heimes53876d92008-04-19 00:31:39 +0000845 return math_1_to_int(number, ceil, 0);
Guido van Rossum13e05de2007-08-23 22:56:55 +0000846 else
847 return PyObject_CallFunction(method, "O", number);
848}
849
850PyDoc_STRVAR(math_ceil_doc,
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000851 "ceil(x)\n\nReturn the ceiling of x as an int.\n"
Guido van Rossum13e05de2007-08-23 22:56:55 +0000852 "This is the smallest integral value >= x.");
853
Christian Heimes072c0f12008-01-03 23:01:04 +0000854FUNC2(copysign, copysign,
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000855 "copysign(x, y)\n\nReturn x with the sign of y.")
Christian Heimes53876d92008-04-19 00:31:39 +0000856FUNC1(cos, cos, 0,
857 "cos(x)\n\nReturn the cosine of x (measured in radians).")
858FUNC1(cosh, cosh, 1,
859 "cosh(x)\n\nReturn the hyperbolic cosine of x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +0000860FUNC1A(erf, m_erf,
861 "erf(x)\n\nError function at x.")
862FUNC1A(erfc, m_erfc,
863 "erfc(x)\n\nComplementary error function at x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000864FUNC1(exp, exp, 1,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000865 "exp(x)\n\nReturn e raised to the power of x.")
Mark Dickinson664b5112009-12-16 20:23:42 +0000866FUNC1(expm1, m_expm1, 1,
867 "expm1(x)\n\nReturn exp(x)-1.\n"
868 "This function avoids the loss of precision involved in the direct "
869 "evaluation of exp(x)-1 for small x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000870FUNC1(fabs, fabs, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000871 "fabs(x)\n\nReturn the absolute value of the float x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +0000872
873static PyObject * math_floor(PyObject *self, PyObject *number) {
874 static PyObject *floor_str = NULL;
875 PyObject *method;
876
877 if (floor_str == NULL) {
Christian Heimesfe82e772008-01-28 02:38:20 +0000878 floor_str = PyUnicode_InternFromString("__floor__");
Guido van Rossum13e05de2007-08-23 22:56:55 +0000879 if (floor_str == NULL)
880 return NULL;
881 }
882
Christian Heimes90aa7642007-12-19 02:45:37 +0000883 method = _PyType_Lookup(Py_TYPE(number), floor_str);
Guido van Rossum13e05de2007-08-23 22:56:55 +0000884 if (method == NULL)
Christian Heimes53876d92008-04-19 00:31:39 +0000885 return math_1_to_int(number, floor, 0);
Guido van Rossum13e05de2007-08-23 22:56:55 +0000886 else
887 return PyObject_CallFunction(method, "O", number);
888}
889
890PyDoc_STRVAR(math_floor_doc,
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000891 "floor(x)\n\nReturn the floor of x as an int.\n"
Guido van Rossum13e05de2007-08-23 22:56:55 +0000892 "This is the largest integral value <= x.");
893
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000894FUNC1A(gamma, m_tgamma,
895 "gamma(x)\n\nGamma function at x.")
Mark Dickinson05d2e082009-12-11 20:17:17 +0000896FUNC1A(lgamma, m_lgamma,
897 "lgamma(x)\n\nNatural logarithm of absolute value of Gamma function at x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000898FUNC1(log1p, log1p, 1,
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000899 "log1p(x)\n\nReturn the natural logarithm of 1+x (base e).\n"
900 "The result is computed in a way which is accurate for x near zero.")
Christian Heimes53876d92008-04-19 00:31:39 +0000901FUNC1(sin, sin, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000902 "sin(x)\n\nReturn the sine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +0000903FUNC1(sinh, sinh, 1,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000904 "sinh(x)\n\nReturn the hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000905FUNC1(sqrt, sqrt, 0,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000906 "sqrt(x)\n\nReturn the square root of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000907FUNC1(tan, tan, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000908 "tan(x)\n\nReturn the tangent of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +0000909FUNC1(tanh, tanh, 0,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000910 "tanh(x)\n\nReturn the hyperbolic tangent of x.")
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000911
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000912/* Precision summation function as msum() by Raymond Hettinger in
913 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
914 enhanced with the exact partials sum and roundoff from Mark
915 Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
916 See those links for more details, proofs and other references.
917
918 Note 1: IEEE 754R floating point semantics are assumed,
919 but the current implementation does not re-establish special
920 value semantics across iterations (i.e. handling -Inf + Inf).
921
922 Note 2: No provision is made for intermediate overflow handling;
Georg Brandlf78e02b2008-06-10 17:40:04 +0000923 therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000924 sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
925 overflow of the first partial sum.
926
Benjamin Petersonfea6a942008-07-02 16:11:42 +0000927 Note 3: The intermediate values lo, yr, and hi are declared volatile so
928 aggressive compilers won't algebraically reduce lo to always be exactly 0.0.
Georg Brandlf78e02b2008-06-10 17:40:04 +0000929 Also, the volatile declaration forces the values to be stored in memory as
930 regular doubles instead of extended long precision (80-bit) values. This
Benjamin Petersonfea6a942008-07-02 16:11:42 +0000931 prevents double rounding because any addition or subtraction of two doubles
Georg Brandlf78e02b2008-06-10 17:40:04 +0000932 can be resolved exactly into double-sized hi and lo values. As long as the
933 hi value gets forced into a double before yr and lo are computed, the extra
934 bits in downstream extended precision operations (x87 for example) will be
935 exactly zero and therefore can be losslessly stored back into a double,
936 thereby preventing double rounding.
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000937
938 Note 4: A similar implementation is in Modules/cmathmodule.c.
939 Be sure to update both when making changes.
940
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000941 Note 5: The signature of math.fsum() differs from __builtin__.sum()
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000942 because the start argument doesn't make sense in the context of
943 accurate summation. Since the partials table is collapsed before
944 returning a result, sum(seq2, start=sum(seq1)) may not equal the
945 accurate result returned by sum(itertools.chain(seq1, seq2)).
946*/
947
948#define NUM_PARTIALS 32 /* initial partials array size, on stack */
949
950/* Extend the partials array p[] by doubling its size. */
951static int /* non-zero on error */
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000952_fsum_realloc(double **p_ptr, Py_ssize_t n,
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000953 double *ps, Py_ssize_t *m_ptr)
954{
955 void *v = NULL;
956 Py_ssize_t m = *m_ptr;
957
958 m += m; /* double */
959 if (n < m && m < (PY_SSIZE_T_MAX / sizeof(double))) {
960 double *p = *p_ptr;
961 if (p == ps) {
962 v = PyMem_Malloc(sizeof(double) * m);
963 if (v != NULL)
964 memcpy(v, ps, sizeof(double) * n);
965 }
966 else
967 v = PyMem_Realloc(p, sizeof(double) * m);
968 }
969 if (v == NULL) { /* size overflow or no memory */
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000970 PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000971 return 1;
972 }
973 *p_ptr = (double*) v;
974 *m_ptr = m;
975 return 0;
976}
977
978/* Full precision summation of a sequence of floats.
979
980 def msum(iterable):
981 partials = [] # sorted, non-overlapping partial sums
982 for x in iterable:
983 i = 0
984 for y in partials:
985 if abs(x) < abs(y):
986 x, y = y, x
987 hi = x + y
988 lo = y - (hi - x)
989 if lo:
990 partials[i] = lo
991 i += 1
992 x = hi
993 partials[i:] = [x]
994 return sum_exact(partials)
995
996 Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
997 are exactly equal to x+y. The inner loop applies hi/lo summation to each
998 partial so that the list of partial sums remains exact.
999
1000 Sum_exact() adds the partial sums exactly and correctly rounds the final
1001 result (using the round-half-to-even rule). The items in partials remain
1002 non-zero, non-special, non-overlapping and strictly increasing in
1003 magnitude, but possibly not all having the same sign.
1004
1005 Depends on IEEE 754 arithmetic guarantees and half-even rounding.
1006*/
1007
1008static PyObject*
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001009math_fsum(PyObject *self, PyObject *seq)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001010{
1011 PyObject *item, *iter, *sum = NULL;
1012 Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
Georg Brandlf78e02b2008-06-10 17:40:04 +00001013 double x, y, t, ps[NUM_PARTIALS], *p = ps;
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001014 double xsave, special_sum = 0.0, inf_sum = 0.0;
Georg Brandlf78e02b2008-06-10 17:40:04 +00001015 volatile double hi, yr, lo;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001016
1017 iter = PyObject_GetIter(seq);
1018 if (iter == NULL)
1019 return NULL;
1020
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001021 PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001022
1023 for(;;) { /* for x in iterable */
1024 assert(0 <= n && n <= m);
1025 assert((m == NUM_PARTIALS && p == ps) ||
1026 (m > NUM_PARTIALS && p != NULL));
1027
1028 item = PyIter_Next(iter);
1029 if (item == NULL) {
1030 if (PyErr_Occurred())
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001031 goto _fsum_error;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001032 break;
1033 }
1034 x = PyFloat_AsDouble(item);
1035 Py_DECREF(item);
1036 if (PyErr_Occurred())
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001037 goto _fsum_error;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001038
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001039 xsave = x;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001040 for (i = j = 0; j < n; j++) { /* for y in partials */
1041 y = p[j];
Georg Brandlf78e02b2008-06-10 17:40:04 +00001042 if (fabs(x) < fabs(y)) {
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001043 t = x; x = y; y = t;
Georg Brandlf78e02b2008-06-10 17:40:04 +00001044 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001045 hi = x + y;
Georg Brandlf78e02b2008-06-10 17:40:04 +00001046 yr = hi - x;
1047 lo = y - yr;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001048 if (lo != 0.0)
1049 p[i++] = lo;
1050 x = hi;
1051 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001052
1053 n = i; /* ps[i:] = [x] */
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001054 if (x != 0.0) {
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001055 if (! Py_IS_FINITE(x)) {
1056 /* a nonfinite x could arise either as
1057 a result of intermediate overflow, or
1058 as a result of a nan or inf in the
1059 summands */
1060 if (Py_IS_FINITE(xsave)) {
1061 PyErr_SetString(PyExc_OverflowError,
1062 "intermediate overflow in fsum");
1063 goto _fsum_error;
1064 }
1065 if (Py_IS_INFINITY(xsave))
1066 inf_sum += xsave;
1067 special_sum += xsave;
1068 /* reset partials */
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001069 n = 0;
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001070 }
1071 else if (n >= m && _fsum_realloc(&p, n, ps, &m))
1072 goto _fsum_error;
1073 else
1074 p[n++] = x;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001075 }
1076 }
1077
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001078 if (special_sum != 0.0) {
1079 if (Py_IS_NAN(inf_sum))
1080 PyErr_SetString(PyExc_ValueError,
1081 "-inf + inf in fsum");
1082 else
1083 sum = PyFloat_FromDouble(special_sum);
1084 goto _fsum_error;
1085 }
1086
Georg Brandlf78e02b2008-06-10 17:40:04 +00001087 hi = 0.0;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001088 if (n > 0) {
1089 hi = p[--n];
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001090 /* sum_exact(ps, hi) from the top, stop when the sum becomes
1091 inexact. */
1092 while (n > 0) {
1093 x = hi;
1094 y = p[--n];
1095 assert(fabs(y) < fabs(x));
1096 hi = x + y;
1097 yr = hi - x;
1098 lo = y - yr;
1099 if (lo != 0.0)
1100 break;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001101 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001102 /* Make half-even rounding work across multiple partials.
1103 Needed so that sum([1e-16, 1, 1e16]) will round-up the last
1104 digit to two instead of down to zero (the 1e-16 makes the 1
1105 slightly closer to two). With a potential 1 ULP rounding
1106 error fixed-up, math.fsum() can guarantee commutativity. */
1107 if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
1108 (lo > 0.0 && p[n-1] > 0.0))) {
1109 y = lo * 2.0;
1110 x = hi + y;
1111 yr = x - hi;
1112 if (y == yr)
1113 hi = x;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001114 }
1115 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001116 sum = PyFloat_FromDouble(hi);
1117
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001118_fsum_error:
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001119 PyFPE_END_PROTECT(hi)
1120 Py_DECREF(iter);
1121 if (p != ps)
1122 PyMem_Free(p);
1123 return sum;
1124}
1125
1126#undef NUM_PARTIALS
1127
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001128PyDoc_STRVAR(math_fsum_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001129"fsum(iterable)\n\n\
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001130Return an accurate floating point sum of values in the iterable.\n\
1131Assumes IEEE-754 floating point arithmetic.");
1132
Barry Warsaw8b43b191996-12-09 22:32:36 +00001133static PyObject *
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001134math_factorial(PyObject *self, PyObject *arg)
1135{
1136 long i, x;
1137 PyObject *result, *iobj, *newresult;
1138
1139 if (PyFloat_Check(arg)) {
Mark Dickinsonda39dbf2009-12-20 14:07:47 +00001140 PyObject *lx;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001141 double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
Mark Dickinsonda39dbf2009-12-20 14:07:47 +00001142 if (!(Py_IS_FINITE(dx) && dx == floor(dx))) {
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001143 PyErr_SetString(PyExc_ValueError,
1144 "factorial() only accepts integral values");
1145 return NULL;
1146 }
Mark Dickinsonda39dbf2009-12-20 14:07:47 +00001147 lx = PyLong_FromDouble(dx);
1148 if (lx == NULL)
1149 return NULL;
1150 x = PyLong_AsLong(lx);
1151 Py_DECREF(lx);
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001152 }
Mark Dickinsonda39dbf2009-12-20 14:07:47 +00001153 else
1154 x = PyLong_AsLong(arg);
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001155
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001156 if (x == -1 && PyErr_Occurred())
1157 return NULL;
1158 if (x < 0) {
1159 PyErr_SetString(PyExc_ValueError,
1160 "factorial() not defined for negative values");
1161 return NULL;
1162 }
1163
1164 result = (PyObject *)PyLong_FromLong(1);
1165 if (result == NULL)
1166 return NULL;
1167 for (i=1 ; i<=x ; i++) {
1168 iobj = (PyObject *)PyLong_FromLong(i);
1169 if (iobj == NULL)
1170 goto error;
1171 newresult = PyNumber_Multiply(result, iobj);
1172 Py_DECREF(iobj);
1173 if (newresult == NULL)
1174 goto error;
1175 Py_DECREF(result);
1176 result = newresult;
1177 }
1178 return result;
1179
1180error:
1181 Py_DECREF(result);
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001182 return NULL;
1183}
1184
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001185PyDoc_STRVAR(math_factorial_doc,
1186"factorial(x) -> Integral\n"
1187"\n"
1188"Find x!. Raise a ValueError if x is negative or non-integral.");
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001189
1190static PyObject *
Christian Heimes400adb02008-02-01 08:12:03 +00001191math_trunc(PyObject *self, PyObject *number)
1192{
1193 static PyObject *trunc_str = NULL;
1194 PyObject *trunc;
1195
1196 if (Py_TYPE(number)->tp_dict == NULL) {
1197 if (PyType_Ready(Py_TYPE(number)) < 0)
1198 return NULL;
1199 }
1200
1201 if (trunc_str == NULL) {
1202 trunc_str = PyUnicode_InternFromString("__trunc__");
1203 if (trunc_str == NULL)
1204 return NULL;
1205 }
1206
1207 trunc = _PyType_Lookup(Py_TYPE(number), trunc_str);
1208 if (trunc == NULL) {
1209 PyErr_Format(PyExc_TypeError,
1210 "type %.100s doesn't define __trunc__ method",
1211 Py_TYPE(number)->tp_name);
1212 return NULL;
1213 }
1214 return PyObject_CallFunctionObjArgs(trunc, number, NULL);
1215}
1216
1217PyDoc_STRVAR(math_trunc_doc,
1218"trunc(x:Real) -> Integral\n"
1219"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001220"Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.");
Christian Heimes400adb02008-02-01 08:12:03 +00001221
1222static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001223math_frexp(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001224{
Guido van Rossumd18ad581991-10-24 14:57:21 +00001225 int i;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001226 double x = PyFloat_AsDouble(arg);
1227 if (x == -1.0 && PyErr_Occurred())
Guido van Rossumd18ad581991-10-24 14:57:21 +00001228 return NULL;
Christian Heimes53876d92008-04-19 00:31:39 +00001229 /* deal with special cases directly, to sidestep platform
1230 differences */
1231 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
1232 i = 0;
1233 }
1234 else {
1235 PyFPE_START_PROTECT("in math_frexp", return 0);
1236 x = frexp(x, &i);
1237 PyFPE_END_PROTECT(x);
1238 }
1239 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001240}
1241
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001242PyDoc_STRVAR(math_frexp_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001243"frexp(x)\n"
1244"\n"
1245"Return the mantissa and exponent of x, as pair (m, e).\n"
1246"m is a float and e is an int, such that x = m * 2.**e.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001247"If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001248
Barry Warsaw8b43b191996-12-09 22:32:36 +00001249static PyObject *
Fred Drake40c48682000-07-03 18:11:56 +00001250math_ldexp(PyObject *self, PyObject *args)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001251{
Christian Heimes53876d92008-04-19 00:31:39 +00001252 double x, r;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001253 PyObject *oexp;
1254 long exp;
1255 if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp))
Guido van Rossumd18ad581991-10-24 14:57:21 +00001256 return NULL;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001257
1258 if (PyLong_Check(oexp)) {
1259 /* on overflow, replace exponent with either LONG_MAX
1260 or LONG_MIN, depending on the sign. */
1261 exp = PyLong_AsLong(oexp);
1262 if (exp == -1 && PyErr_Occurred()) {
1263 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1264 if (Py_SIZE(oexp) < 0) {
1265 exp = LONG_MIN;
1266 }
1267 else {
1268 exp = LONG_MAX;
1269 }
1270 PyErr_Clear();
1271 }
1272 else {
1273 /* propagate any unexpected exception */
1274 return NULL;
1275 }
1276 }
1277 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001278 else {
1279 PyErr_SetString(PyExc_TypeError,
1280 "Expected an int or long as second argument "
1281 "to ldexp.");
1282 return NULL;
1283 }
1284
1285 if (x == 0. || !Py_IS_FINITE(x)) {
1286 /* NaNs, zeros and infinities are returned unchanged */
1287 r = x;
Christian Heimes53876d92008-04-19 00:31:39 +00001288 errno = 0;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001289 } else if (exp > INT_MAX) {
1290 /* overflow */
1291 r = copysign(Py_HUGE_VAL, x);
1292 errno = ERANGE;
1293 } else if (exp < INT_MIN) {
1294 /* underflow to +-0 */
1295 r = copysign(0., x);
1296 errno = 0;
1297 } else {
1298 errno = 0;
1299 PyFPE_START_PROTECT("in math_ldexp", return 0);
1300 r = ldexp(x, (int)exp);
1301 PyFPE_END_PROTECT(r);
1302 if (Py_IS_INFINITY(r))
1303 errno = ERANGE;
1304 }
1305
Christian Heimes53876d92008-04-19 00:31:39 +00001306 if (errno && is_error(r))
Tim Peters1d120612000-10-12 06:10:25 +00001307 return NULL;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001308 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001309}
1310
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001311PyDoc_STRVAR(math_ldexp_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001312"ldexp(x, i)\n\n\
1313Return x * (2**i).");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001314
Barry Warsaw8b43b191996-12-09 22:32:36 +00001315static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001316math_modf(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001317{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001318 double y, x = PyFloat_AsDouble(arg);
1319 if (x == -1.0 && PyErr_Occurred())
Guido van Rossumd18ad581991-10-24 14:57:21 +00001320 return NULL;
Christian Heimesa342c012008-04-20 21:01:16 +00001321 /* some platforms don't do the right thing for NaNs and
1322 infinities, so we take care of special cases directly. */
1323 if (!Py_IS_FINITE(x)) {
1324 if (Py_IS_INFINITY(x))
1325 return Py_BuildValue("(dd)", copysign(0., x), x);
1326 else if (Py_IS_NAN(x))
1327 return Py_BuildValue("(dd)", x, x);
1328 }
1329
Guido van Rossumd18ad581991-10-24 14:57:21 +00001330 errno = 0;
Christian Heimes53876d92008-04-19 00:31:39 +00001331 PyFPE_START_PROTECT("in math_modf", return 0);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001332 x = modf(x, &y);
Christian Heimes53876d92008-04-19 00:31:39 +00001333 PyFPE_END_PROTECT(x);
1334 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001335}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001336
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001337PyDoc_STRVAR(math_modf_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001338"modf(x)\n"
1339"\n"
1340"Return the fractional and integer parts of x. Both results carry the sign\n"
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001341"of x and are floats.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001342
Tim Peters78526162001-09-05 00:53:45 +00001343/* A decent logarithm is easy to compute even for huge longs, but libm can't
1344 do that by itself -- loghelper can. func is log or log10, and name is
1345 "log" or "log10". Note that overflow isn't possible: a long can contain
1346 no more than INT_MAX * SHIFT bits, so has value certainly less than
1347 2**(2**64 * 2**16) == 2**2**80, and log2 of that is 2**80, which is
1348 small enough to fit in an IEEE single. log and log10 are even smaller.
1349*/
1350
1351static PyObject*
Thomas Wouters89f507f2006-12-13 04:49:30 +00001352loghelper(PyObject* arg, double (*func)(double), char *funcname)
Tim Peters78526162001-09-05 00:53:45 +00001353{
Tim Peters78526162001-09-05 00:53:45 +00001354 /* If it is long, do it ourselves. */
1355 if (PyLong_Check(arg)) {
1356 double x;
1357 int e;
1358 x = _PyLong_AsScaledDouble(arg, &e);
1359 if (x <= 0.0) {
1360 PyErr_SetString(PyExc_ValueError,
1361 "math domain error");
1362 return NULL;
1363 }
Christian Heimesaf98da12008-01-27 15:18:18 +00001364 /* Value is ~= x * 2**(e*PyLong_SHIFT), so the log ~=
1365 log(x) + log(2) * e * PyLong_SHIFT.
1366 CAUTION: e*PyLong_SHIFT may overflow using int arithmetic,
Tim Peters78526162001-09-05 00:53:45 +00001367 so force use of double. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001368 x = func(x) + (e * (double)PyLong_SHIFT) * func(2.0);
Tim Peters78526162001-09-05 00:53:45 +00001369 return PyFloat_FromDouble(x);
1370 }
1371
1372 /* Else let libm handle it by itself. */
Christian Heimes53876d92008-04-19 00:31:39 +00001373 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +00001374}
1375
1376static PyObject *
1377math_log(PyObject *self, PyObject *args)
1378{
Raymond Hettinger866964c2002-12-14 19:51:34 +00001379 PyObject *arg;
1380 PyObject *base = NULL;
1381 PyObject *num, *den;
1382 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001383
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001384 if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base))
Raymond Hettinger866964c2002-12-14 19:51:34 +00001385 return NULL;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001386
Mark Dickinsone675f082008-12-11 21:56:00 +00001387 num = loghelper(arg, m_log, "log");
Thomas Wouters89f507f2006-12-13 04:49:30 +00001388 if (num == NULL || base == NULL)
1389 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001390
Mark Dickinsone675f082008-12-11 21:56:00 +00001391 den = loghelper(base, m_log, "log");
Raymond Hettinger866964c2002-12-14 19:51:34 +00001392 if (den == NULL) {
1393 Py_DECREF(num);
1394 return NULL;
1395 }
1396
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001397 ans = PyNumber_TrueDivide(num, den);
Raymond Hettinger866964c2002-12-14 19:51:34 +00001398 Py_DECREF(num);
1399 Py_DECREF(den);
1400 return ans;
Tim Peters78526162001-09-05 00:53:45 +00001401}
1402
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001403PyDoc_STRVAR(math_log_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001404"log(x[, base])\n\n\
1405Return the logarithm of x to the given base.\n\
Raymond Hettinger866964c2002-12-14 19:51:34 +00001406If the base not specified, returns the natural logarithm (base e) of x.");
Tim Peters78526162001-09-05 00:53:45 +00001407
1408static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001409math_log10(PyObject *self, PyObject *arg)
Tim Peters78526162001-09-05 00:53:45 +00001410{
Mark Dickinsone675f082008-12-11 21:56:00 +00001411 return loghelper(arg, m_log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +00001412}
1413
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001414PyDoc_STRVAR(math_log10_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001415"log10(x)\n\nReturn the base 10 logarithm of x.");
Tim Peters78526162001-09-05 00:53:45 +00001416
Christian Heimes53876d92008-04-19 00:31:39 +00001417static PyObject *
1418math_fmod(PyObject *self, PyObject *args)
1419{
1420 PyObject *ox, *oy;
1421 double r, x, y;
1422 if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy))
1423 return NULL;
1424 x = PyFloat_AsDouble(ox);
1425 y = PyFloat_AsDouble(oy);
1426 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1427 return NULL;
1428 /* fmod(x, +/-Inf) returns x for finite x. */
1429 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
1430 return PyFloat_FromDouble(x);
1431 errno = 0;
1432 PyFPE_START_PROTECT("in math_fmod", return 0);
1433 r = fmod(x, y);
1434 PyFPE_END_PROTECT(r);
1435 if (Py_IS_NAN(r)) {
1436 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1437 errno = EDOM;
1438 else
1439 errno = 0;
1440 }
1441 if (errno && is_error(r))
1442 return NULL;
1443 else
1444 return PyFloat_FromDouble(r);
1445}
1446
1447PyDoc_STRVAR(math_fmod_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001448"fmod(x, y)\n\nReturn fmod(x, y), according to platform C."
Christian Heimes53876d92008-04-19 00:31:39 +00001449" x % y may differ.");
1450
1451static PyObject *
1452math_hypot(PyObject *self, PyObject *args)
1453{
1454 PyObject *ox, *oy;
1455 double r, x, y;
1456 if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy))
1457 return NULL;
1458 x = PyFloat_AsDouble(ox);
1459 y = PyFloat_AsDouble(oy);
1460 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1461 return NULL;
1462 /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */
1463 if (Py_IS_INFINITY(x))
1464 return PyFloat_FromDouble(fabs(x));
1465 if (Py_IS_INFINITY(y))
1466 return PyFloat_FromDouble(fabs(y));
1467 errno = 0;
1468 PyFPE_START_PROTECT("in math_hypot", return 0);
1469 r = hypot(x, y);
1470 PyFPE_END_PROTECT(r);
1471 if (Py_IS_NAN(r)) {
1472 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1473 errno = EDOM;
1474 else
1475 errno = 0;
1476 }
1477 else if (Py_IS_INFINITY(r)) {
1478 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
1479 errno = ERANGE;
1480 else
1481 errno = 0;
1482 }
1483 if (errno && is_error(r))
1484 return NULL;
1485 else
1486 return PyFloat_FromDouble(r);
1487}
1488
1489PyDoc_STRVAR(math_hypot_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001490"hypot(x, y)\n\nReturn the Euclidean distance, sqrt(x*x + y*y).");
Christian Heimes53876d92008-04-19 00:31:39 +00001491
1492/* pow can't use math_2, but needs its own wrapper: the problem is
1493 that an infinite result can arise either as a result of overflow
1494 (in which case OverflowError should be raised) or as a result of
1495 e.g. 0.**-5. (for which ValueError needs to be raised.)
1496*/
1497
1498static PyObject *
1499math_pow(PyObject *self, PyObject *args)
1500{
1501 PyObject *ox, *oy;
1502 double r, x, y;
Christian Heimesa342c012008-04-20 21:01:16 +00001503 int odd_y;
Christian Heimes53876d92008-04-19 00:31:39 +00001504
1505 if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy))
1506 return NULL;
1507 x = PyFloat_AsDouble(ox);
1508 y = PyFloat_AsDouble(oy);
1509 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1510 return NULL;
Christian Heimesa342c012008-04-20 21:01:16 +00001511
1512 /* deal directly with IEEE specials, to cope with problems on various
1513 platforms whose semantics don't exactly match C99 */
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001514 r = 0.; /* silence compiler warning */
Christian Heimesa342c012008-04-20 21:01:16 +00001515 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
1516 errno = 0;
1517 if (Py_IS_NAN(x))
1518 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
1519 else if (Py_IS_NAN(y))
1520 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
1521 else if (Py_IS_INFINITY(x)) {
1522 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
1523 if (y > 0.)
1524 r = odd_y ? x : fabs(x);
1525 else if (y == 0.)
1526 r = 1.;
1527 else /* y < 0. */
1528 r = odd_y ? copysign(0., x) : 0.;
1529 }
1530 else if (Py_IS_INFINITY(y)) {
1531 if (fabs(x) == 1.0)
1532 r = 1.;
1533 else if (y > 0. && fabs(x) > 1.0)
1534 r = y;
1535 else if (y < 0. && fabs(x) < 1.0) {
1536 r = -y; /* result is +inf */
1537 if (x == 0.) /* 0**-inf: divide-by-zero */
1538 errno = EDOM;
1539 }
1540 else
1541 r = 0.;
1542 }
Christian Heimes53876d92008-04-19 00:31:39 +00001543 }
Christian Heimesa342c012008-04-20 21:01:16 +00001544 else {
1545 /* let libm handle finite**finite */
1546 errno = 0;
1547 PyFPE_START_PROTECT("in math_pow", return 0);
1548 r = pow(x, y);
1549 PyFPE_END_PROTECT(r);
1550 /* a NaN result should arise only from (-ve)**(finite
1551 non-integer); in this case we want to raise ValueError. */
1552 if (!Py_IS_FINITE(r)) {
1553 if (Py_IS_NAN(r)) {
1554 errno = EDOM;
1555 }
1556 /*
1557 an infinite result here arises either from:
1558 (A) (+/-0.)**negative (-> divide-by-zero)
1559 (B) overflow of x**y with x and y finite
1560 */
1561 else if (Py_IS_INFINITY(r)) {
1562 if (x == 0.)
1563 errno = EDOM;
1564 else
1565 errno = ERANGE;
1566 }
1567 }
Christian Heimes53876d92008-04-19 00:31:39 +00001568 }
1569
1570 if (errno && is_error(r))
1571 return NULL;
1572 else
1573 return PyFloat_FromDouble(r);
1574}
1575
1576PyDoc_STRVAR(math_pow_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001577"pow(x, y)\n\nReturn x**y (x to the power of y).");
Christian Heimes53876d92008-04-19 00:31:39 +00001578
Christian Heimes072c0f12008-01-03 23:01:04 +00001579static const double degToRad = Py_MATH_PI / 180.0;
1580static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001581
1582static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001583math_degrees(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001584{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001585 double x = PyFloat_AsDouble(arg);
1586 if (x == -1.0 && PyErr_Occurred())
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001587 return NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +00001588 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001589}
1590
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001591PyDoc_STRVAR(math_degrees_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001592"degrees(x)\n\n\
1593Convert angle x from radians to degrees.");
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001594
1595static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001596math_radians(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001597{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001598 double x = PyFloat_AsDouble(arg);
1599 if (x == -1.0 && PyErr_Occurred())
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001600 return NULL;
1601 return PyFloat_FromDouble(x * degToRad);
1602}
1603
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001604PyDoc_STRVAR(math_radians_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001605"radians(x)\n\n\
1606Convert angle x from degrees to radians.");
Tim Peters78526162001-09-05 00:53:45 +00001607
Christian Heimes072c0f12008-01-03 23:01:04 +00001608static PyObject *
1609math_isnan(PyObject *self, PyObject *arg)
1610{
1611 double x = PyFloat_AsDouble(arg);
1612 if (x == -1.0 && PyErr_Occurred())
1613 return NULL;
1614 return PyBool_FromLong((long)Py_IS_NAN(x));
1615}
1616
1617PyDoc_STRVAR(math_isnan_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001618"isnan(x) -> bool\n\n\
1619Check if float x is not a number (NaN).");
Christian Heimes072c0f12008-01-03 23:01:04 +00001620
1621static PyObject *
1622math_isinf(PyObject *self, PyObject *arg)
1623{
1624 double x = PyFloat_AsDouble(arg);
1625 if (x == -1.0 && PyErr_Occurred())
1626 return NULL;
1627 return PyBool_FromLong((long)Py_IS_INFINITY(x));
1628}
1629
1630PyDoc_STRVAR(math_isinf_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001631"isinf(x) -> bool\n\n\
1632Check if float x is infinite (positive or negative).");
Christian Heimes072c0f12008-01-03 23:01:04 +00001633
Barry Warsaw8b43b191996-12-09 22:32:36 +00001634static PyMethodDef math_methods[] = {
Thomas Wouters89f507f2006-12-13 04:49:30 +00001635 {"acos", math_acos, METH_O, math_acos_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001636 {"acosh", math_acosh, METH_O, math_acosh_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001637 {"asin", math_asin, METH_O, math_asin_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001638 {"asinh", math_asinh, METH_O, math_asinh_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001639 {"atan", math_atan, METH_O, math_atan_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001640 {"atan2", math_atan2, METH_VARARGS, math_atan2_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001641 {"atanh", math_atanh, METH_O, math_atanh_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001642 {"ceil", math_ceil, METH_O, math_ceil_doc},
Christian Heimes072c0f12008-01-03 23:01:04 +00001643 {"copysign", math_copysign, METH_VARARGS, math_copysign_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001644 {"cos", math_cos, METH_O, math_cos_doc},
1645 {"cosh", math_cosh, METH_O, math_cosh_doc},
1646 {"degrees", math_degrees, METH_O, math_degrees_doc},
Mark Dickinson45f992a2009-12-19 11:20:49 +00001647 {"erf", math_erf, METH_O, math_erf_doc},
1648 {"erfc", math_erfc, METH_O, math_erfc_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001649 {"exp", math_exp, METH_O, math_exp_doc},
Mark Dickinson664b5112009-12-16 20:23:42 +00001650 {"expm1", math_expm1, METH_O, math_expm1_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001651 {"fabs", math_fabs, METH_O, math_fabs_doc},
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001652 {"factorial", math_factorial, METH_O, math_factorial_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001653 {"floor", math_floor, METH_O, math_floor_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001654 {"fmod", math_fmod, METH_VARARGS, math_fmod_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001655 {"frexp", math_frexp, METH_O, math_frexp_doc},
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001656 {"fsum", math_fsum, METH_O, math_fsum_doc},
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001657 {"gamma", math_gamma, METH_O, math_gamma_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001658 {"hypot", math_hypot, METH_VARARGS, math_hypot_doc},
Christian Heimes072c0f12008-01-03 23:01:04 +00001659 {"isinf", math_isinf, METH_O, math_isinf_doc},
1660 {"isnan", math_isnan, METH_O, math_isnan_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001661 {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc},
Mark Dickinson05d2e082009-12-11 20:17:17 +00001662 {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001663 {"log", math_log, METH_VARARGS, math_log_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001664 {"log1p", math_log1p, METH_O, math_log1p_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001665 {"log10", math_log10, METH_O, math_log10_doc},
1666 {"modf", math_modf, METH_O, math_modf_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001667 {"pow", math_pow, METH_VARARGS, math_pow_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001668 {"radians", math_radians, METH_O, math_radians_doc},
1669 {"sin", math_sin, METH_O, math_sin_doc},
1670 {"sinh", math_sinh, METH_O, math_sinh_doc},
1671 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
1672 {"tan", math_tan, METH_O, math_tan_doc},
1673 {"tanh", math_tanh, METH_O, math_tanh_doc},
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001674 {"trunc", math_trunc, METH_O, math_trunc_doc},
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001675 {NULL, NULL} /* sentinel */
1676};
1677
Guido van Rossumc6e22901998-12-04 19:26:43 +00001678
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001679PyDoc_STRVAR(module_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001680"This module is always available. It provides access to the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001681"mathematical functions defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001682
Martin v. Löwis1a214512008-06-11 05:26:20 +00001683
1684static struct PyModuleDef mathmodule = {
1685 PyModuleDef_HEAD_INIT,
1686 "math",
1687 module_doc,
1688 -1,
1689 math_methods,
1690 NULL,
1691 NULL,
1692 NULL,
1693 NULL
1694};
1695
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001696PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001697PyInit_math(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001698{
Christian Heimes53876d92008-04-19 00:31:39 +00001699 PyObject *m;
Tim Petersfe71f812001-08-07 22:10:00 +00001700
Martin v. Löwis1a214512008-06-11 05:26:20 +00001701 m = PyModule_Create(&mathmodule);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00001702 if (m == NULL)
1703 goto finally;
Barry Warsawfc93f751996-12-17 00:47:03 +00001704
Christian Heimes53876d92008-04-19 00:31:39 +00001705 PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
1706 PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
Barry Warsawfc93f751996-12-17 00:47:03 +00001707
Christian Heimes53876d92008-04-19 00:31:39 +00001708 finally:
Martin v. Löwis1a214512008-06-11 05:26:20 +00001709 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001710}