blob: f835005f754b5cd4b627f8f553cf1408df1a0706 [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)) {
1140 double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
1141 if (dx != floor(dx)) {
1142 PyErr_SetString(PyExc_ValueError,
1143 "factorial() only accepts integral values");
1144 return NULL;
1145 }
1146 }
1147
1148 x = PyLong_AsLong(arg);
1149 if (x == -1 && PyErr_Occurred())
1150 return NULL;
1151 if (x < 0) {
1152 PyErr_SetString(PyExc_ValueError,
1153 "factorial() not defined for negative values");
1154 return NULL;
1155 }
1156
1157 result = (PyObject *)PyLong_FromLong(1);
1158 if (result == NULL)
1159 return NULL;
1160 for (i=1 ; i<=x ; i++) {
1161 iobj = (PyObject *)PyLong_FromLong(i);
1162 if (iobj == NULL)
1163 goto error;
1164 newresult = PyNumber_Multiply(result, iobj);
1165 Py_DECREF(iobj);
1166 if (newresult == NULL)
1167 goto error;
1168 Py_DECREF(result);
1169 result = newresult;
1170 }
1171 return result;
1172
1173error:
1174 Py_DECREF(result);
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001175 return NULL;
1176}
1177
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001178PyDoc_STRVAR(math_factorial_doc,
1179"factorial(x) -> Integral\n"
1180"\n"
1181"Find x!. Raise a ValueError if x is negative or non-integral.");
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001182
1183static PyObject *
Christian Heimes400adb02008-02-01 08:12:03 +00001184math_trunc(PyObject *self, PyObject *number)
1185{
1186 static PyObject *trunc_str = NULL;
1187 PyObject *trunc;
1188
1189 if (Py_TYPE(number)->tp_dict == NULL) {
1190 if (PyType_Ready(Py_TYPE(number)) < 0)
1191 return NULL;
1192 }
1193
1194 if (trunc_str == NULL) {
1195 trunc_str = PyUnicode_InternFromString("__trunc__");
1196 if (trunc_str == NULL)
1197 return NULL;
1198 }
1199
1200 trunc = _PyType_Lookup(Py_TYPE(number), trunc_str);
1201 if (trunc == NULL) {
1202 PyErr_Format(PyExc_TypeError,
1203 "type %.100s doesn't define __trunc__ method",
1204 Py_TYPE(number)->tp_name);
1205 return NULL;
1206 }
1207 return PyObject_CallFunctionObjArgs(trunc, number, NULL);
1208}
1209
1210PyDoc_STRVAR(math_trunc_doc,
1211"trunc(x:Real) -> Integral\n"
1212"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001213"Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.");
Christian Heimes400adb02008-02-01 08:12:03 +00001214
1215static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001216math_frexp(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001217{
Guido van Rossumd18ad581991-10-24 14:57:21 +00001218 int i;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001219 double x = PyFloat_AsDouble(arg);
1220 if (x == -1.0 && PyErr_Occurred())
Guido van Rossumd18ad581991-10-24 14:57:21 +00001221 return NULL;
Christian Heimes53876d92008-04-19 00:31:39 +00001222 /* deal with special cases directly, to sidestep platform
1223 differences */
1224 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
1225 i = 0;
1226 }
1227 else {
1228 PyFPE_START_PROTECT("in math_frexp", return 0);
1229 x = frexp(x, &i);
1230 PyFPE_END_PROTECT(x);
1231 }
1232 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001233}
1234
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001235PyDoc_STRVAR(math_frexp_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001236"frexp(x)\n"
1237"\n"
1238"Return the mantissa and exponent of x, as pair (m, e).\n"
1239"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 +00001240"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 +00001241
Barry Warsaw8b43b191996-12-09 22:32:36 +00001242static PyObject *
Fred Drake40c48682000-07-03 18:11:56 +00001243math_ldexp(PyObject *self, PyObject *args)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001244{
Christian Heimes53876d92008-04-19 00:31:39 +00001245 double x, r;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001246 PyObject *oexp;
1247 long exp;
1248 if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp))
Guido van Rossumd18ad581991-10-24 14:57:21 +00001249 return NULL;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001250
1251 if (PyLong_Check(oexp)) {
1252 /* on overflow, replace exponent with either LONG_MAX
1253 or LONG_MIN, depending on the sign. */
1254 exp = PyLong_AsLong(oexp);
1255 if (exp == -1 && PyErr_Occurred()) {
1256 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1257 if (Py_SIZE(oexp) < 0) {
1258 exp = LONG_MIN;
1259 }
1260 else {
1261 exp = LONG_MAX;
1262 }
1263 PyErr_Clear();
1264 }
1265 else {
1266 /* propagate any unexpected exception */
1267 return NULL;
1268 }
1269 }
1270 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001271 else {
1272 PyErr_SetString(PyExc_TypeError,
1273 "Expected an int or long as second argument "
1274 "to ldexp.");
1275 return NULL;
1276 }
1277
1278 if (x == 0. || !Py_IS_FINITE(x)) {
1279 /* NaNs, zeros and infinities are returned unchanged */
1280 r = x;
Christian Heimes53876d92008-04-19 00:31:39 +00001281 errno = 0;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001282 } else if (exp > INT_MAX) {
1283 /* overflow */
1284 r = copysign(Py_HUGE_VAL, x);
1285 errno = ERANGE;
1286 } else if (exp < INT_MIN) {
1287 /* underflow to +-0 */
1288 r = copysign(0., x);
1289 errno = 0;
1290 } else {
1291 errno = 0;
1292 PyFPE_START_PROTECT("in math_ldexp", return 0);
1293 r = ldexp(x, (int)exp);
1294 PyFPE_END_PROTECT(r);
1295 if (Py_IS_INFINITY(r))
1296 errno = ERANGE;
1297 }
1298
Christian Heimes53876d92008-04-19 00:31:39 +00001299 if (errno && is_error(r))
Tim Peters1d120612000-10-12 06:10:25 +00001300 return NULL;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001301 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001302}
1303
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001304PyDoc_STRVAR(math_ldexp_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001305"ldexp(x, i)\n\n\
1306Return x * (2**i).");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001307
Barry Warsaw8b43b191996-12-09 22:32:36 +00001308static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001309math_modf(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001310{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001311 double y, x = PyFloat_AsDouble(arg);
1312 if (x == -1.0 && PyErr_Occurred())
Guido van Rossumd18ad581991-10-24 14:57:21 +00001313 return NULL;
Christian Heimesa342c012008-04-20 21:01:16 +00001314 /* some platforms don't do the right thing for NaNs and
1315 infinities, so we take care of special cases directly. */
1316 if (!Py_IS_FINITE(x)) {
1317 if (Py_IS_INFINITY(x))
1318 return Py_BuildValue("(dd)", copysign(0., x), x);
1319 else if (Py_IS_NAN(x))
1320 return Py_BuildValue("(dd)", x, x);
1321 }
1322
Guido van Rossumd18ad581991-10-24 14:57:21 +00001323 errno = 0;
Christian Heimes53876d92008-04-19 00:31:39 +00001324 PyFPE_START_PROTECT("in math_modf", return 0);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001325 x = modf(x, &y);
Christian Heimes53876d92008-04-19 00:31:39 +00001326 PyFPE_END_PROTECT(x);
1327 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001328}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001329
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001330PyDoc_STRVAR(math_modf_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001331"modf(x)\n"
1332"\n"
1333"Return the fractional and integer parts of x. Both results carry the sign\n"
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001334"of x and are floats.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001335
Tim Peters78526162001-09-05 00:53:45 +00001336/* A decent logarithm is easy to compute even for huge longs, but libm can't
1337 do that by itself -- loghelper can. func is log or log10, and name is
1338 "log" or "log10". Note that overflow isn't possible: a long can contain
1339 no more than INT_MAX * SHIFT bits, so has value certainly less than
1340 2**(2**64 * 2**16) == 2**2**80, and log2 of that is 2**80, which is
1341 small enough to fit in an IEEE single. log and log10 are even smaller.
1342*/
1343
1344static PyObject*
Thomas Wouters89f507f2006-12-13 04:49:30 +00001345loghelper(PyObject* arg, double (*func)(double), char *funcname)
Tim Peters78526162001-09-05 00:53:45 +00001346{
Tim Peters78526162001-09-05 00:53:45 +00001347 /* If it is long, do it ourselves. */
1348 if (PyLong_Check(arg)) {
1349 double x;
1350 int e;
1351 x = _PyLong_AsScaledDouble(arg, &e);
1352 if (x <= 0.0) {
1353 PyErr_SetString(PyExc_ValueError,
1354 "math domain error");
1355 return NULL;
1356 }
Christian Heimesaf98da12008-01-27 15:18:18 +00001357 /* Value is ~= x * 2**(e*PyLong_SHIFT), so the log ~=
1358 log(x) + log(2) * e * PyLong_SHIFT.
1359 CAUTION: e*PyLong_SHIFT may overflow using int arithmetic,
Tim Peters78526162001-09-05 00:53:45 +00001360 so force use of double. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001361 x = func(x) + (e * (double)PyLong_SHIFT) * func(2.0);
Tim Peters78526162001-09-05 00:53:45 +00001362 return PyFloat_FromDouble(x);
1363 }
1364
1365 /* Else let libm handle it by itself. */
Christian Heimes53876d92008-04-19 00:31:39 +00001366 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +00001367}
1368
1369static PyObject *
1370math_log(PyObject *self, PyObject *args)
1371{
Raymond Hettinger866964c2002-12-14 19:51:34 +00001372 PyObject *arg;
1373 PyObject *base = NULL;
1374 PyObject *num, *den;
1375 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001376
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001377 if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base))
Raymond Hettinger866964c2002-12-14 19:51:34 +00001378 return NULL;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001379
Mark Dickinsone675f082008-12-11 21:56:00 +00001380 num = loghelper(arg, m_log, "log");
Thomas Wouters89f507f2006-12-13 04:49:30 +00001381 if (num == NULL || base == NULL)
1382 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001383
Mark Dickinsone675f082008-12-11 21:56:00 +00001384 den = loghelper(base, m_log, "log");
Raymond Hettinger866964c2002-12-14 19:51:34 +00001385 if (den == NULL) {
1386 Py_DECREF(num);
1387 return NULL;
1388 }
1389
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001390 ans = PyNumber_TrueDivide(num, den);
Raymond Hettinger866964c2002-12-14 19:51:34 +00001391 Py_DECREF(num);
1392 Py_DECREF(den);
1393 return ans;
Tim Peters78526162001-09-05 00:53:45 +00001394}
1395
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001396PyDoc_STRVAR(math_log_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001397"log(x[, base])\n\n\
1398Return the logarithm of x to the given base.\n\
Raymond Hettinger866964c2002-12-14 19:51:34 +00001399If the base not specified, returns the natural logarithm (base e) of x.");
Tim Peters78526162001-09-05 00:53:45 +00001400
1401static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001402math_log10(PyObject *self, PyObject *arg)
Tim Peters78526162001-09-05 00:53:45 +00001403{
Mark Dickinsone675f082008-12-11 21:56:00 +00001404 return loghelper(arg, m_log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +00001405}
1406
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001407PyDoc_STRVAR(math_log10_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001408"log10(x)\n\nReturn the base 10 logarithm of x.");
Tim Peters78526162001-09-05 00:53:45 +00001409
Christian Heimes53876d92008-04-19 00:31:39 +00001410static PyObject *
1411math_fmod(PyObject *self, PyObject *args)
1412{
1413 PyObject *ox, *oy;
1414 double r, x, y;
1415 if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy))
1416 return NULL;
1417 x = PyFloat_AsDouble(ox);
1418 y = PyFloat_AsDouble(oy);
1419 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1420 return NULL;
1421 /* fmod(x, +/-Inf) returns x for finite x. */
1422 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
1423 return PyFloat_FromDouble(x);
1424 errno = 0;
1425 PyFPE_START_PROTECT("in math_fmod", return 0);
1426 r = fmod(x, y);
1427 PyFPE_END_PROTECT(r);
1428 if (Py_IS_NAN(r)) {
1429 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1430 errno = EDOM;
1431 else
1432 errno = 0;
1433 }
1434 if (errno && is_error(r))
1435 return NULL;
1436 else
1437 return PyFloat_FromDouble(r);
1438}
1439
1440PyDoc_STRVAR(math_fmod_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001441"fmod(x, y)\n\nReturn fmod(x, y), according to platform C."
Christian Heimes53876d92008-04-19 00:31:39 +00001442" x % y may differ.");
1443
1444static PyObject *
1445math_hypot(PyObject *self, PyObject *args)
1446{
1447 PyObject *ox, *oy;
1448 double r, x, y;
1449 if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy))
1450 return NULL;
1451 x = PyFloat_AsDouble(ox);
1452 y = PyFloat_AsDouble(oy);
1453 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1454 return NULL;
1455 /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */
1456 if (Py_IS_INFINITY(x))
1457 return PyFloat_FromDouble(fabs(x));
1458 if (Py_IS_INFINITY(y))
1459 return PyFloat_FromDouble(fabs(y));
1460 errno = 0;
1461 PyFPE_START_PROTECT("in math_hypot", return 0);
1462 r = hypot(x, y);
1463 PyFPE_END_PROTECT(r);
1464 if (Py_IS_NAN(r)) {
1465 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1466 errno = EDOM;
1467 else
1468 errno = 0;
1469 }
1470 else if (Py_IS_INFINITY(r)) {
1471 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
1472 errno = ERANGE;
1473 else
1474 errno = 0;
1475 }
1476 if (errno && is_error(r))
1477 return NULL;
1478 else
1479 return PyFloat_FromDouble(r);
1480}
1481
1482PyDoc_STRVAR(math_hypot_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001483"hypot(x, y)\n\nReturn the Euclidean distance, sqrt(x*x + y*y).");
Christian Heimes53876d92008-04-19 00:31:39 +00001484
1485/* pow can't use math_2, but needs its own wrapper: the problem is
1486 that an infinite result can arise either as a result of overflow
1487 (in which case OverflowError should be raised) or as a result of
1488 e.g. 0.**-5. (for which ValueError needs to be raised.)
1489*/
1490
1491static PyObject *
1492math_pow(PyObject *self, PyObject *args)
1493{
1494 PyObject *ox, *oy;
1495 double r, x, y;
Christian Heimesa342c012008-04-20 21:01:16 +00001496 int odd_y;
Christian Heimes53876d92008-04-19 00:31:39 +00001497
1498 if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy))
1499 return NULL;
1500 x = PyFloat_AsDouble(ox);
1501 y = PyFloat_AsDouble(oy);
1502 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1503 return NULL;
Christian Heimesa342c012008-04-20 21:01:16 +00001504
1505 /* deal directly with IEEE specials, to cope with problems on various
1506 platforms whose semantics don't exactly match C99 */
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001507 r = 0.; /* silence compiler warning */
Christian Heimesa342c012008-04-20 21:01:16 +00001508 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
1509 errno = 0;
1510 if (Py_IS_NAN(x))
1511 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
1512 else if (Py_IS_NAN(y))
1513 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
1514 else if (Py_IS_INFINITY(x)) {
1515 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
1516 if (y > 0.)
1517 r = odd_y ? x : fabs(x);
1518 else if (y == 0.)
1519 r = 1.;
1520 else /* y < 0. */
1521 r = odd_y ? copysign(0., x) : 0.;
1522 }
1523 else if (Py_IS_INFINITY(y)) {
1524 if (fabs(x) == 1.0)
1525 r = 1.;
1526 else if (y > 0. && fabs(x) > 1.0)
1527 r = y;
1528 else if (y < 0. && fabs(x) < 1.0) {
1529 r = -y; /* result is +inf */
1530 if (x == 0.) /* 0**-inf: divide-by-zero */
1531 errno = EDOM;
1532 }
1533 else
1534 r = 0.;
1535 }
Christian Heimes53876d92008-04-19 00:31:39 +00001536 }
Christian Heimesa342c012008-04-20 21:01:16 +00001537 else {
1538 /* let libm handle finite**finite */
1539 errno = 0;
1540 PyFPE_START_PROTECT("in math_pow", return 0);
1541 r = pow(x, y);
1542 PyFPE_END_PROTECT(r);
1543 /* a NaN result should arise only from (-ve)**(finite
1544 non-integer); in this case we want to raise ValueError. */
1545 if (!Py_IS_FINITE(r)) {
1546 if (Py_IS_NAN(r)) {
1547 errno = EDOM;
1548 }
1549 /*
1550 an infinite result here arises either from:
1551 (A) (+/-0.)**negative (-> divide-by-zero)
1552 (B) overflow of x**y with x and y finite
1553 */
1554 else if (Py_IS_INFINITY(r)) {
1555 if (x == 0.)
1556 errno = EDOM;
1557 else
1558 errno = ERANGE;
1559 }
1560 }
Christian Heimes53876d92008-04-19 00:31:39 +00001561 }
1562
1563 if (errno && is_error(r))
1564 return NULL;
1565 else
1566 return PyFloat_FromDouble(r);
1567}
1568
1569PyDoc_STRVAR(math_pow_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001570"pow(x, y)\n\nReturn x**y (x to the power of y).");
Christian Heimes53876d92008-04-19 00:31:39 +00001571
Christian Heimes072c0f12008-01-03 23:01:04 +00001572static const double degToRad = Py_MATH_PI / 180.0;
1573static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001574
1575static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001576math_degrees(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001577{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001578 double x = PyFloat_AsDouble(arg);
1579 if (x == -1.0 && PyErr_Occurred())
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001580 return NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +00001581 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001582}
1583
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001584PyDoc_STRVAR(math_degrees_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001585"degrees(x)\n\n\
1586Convert angle x from radians to degrees.");
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001587
1588static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001589math_radians(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001590{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001591 double x = PyFloat_AsDouble(arg);
1592 if (x == -1.0 && PyErr_Occurred())
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001593 return NULL;
1594 return PyFloat_FromDouble(x * degToRad);
1595}
1596
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001597PyDoc_STRVAR(math_radians_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001598"radians(x)\n\n\
1599Convert angle x from degrees to radians.");
Tim Peters78526162001-09-05 00:53:45 +00001600
Christian Heimes072c0f12008-01-03 23:01:04 +00001601static PyObject *
1602math_isnan(PyObject *self, PyObject *arg)
1603{
1604 double x = PyFloat_AsDouble(arg);
1605 if (x == -1.0 && PyErr_Occurred())
1606 return NULL;
1607 return PyBool_FromLong((long)Py_IS_NAN(x));
1608}
1609
1610PyDoc_STRVAR(math_isnan_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001611"isnan(x) -> bool\n\n\
1612Check if float x is not a number (NaN).");
Christian Heimes072c0f12008-01-03 23:01:04 +00001613
1614static PyObject *
1615math_isinf(PyObject *self, PyObject *arg)
1616{
1617 double x = PyFloat_AsDouble(arg);
1618 if (x == -1.0 && PyErr_Occurred())
1619 return NULL;
1620 return PyBool_FromLong((long)Py_IS_INFINITY(x));
1621}
1622
1623PyDoc_STRVAR(math_isinf_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001624"isinf(x) -> bool\n\n\
1625Check if float x is infinite (positive or negative).");
Christian Heimes072c0f12008-01-03 23:01:04 +00001626
Barry Warsaw8b43b191996-12-09 22:32:36 +00001627static PyMethodDef math_methods[] = {
Thomas Wouters89f507f2006-12-13 04:49:30 +00001628 {"acos", math_acos, METH_O, math_acos_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001629 {"acosh", math_acosh, METH_O, math_acosh_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001630 {"asin", math_asin, METH_O, math_asin_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001631 {"asinh", math_asinh, METH_O, math_asinh_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001632 {"atan", math_atan, METH_O, math_atan_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001633 {"atan2", math_atan2, METH_VARARGS, math_atan2_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001634 {"atanh", math_atanh, METH_O, math_atanh_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001635 {"ceil", math_ceil, METH_O, math_ceil_doc},
Christian Heimes072c0f12008-01-03 23:01:04 +00001636 {"copysign", math_copysign, METH_VARARGS, math_copysign_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001637 {"cos", math_cos, METH_O, math_cos_doc},
1638 {"cosh", math_cosh, METH_O, math_cosh_doc},
1639 {"degrees", math_degrees, METH_O, math_degrees_doc},
Mark Dickinson45f992a2009-12-19 11:20:49 +00001640 {"erf", math_erf, METH_O, math_erf_doc},
1641 {"erfc", math_erfc, METH_O, math_erfc_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001642 {"exp", math_exp, METH_O, math_exp_doc},
Mark Dickinson664b5112009-12-16 20:23:42 +00001643 {"expm1", math_expm1, METH_O, math_expm1_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001644 {"fabs", math_fabs, METH_O, math_fabs_doc},
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001645 {"factorial", math_factorial, METH_O, math_factorial_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001646 {"floor", math_floor, METH_O, math_floor_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001647 {"fmod", math_fmod, METH_VARARGS, math_fmod_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001648 {"frexp", math_frexp, METH_O, math_frexp_doc},
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001649 {"fsum", math_fsum, METH_O, math_fsum_doc},
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001650 {"gamma", math_gamma, METH_O, math_gamma_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001651 {"hypot", math_hypot, METH_VARARGS, math_hypot_doc},
Christian Heimes072c0f12008-01-03 23:01:04 +00001652 {"isinf", math_isinf, METH_O, math_isinf_doc},
1653 {"isnan", math_isnan, METH_O, math_isnan_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001654 {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc},
Mark Dickinson05d2e082009-12-11 20:17:17 +00001655 {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001656 {"log", math_log, METH_VARARGS, math_log_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001657 {"log1p", math_log1p, METH_O, math_log1p_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001658 {"log10", math_log10, METH_O, math_log10_doc},
1659 {"modf", math_modf, METH_O, math_modf_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001660 {"pow", math_pow, METH_VARARGS, math_pow_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001661 {"radians", math_radians, METH_O, math_radians_doc},
1662 {"sin", math_sin, METH_O, math_sin_doc},
1663 {"sinh", math_sinh, METH_O, math_sinh_doc},
1664 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
1665 {"tan", math_tan, METH_O, math_tan_doc},
1666 {"tanh", math_tanh, METH_O, math_tanh_doc},
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001667 {"trunc", math_trunc, METH_O, math_trunc_doc},
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001668 {NULL, NULL} /* sentinel */
1669};
1670
Guido van Rossumc6e22901998-12-04 19:26:43 +00001671
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001672PyDoc_STRVAR(module_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001673"This module is always available. It provides access to the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001674"mathematical functions defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001675
Martin v. Löwis1a214512008-06-11 05:26:20 +00001676
1677static struct PyModuleDef mathmodule = {
1678 PyModuleDef_HEAD_INIT,
1679 "math",
1680 module_doc,
1681 -1,
1682 math_methods,
1683 NULL,
1684 NULL,
1685 NULL,
1686 NULL
1687};
1688
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001689PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001690PyInit_math(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001691{
Christian Heimes53876d92008-04-19 00:31:39 +00001692 PyObject *m;
Tim Petersfe71f812001-08-07 22:10:00 +00001693
Martin v. Löwis1a214512008-06-11 05:26:20 +00001694 m = PyModule_Create(&mathmodule);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00001695 if (m == NULL)
1696 goto finally;
Barry Warsawfc93f751996-12-17 00:47:03 +00001697
Christian Heimes53876d92008-04-19 00:31:39 +00001698 PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
1699 PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
Barry Warsawfc93f751996-12-17 00:47:03 +00001700
Christian Heimes53876d92008-04-19 00:31:39 +00001701 finally:
Martin v. Löwis1a214512008-06-11 05:26:20 +00001702 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001703}