blob: ef842989ba888ec8dfbe1f178c08e0cd3db83e91 [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;
72
73static double
74sinpi(double x)
75{
76 double y, r;
77 int n;
78 /* this function should only ever be called for finite arguments */
79 assert(Py_IS_FINITE(x));
80 y = fmod(fabs(x), 2.0);
81 n = (int)round(2.0*y);
82 assert(0 <= n && n <= 4);
83 switch (n) {
84 case 0:
85 r = sin(pi*y);
86 break;
87 case 1:
88 r = cos(pi*(y-0.5));
89 break;
90 case 2:
91 /* N.B. -sin(pi*(y-1.0)) is *not* equivalent: it would give
92 -0.0 instead of 0.0 when y == 1.0. */
93 r = sin(pi*(1.0-y));
94 break;
95 case 3:
96 r = -cos(pi*(y-1.5));
97 break;
98 case 4:
99 r = sin(pi*(y-2.0));
100 break;
101 default:
102 assert(0); /* should never get here */
103 r = -1.23e200; /* silence gcc warning */
Tim Peters1d120612000-10-12 06:10:25 +0000104 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000105 return copysign(1.0, x)*r;
106}
107
108/* Implementation of the real gamma function. In extensive but non-exhaustive
109 random tests, this function proved accurate to within <= 10 ulps across the
110 entire float domain. Note that accuracy may depend on the quality of the
111 system math functions, the pow function in particular. Special cases
112 follow C99 annex F. The parameters and method are tailored to platforms
113 whose double format is the IEEE 754 binary64 format.
114
115 Method: for x > 0.0 we use the Lanczos approximation with parameters N=13
116 and g=6.024680040776729583740234375; these parameters are amongst those
117 used by the Boost library. Following Boost (again), we re-express the
118 Lanczos sum as a rational function, and compute it that way. The
119 coefficients below were computed independently using MPFR, and have been
120 double-checked against the coefficients in the Boost source code.
121
122 For x < 0.0 we use the reflection formula.
123
124 There's one minor tweak that deserves explanation: Lanczos' formula for
125 Gamma(x) involves computing pow(x+g-0.5, x-0.5) / exp(x+g-0.5). For many x
126 values, x+g-0.5 can be represented exactly. However, in cases where it
127 can't be represented exactly the small error in x+g-0.5 can be magnified
128 significantly by the pow and exp calls, especially for large x. A cheap
129 correction is to multiply by (1 + e*g/(x+g-0.5)), where e is the error
130 involved in the computation of x+g-0.5 (that is, e = computed value of
131 x+g-0.5 - exact value of x+g-0.5). Here's the proof:
132
133 Correction factor
134 -----------------
135 Write x+g-0.5 = y-e, where y is exactly representable as an IEEE 754
136 double, and e is tiny. Then:
137
138 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) = pow(y-e, x-0.5)/exp(y-e)
139 = pow(y, x-0.5)/exp(y) * C,
140
141 where the correction_factor C is given by
142
143 C = pow(1-e/y, x-0.5) * exp(e)
144
145 Since e is tiny, pow(1-e/y, x-0.5) ~ 1-(x-0.5)*e/y, and exp(x) ~ 1+e, so:
146
147 C ~ (1-(x-0.5)*e/y) * (1+e) ~ 1 + e*(y-(x-0.5))/y
148
149 But y-(x-0.5) = g+e, and g+e ~ g. So we get C ~ 1 + e*g/y, and
150
151 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) ~ pow(y, x-0.5)/exp(y) * (1 + e*g/y),
152
153 Note that for accuracy, when computing r*C it's better to do
154
155 r + e*g/y*r;
156
157 than
158
159 r * (1 + e*g/y);
160
161 since the addition in the latter throws away most of the bits of
162 information in e*g/y.
163*/
164
165#define LANCZOS_N 13
166static const double lanczos_g = 6.024680040776729583740234375;
167static const double lanczos_g_minus_half = 5.524680040776729583740234375;
168static const double lanczos_num_coeffs[LANCZOS_N] = {
169 23531376880.410759688572007674451636754734846804940,
170 42919803642.649098768957899047001988850926355848959,
171 35711959237.355668049440185451547166705960488635843,
172 17921034426.037209699919755754458931112671403265390,
173 6039542586.3520280050642916443072979210699388420708,
174 1439720407.3117216736632230727949123939715485786772,
175 248874557.86205415651146038641322942321632125127801,
176 31426415.585400194380614231628318205362874684987640,
177 2876370.6289353724412254090516208496135991145378768,
178 186056.26539522349504029498971604569928220784236328,
179 8071.6720023658162106380029022722506138218516325024,
180 210.82427775157934587250973392071336271166969580291,
181 2.5066282746310002701649081771338373386264310793408
182};
183
184/* denominator is x*(x+1)*...*(x+LANCZOS_N-2) */
185static const double lanczos_den_coeffs[LANCZOS_N] = {
186 0.0, 39916800.0, 120543840.0, 150917976.0, 105258076.0, 45995730.0,
187 13339535.0, 2637558.0, 357423.0, 32670.0, 1925.0, 66.0, 1.0};
188
189/* gamma values for small positive integers, 1 though NGAMMA_INTEGRAL */
190#define NGAMMA_INTEGRAL 23
191static const double gamma_integral[NGAMMA_INTEGRAL] = {
192 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0,
193 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0,
194 1307674368000.0, 20922789888000.0, 355687428096000.0,
195 6402373705728000.0, 121645100408832000.0, 2432902008176640000.0,
196 51090942171709440000.0, 1124000727777607680000.0,
197};
198
199/* Lanczos' sum L_g(x), for positive x */
200
201static double
202lanczos_sum(double x)
203{
204 double num = 0.0, den = 0.0;
205 int i;
206 assert(x > 0.0);
207 /* evaluate the rational function lanczos_sum(x). For large
208 x, the obvious algorithm risks overflow, so we instead
209 rescale the denominator and numerator of the rational
210 function by x**(1-LANCZOS_N) and treat this as a
211 rational function in 1/x. This also reduces the error for
212 larger x values. The choice of cutoff point (5.0 below) is
213 somewhat arbitrary; in tests, smaller cutoff values than
214 this resulted in lower accuracy. */
215 if (x < 5.0) {
216 for (i = LANCZOS_N; --i >= 0; ) {
217 num = num * x + lanczos_num_coeffs[i];
218 den = den * x + lanczos_den_coeffs[i];
219 }
220 }
221 else {
222 for (i = 0; i < LANCZOS_N; i++) {
223 num = num / x + lanczos_num_coeffs[i];
224 den = den / x + lanczos_den_coeffs[i];
225 }
226 }
227 return num/den;
228}
229
230static double
231m_tgamma(double x)
232{
233 double absx, r, y, z, sqrtpow;
234
235 /* special cases */
236 if (!Py_IS_FINITE(x)) {
237 if (Py_IS_NAN(x) || x > 0.0)
238 return x; /* tgamma(nan) = nan, tgamma(inf) = inf */
239 else {
240 errno = EDOM;
241 return Py_NAN; /* tgamma(-inf) = nan, invalid */
242 }
243 }
244 if (x == 0.0) {
245 errno = EDOM;
246 return 1.0/x; /* tgamma(+-0.0) = +-inf, divide-by-zero */
247 }
248
249 /* integer arguments */
250 if (x == floor(x)) {
251 if (x < 0.0) {
252 errno = EDOM; /* tgamma(n) = nan, invalid for */
253 return Py_NAN; /* negative integers n */
254 }
255 if (x <= NGAMMA_INTEGRAL)
256 return gamma_integral[(int)x - 1];
257 }
258 absx = fabs(x);
259
260 /* tiny arguments: tgamma(x) ~ 1/x for x near 0 */
261 if (absx < 1e-20) {
262 r = 1.0/x;
263 if (Py_IS_INFINITY(r))
264 errno = ERANGE;
265 return r;
266 }
267
268 /* large arguments: assuming IEEE 754 doubles, tgamma(x) overflows for
269 x > 200, and underflows to +-0.0 for x < -200, not a negative
270 integer. */
271 if (absx > 200.0) {
272 if (x < 0.0) {
273 return 0.0/sinpi(x);
274 }
275 else {
276 errno = ERANGE;
277 return Py_HUGE_VAL;
278 }
279 }
280
281 y = absx + lanczos_g_minus_half;
282 /* compute error in sum */
283 if (absx > lanczos_g_minus_half) {
284 /* note: the correction can be foiled by an optimizing
285 compiler that (incorrectly) thinks that an expression like
286 a + b - a - b can be optimized to 0.0. This shouldn't
287 happen in a standards-conforming compiler. */
288 double q = y - absx;
289 z = q - lanczos_g_minus_half;
290 }
291 else {
292 double q = y - lanczos_g_minus_half;
293 z = q - absx;
294 }
295 z = z * lanczos_g / y;
296 if (x < 0.0) {
297 r = -pi / sinpi(absx) / absx * exp(y) / lanczos_sum(absx);
298 r -= z * r;
299 if (absx < 140.0) {
300 r /= pow(y, absx - 0.5);
301 }
302 else {
303 sqrtpow = pow(y, absx / 2.0 - 0.25);
304 r /= sqrtpow;
305 r /= sqrtpow;
306 }
307 }
308 else {
309 r = lanczos_sum(absx) / exp(y);
310 r += z * r;
311 if (absx < 140.0) {
312 r *= pow(y, absx - 0.5);
313 }
314 else {
315 sqrtpow = pow(y, absx / 2.0 - 0.25);
316 r *= sqrtpow;
317 r *= sqrtpow;
318 }
319 }
320 if (Py_IS_INFINITY(r))
321 errno = ERANGE;
322 return r;
Guido van Rossum8832b621991-12-16 15:44:24 +0000323}
324
Christian Heimes53876d92008-04-19 00:31:39 +0000325/*
Mark Dickinson05d2e082009-12-11 20:17:17 +0000326 lgamma: natural log of the absolute value of the Gamma function.
327 For large arguments, Lanczos' formula works extremely well here.
328*/
329
330static double
331m_lgamma(double x)
332{
333 double r, absx;
334
335 /* special cases */
336 if (!Py_IS_FINITE(x)) {
337 if (Py_IS_NAN(x))
338 return x; /* lgamma(nan) = nan */
339 else
340 return Py_HUGE_VAL; /* lgamma(+-inf) = +inf */
341 }
342
343 /* integer arguments */
344 if (x == floor(x) && x <= 2.0) {
345 if (x <= 0.0) {
346 errno = EDOM; /* lgamma(n) = inf, divide-by-zero for */
347 return Py_HUGE_VAL; /* integers n <= 0 */
348 }
349 else {
350 return 0.0; /* lgamma(1) = lgamma(2) = 0.0 */
351 }
352 }
353
354 absx = fabs(x);
355 /* tiny arguments: lgamma(x) ~ -log(fabs(x)) for small x */
356 if (absx < 1e-20)
357 return -log(absx);
358
359 /* Lanczos' formula */
360 if (x > 0.0) {
361 /* we could save a fraction of a ulp in accuracy by having a
362 second set of numerator coefficients for lanczos_sum that
363 absorbed the exp(-lanczos_g) term, and throwing out the
364 lanczos_g subtraction below; it's probably not worth it. */
365 r = log(lanczos_sum(x)) - lanczos_g +
366 (x-0.5)*(log(x+lanczos_g-0.5)-1);
367 }
368 else {
369 r = log(pi) - log(fabs(sinpi(absx))) - log(absx) -
370 (log(lanczos_sum(absx)) - lanczos_g +
371 (absx-0.5)*(log(absx+lanczos_g-0.5)-1));
372 }
373 if (Py_IS_INFINITY(r))
374 errno = ERANGE;
375 return r;
376}
377
378
379/*
Christian Heimese57950f2008-04-21 13:08:03 +0000380 wrapper for atan2 that deals directly with special cases before
381 delegating to the platform libm for the remaining cases. This
382 is necessary to get consistent behaviour across platforms.
383 Windows, FreeBSD and alpha Tru64 are amongst platforms that don't
384 always follow C99.
385*/
386
387static double
388m_atan2(double y, double x)
389{
390 if (Py_IS_NAN(x) || Py_IS_NAN(y))
391 return Py_NAN;
392 if (Py_IS_INFINITY(y)) {
393 if (Py_IS_INFINITY(x)) {
394 if (copysign(1., x) == 1.)
395 /* atan2(+-inf, +inf) == +-pi/4 */
396 return copysign(0.25*Py_MATH_PI, y);
397 else
398 /* atan2(+-inf, -inf) == +-pi*3/4 */
399 return copysign(0.75*Py_MATH_PI, y);
400 }
401 /* atan2(+-inf, x) == +-pi/2 for finite x */
402 return copysign(0.5*Py_MATH_PI, y);
403 }
404 if (Py_IS_INFINITY(x) || y == 0.) {
405 if (copysign(1., x) == 1.)
406 /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */
407 return copysign(0., y);
408 else
409 /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */
410 return copysign(Py_MATH_PI, y);
411 }
412 return atan2(y, x);
413}
414
415/*
Mark Dickinsone675f082008-12-11 21:56:00 +0000416 Various platforms (Solaris, OpenBSD) do nonstandard things for log(0),
417 log(-ve), log(NaN). Here are wrappers for log and log10 that deal with
418 special values directly, passing positive non-special values through to
419 the system log/log10.
420 */
421
422static double
423m_log(double x)
424{
425 if (Py_IS_FINITE(x)) {
426 if (x > 0.0)
427 return log(x);
428 errno = EDOM;
429 if (x == 0.0)
430 return -Py_HUGE_VAL; /* log(0) = -inf */
431 else
432 return Py_NAN; /* log(-ve) = nan */
433 }
434 else if (Py_IS_NAN(x))
435 return x; /* log(nan) = nan */
436 else if (x > 0.0)
437 return x; /* log(inf) = inf */
438 else {
439 errno = EDOM;
440 return Py_NAN; /* log(-inf) = nan */
441 }
442}
443
444static double
445m_log10(double x)
446{
447 if (Py_IS_FINITE(x)) {
448 if (x > 0.0)
449 return log10(x);
450 errno = EDOM;
451 if (x == 0.0)
452 return -Py_HUGE_VAL; /* log10(0) = -inf */
453 else
454 return Py_NAN; /* log10(-ve) = nan */
455 }
456 else if (Py_IS_NAN(x))
457 return x; /* log10(nan) = nan */
458 else if (x > 0.0)
459 return x; /* log10(inf) = inf */
460 else {
461 errno = EDOM;
462 return Py_NAN; /* log10(-inf) = nan */
463 }
464}
465
466
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000467/* Call is_error when errno != 0, and where x is the result libm
468 * returned. is_error will usually set up an exception and return
469 * true (1), but may return false (0) without setting up an exception.
470 */
471static int
472is_error(double x)
473{
474 int result = 1; /* presumption of guilt */
475 assert(errno); /* non-zero errno is a precondition for calling */
476 if (errno == EDOM)
477 PyErr_SetString(PyExc_ValueError, "math domain error");
478
479 else if (errno == ERANGE) {
480 /* ANSI C generally requires libm functions to set ERANGE
481 * on overflow, but also generally *allows* them to set
482 * ERANGE on underflow too. There's no consistency about
483 * the latter across platforms.
484 * Alas, C99 never requires that errno be set.
485 * Here we suppress the underflow errors (libm functions
486 * should return a zero on underflow, and +- HUGE_VAL on
487 * overflow, so testing the result for zero suffices to
488 * distinguish the cases).
489 *
490 * On some platforms (Ubuntu/ia64) it seems that errno can be
491 * set to ERANGE for subnormal results that do *not* underflow
492 * to zero. So to be safe, we'll ignore ERANGE whenever the
493 * function result is less than one in absolute value.
494 */
495 if (fabs(x) < 1.0)
496 result = 0;
497 else
498 PyErr_SetString(PyExc_OverflowError,
499 "math range error");
500 }
501 else
502 /* Unexpected math error */
503 PyErr_SetFromErrno(PyExc_ValueError);
504 return result;
505}
506
Mark Dickinsone675f082008-12-11 21:56:00 +0000507/*
Christian Heimes53876d92008-04-19 00:31:39 +0000508 math_1 is used to wrap a libm function f that takes a double
509 arguments and returns a double.
510
511 The error reporting follows these rules, which are designed to do
512 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
513 platforms.
514
515 - a NaN result from non-NaN inputs causes ValueError to be raised
516 - an infinite result from finite inputs causes OverflowError to be
517 raised if can_overflow is 1, or raises ValueError if can_overflow
518 is 0.
519 - if the result is finite and errno == EDOM then ValueError is
520 raised
521 - if the result is finite and nonzero and errno == ERANGE then
522 OverflowError is raised
523
524 The last rule is used to catch overflow on platforms which follow
525 C89 but for which HUGE_VAL is not an infinity.
526
527 For the majority of one-argument functions these rules are enough
528 to ensure that Python's functions behave as specified in 'Annex F'
529 of the C99 standard, with the 'invalid' and 'divide-by-zero'
530 floating-point exceptions mapping to Python's ValueError and the
531 'overflow' floating-point exception mapping to OverflowError.
532 math_1 only works for functions that don't have singularities *and*
533 the possibility of overflow; fortunately, that covers everything we
534 care about right now.
535*/
536
Barry Warsaw8b43b191996-12-09 22:32:36 +0000537static PyObject *
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000538math_1_to_whatever(PyObject *arg, double (*func) (double),
Christian Heimes53876d92008-04-19 00:31:39 +0000539 PyObject *(*from_double_func) (double),
540 int can_overflow)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000541{
Christian Heimes53876d92008-04-19 00:31:39 +0000542 double x, r;
543 x = PyFloat_AsDouble(arg);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000544 if (x == -1.0 && PyErr_Occurred())
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000545 return NULL;
546 errno = 0;
Christian Heimes53876d92008-04-19 00:31:39 +0000547 PyFPE_START_PROTECT("in math_1", return 0);
548 r = (*func)(x);
549 PyFPE_END_PROTECT(r);
Mark Dickinsona0de26c2008-04-30 23:30:57 +0000550 if (Py_IS_NAN(r) && !Py_IS_NAN(x)) {
551 PyErr_SetString(PyExc_ValueError,
Mark Dickinson66bada52008-06-18 10:04:31 +0000552 "math domain error"); /* invalid arg */
Mark Dickinsona0de26c2008-04-30 23:30:57 +0000553 return NULL;
Christian Heimes53876d92008-04-19 00:31:39 +0000554 }
Mark Dickinsona0de26c2008-04-30 23:30:57 +0000555 if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) {
556 if (can_overflow)
557 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson66bada52008-06-18 10:04:31 +0000558 "math range error"); /* overflow */
Mark Dickinsonb63aff12008-05-09 14:10:27 +0000559 else
560 PyErr_SetString(PyExc_ValueError,
Mark Dickinson66bada52008-06-18 10:04:31 +0000561 "math domain error"); /* singularity */
Mark Dickinsona0de26c2008-04-30 23:30:57 +0000562 return NULL;
Christian Heimes53876d92008-04-19 00:31:39 +0000563 }
Mark Dickinsonde429622008-05-01 00:19:23 +0000564 if (Py_IS_FINITE(r) && errno && is_error(r))
565 /* this branch unnecessary on most platforms */
Tim Peters1d120612000-10-12 06:10:25 +0000566 return NULL;
Mark Dickinsonde429622008-05-01 00:19:23 +0000567
568 return (*from_double_func)(r);
Christian Heimes53876d92008-04-19 00:31:39 +0000569}
570
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000571/* variant of math_1, to be used when the function being wrapped is known to
572 set errno properly (that is, errno = EDOM for invalid or divide-by-zero,
573 errno = ERANGE for overflow). */
574
575static PyObject *
576math_1a(PyObject *arg, double (*func) (double))
577{
578 double x, r;
579 x = PyFloat_AsDouble(arg);
580 if (x == -1.0 && PyErr_Occurred())
581 return NULL;
582 errno = 0;
583 PyFPE_START_PROTECT("in math_1a", return 0);
584 r = (*func)(x);
585 PyFPE_END_PROTECT(r);
586 if (errno && is_error(r))
587 return NULL;
588 return PyFloat_FromDouble(r);
589}
590
Christian Heimes53876d92008-04-19 00:31:39 +0000591/*
592 math_2 is used to wrap a libm function f that takes two double
593 arguments and returns a double.
594
595 The error reporting follows these rules, which are designed to do
596 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
597 platforms.
598
599 - a NaN result from non-NaN inputs causes ValueError to be raised
600 - an infinite result from finite inputs causes OverflowError to be
601 raised.
602 - if the result is finite and errno == EDOM then ValueError is
603 raised
604 - if the result is finite and nonzero and errno == ERANGE then
605 OverflowError is raised
606
607 The last rule is used to catch overflow on platforms which follow
608 C89 but for which HUGE_VAL is not an infinity.
609
610 For most two-argument functions (copysign, fmod, hypot, atan2)
611 these rules are enough to ensure that Python's functions behave as
612 specified in 'Annex F' of the C99 standard, with the 'invalid' and
613 'divide-by-zero' floating-point exceptions mapping to Python's
614 ValueError and the 'overflow' floating-point exception mapping to
615 OverflowError.
616*/
617
618static PyObject *
619math_1(PyObject *arg, double (*func) (double), int can_overflow)
620{
621 return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow);
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000622}
623
624static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000625math_1_to_int(PyObject *arg, double (*func) (double), int can_overflow)
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000626{
Christian Heimes53876d92008-04-19 00:31:39 +0000627 return math_1_to_whatever(arg, func, PyLong_FromDouble, can_overflow);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000628}
629
Barry Warsaw8b43b191996-12-09 22:32:36 +0000630static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +0000631math_2(PyObject *args, double (*func) (double, double), char *funcname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000632{
Thomas Wouters89f507f2006-12-13 04:49:30 +0000633 PyObject *ox, *oy;
Christian Heimes53876d92008-04-19 00:31:39 +0000634 double x, y, r;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000635 if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy))
636 return NULL;
637 x = PyFloat_AsDouble(ox);
638 y = PyFloat_AsDouble(oy);
639 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000640 return NULL;
641 errno = 0;
Christian Heimes53876d92008-04-19 00:31:39 +0000642 PyFPE_START_PROTECT("in math_2", return 0);
643 r = (*func)(x, y);
644 PyFPE_END_PROTECT(r);
645 if (Py_IS_NAN(r)) {
646 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
647 errno = EDOM;
648 else
649 errno = 0;
650 }
651 else if (Py_IS_INFINITY(r)) {
652 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
653 errno = ERANGE;
654 else
655 errno = 0;
656 }
657 if (errno && is_error(r))
Tim Peters1d120612000-10-12 06:10:25 +0000658 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000659 else
Christian Heimes53876d92008-04-19 00:31:39 +0000660 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000661}
662
Christian Heimes53876d92008-04-19 00:31:39 +0000663#define FUNC1(funcname, func, can_overflow, docstring) \
Fred Drake40c48682000-07-03 18:11:56 +0000664 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
Christian Heimes53876d92008-04-19 00:31:39 +0000665 return math_1(args, func, can_overflow); \
Guido van Rossumc6e22901998-12-04 19:26:43 +0000666 }\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000667 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000668
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000669#define FUNC1A(funcname, func, docstring) \
670 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
671 return math_1a(args, func); \
672 }\
673 PyDoc_STRVAR(math_##funcname##_doc, docstring);
674
Fred Drake40c48682000-07-03 18:11:56 +0000675#define FUNC2(funcname, func, docstring) \
676 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
Thomas Wouters89f507f2006-12-13 04:49:30 +0000677 return math_2(args, func, #funcname); \
Guido van Rossumc6e22901998-12-04 19:26:43 +0000678 }\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000679 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000680
Christian Heimes53876d92008-04-19 00:31:39 +0000681FUNC1(acos, acos, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000682 "acos(x)\n\nReturn the arc cosine (measured in radians) of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000683FUNC1(acosh, acosh, 0,
684 "acosh(x)\n\nReturn the hyperbolic arc cosine (measured in radians) of x.")
685FUNC1(asin, asin, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000686 "asin(x)\n\nReturn the arc sine (measured in radians) of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000687FUNC1(asinh, asinh, 0,
688 "asinh(x)\n\nReturn the hyperbolic arc sine (measured in radians) of x.")
689FUNC1(atan, atan, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000690 "atan(x)\n\nReturn the arc tangent (measured in radians) of x.")
Christian Heimese57950f2008-04-21 13:08:03 +0000691FUNC2(atan2, m_atan2,
Tim Petersfe71f812001-08-07 22:10:00 +0000692 "atan2(y, x)\n\nReturn the arc tangent (measured in radians) of y/x.\n"
693 "Unlike atan(y/x), the signs of both x and y are considered.")
Christian Heimes53876d92008-04-19 00:31:39 +0000694FUNC1(atanh, atanh, 0,
695 "atanh(x)\n\nReturn the hyperbolic arc tangent (measured in radians) of x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +0000696
697static PyObject * math_ceil(PyObject *self, PyObject *number) {
698 static PyObject *ceil_str = NULL;
699 PyObject *method;
700
701 if (ceil_str == NULL) {
Christian Heimesfe82e772008-01-28 02:38:20 +0000702 ceil_str = PyUnicode_InternFromString("__ceil__");
Guido van Rossum13e05de2007-08-23 22:56:55 +0000703 if (ceil_str == NULL)
704 return NULL;
705 }
706
Christian Heimes90aa7642007-12-19 02:45:37 +0000707 method = _PyType_Lookup(Py_TYPE(number), ceil_str);
Guido van Rossum13e05de2007-08-23 22:56:55 +0000708 if (method == NULL)
Christian Heimes53876d92008-04-19 00:31:39 +0000709 return math_1_to_int(number, ceil, 0);
Guido van Rossum13e05de2007-08-23 22:56:55 +0000710 else
711 return PyObject_CallFunction(method, "O", number);
712}
713
714PyDoc_STRVAR(math_ceil_doc,
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000715 "ceil(x)\n\nReturn the ceiling of x as an int.\n"
Guido van Rossum13e05de2007-08-23 22:56:55 +0000716 "This is the smallest integral value >= x.");
717
Christian Heimes072c0f12008-01-03 23:01:04 +0000718FUNC2(copysign, copysign,
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000719 "copysign(x, y)\n\nReturn x with the sign of y.")
Christian Heimes53876d92008-04-19 00:31:39 +0000720FUNC1(cos, cos, 0,
721 "cos(x)\n\nReturn the cosine of x (measured in radians).")
722FUNC1(cosh, cosh, 1,
723 "cosh(x)\n\nReturn the hyperbolic cosine of x.")
724FUNC1(exp, exp, 1,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000725 "exp(x)\n\nReturn e raised to the power of x.")
Mark Dickinson664b5112009-12-16 20:23:42 +0000726FUNC1(expm1, m_expm1, 1,
727 "expm1(x)\n\nReturn exp(x)-1.\n"
728 "This function avoids the loss of precision involved in the direct "
729 "evaluation of exp(x)-1 for small x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000730FUNC1(fabs, fabs, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000731 "fabs(x)\n\nReturn the absolute value of the float x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +0000732
733static PyObject * math_floor(PyObject *self, PyObject *number) {
734 static PyObject *floor_str = NULL;
735 PyObject *method;
736
737 if (floor_str == NULL) {
Christian Heimesfe82e772008-01-28 02:38:20 +0000738 floor_str = PyUnicode_InternFromString("__floor__");
Guido van Rossum13e05de2007-08-23 22:56:55 +0000739 if (floor_str == NULL)
740 return NULL;
741 }
742
Christian Heimes90aa7642007-12-19 02:45:37 +0000743 method = _PyType_Lookup(Py_TYPE(number), floor_str);
Guido van Rossum13e05de2007-08-23 22:56:55 +0000744 if (method == NULL)
Christian Heimes53876d92008-04-19 00:31:39 +0000745 return math_1_to_int(number, floor, 0);
Guido van Rossum13e05de2007-08-23 22:56:55 +0000746 else
747 return PyObject_CallFunction(method, "O", number);
748}
749
750PyDoc_STRVAR(math_floor_doc,
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000751 "floor(x)\n\nReturn the floor of x as an int.\n"
Guido van Rossum13e05de2007-08-23 22:56:55 +0000752 "This is the largest integral value <= x.");
753
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000754FUNC1A(gamma, m_tgamma,
755 "gamma(x)\n\nGamma function at x.")
Mark Dickinson05d2e082009-12-11 20:17:17 +0000756FUNC1A(lgamma, m_lgamma,
757 "lgamma(x)\n\nNatural logarithm of absolute value of Gamma function at x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000758FUNC1(log1p, log1p, 1,
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000759 "log1p(x)\n\nReturn the natural logarithm of 1+x (base e).\n"
760 "The result is computed in a way which is accurate for x near zero.")
Christian Heimes53876d92008-04-19 00:31:39 +0000761FUNC1(sin, sin, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000762 "sin(x)\n\nReturn the sine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +0000763FUNC1(sinh, sinh, 1,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000764 "sinh(x)\n\nReturn the hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000765FUNC1(sqrt, sqrt, 0,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000766 "sqrt(x)\n\nReturn the square root of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000767FUNC1(tan, tan, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000768 "tan(x)\n\nReturn the tangent of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +0000769FUNC1(tanh, tanh, 0,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000770 "tanh(x)\n\nReturn the hyperbolic tangent of x.")
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000771
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000772/* Precision summation function as msum() by Raymond Hettinger in
773 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
774 enhanced with the exact partials sum and roundoff from Mark
775 Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
776 See those links for more details, proofs and other references.
777
778 Note 1: IEEE 754R floating point semantics are assumed,
779 but the current implementation does not re-establish special
780 value semantics across iterations (i.e. handling -Inf + Inf).
781
782 Note 2: No provision is made for intermediate overflow handling;
Georg Brandlf78e02b2008-06-10 17:40:04 +0000783 therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000784 sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
785 overflow of the first partial sum.
786
Benjamin Petersonfea6a942008-07-02 16:11:42 +0000787 Note 3: The intermediate values lo, yr, and hi are declared volatile so
788 aggressive compilers won't algebraically reduce lo to always be exactly 0.0.
Georg Brandlf78e02b2008-06-10 17:40:04 +0000789 Also, the volatile declaration forces the values to be stored in memory as
790 regular doubles instead of extended long precision (80-bit) values. This
Benjamin Petersonfea6a942008-07-02 16:11:42 +0000791 prevents double rounding because any addition or subtraction of two doubles
Georg Brandlf78e02b2008-06-10 17:40:04 +0000792 can be resolved exactly into double-sized hi and lo values. As long as the
793 hi value gets forced into a double before yr and lo are computed, the extra
794 bits in downstream extended precision operations (x87 for example) will be
795 exactly zero and therefore can be losslessly stored back into a double,
796 thereby preventing double rounding.
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000797
798 Note 4: A similar implementation is in Modules/cmathmodule.c.
799 Be sure to update both when making changes.
800
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000801 Note 5: The signature of math.fsum() differs from __builtin__.sum()
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000802 because the start argument doesn't make sense in the context of
803 accurate summation. Since the partials table is collapsed before
804 returning a result, sum(seq2, start=sum(seq1)) may not equal the
805 accurate result returned by sum(itertools.chain(seq1, seq2)).
806*/
807
808#define NUM_PARTIALS 32 /* initial partials array size, on stack */
809
810/* Extend the partials array p[] by doubling its size. */
811static int /* non-zero on error */
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000812_fsum_realloc(double **p_ptr, Py_ssize_t n,
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000813 double *ps, Py_ssize_t *m_ptr)
814{
815 void *v = NULL;
816 Py_ssize_t m = *m_ptr;
817
818 m += m; /* double */
819 if (n < m && m < (PY_SSIZE_T_MAX / sizeof(double))) {
820 double *p = *p_ptr;
821 if (p == ps) {
822 v = PyMem_Malloc(sizeof(double) * m);
823 if (v != NULL)
824 memcpy(v, ps, sizeof(double) * n);
825 }
826 else
827 v = PyMem_Realloc(p, sizeof(double) * m);
828 }
829 if (v == NULL) { /* size overflow or no memory */
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000830 PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000831 return 1;
832 }
833 *p_ptr = (double*) v;
834 *m_ptr = m;
835 return 0;
836}
837
838/* Full precision summation of a sequence of floats.
839
840 def msum(iterable):
841 partials = [] # sorted, non-overlapping partial sums
842 for x in iterable:
843 i = 0
844 for y in partials:
845 if abs(x) < abs(y):
846 x, y = y, x
847 hi = x + y
848 lo = y - (hi - x)
849 if lo:
850 partials[i] = lo
851 i += 1
852 x = hi
853 partials[i:] = [x]
854 return sum_exact(partials)
855
856 Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
857 are exactly equal to x+y. The inner loop applies hi/lo summation to each
858 partial so that the list of partial sums remains exact.
859
860 Sum_exact() adds the partial sums exactly and correctly rounds the final
861 result (using the round-half-to-even rule). The items in partials remain
862 non-zero, non-special, non-overlapping and strictly increasing in
863 magnitude, but possibly not all having the same sign.
864
865 Depends on IEEE 754 arithmetic guarantees and half-even rounding.
866*/
867
868static PyObject*
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000869math_fsum(PyObject *self, PyObject *seq)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000870{
871 PyObject *item, *iter, *sum = NULL;
872 Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
Georg Brandlf78e02b2008-06-10 17:40:04 +0000873 double x, y, t, ps[NUM_PARTIALS], *p = ps;
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000874 double xsave, special_sum = 0.0, inf_sum = 0.0;
Georg Brandlf78e02b2008-06-10 17:40:04 +0000875 volatile double hi, yr, lo;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000876
877 iter = PyObject_GetIter(seq);
878 if (iter == NULL)
879 return NULL;
880
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000881 PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000882
883 for(;;) { /* for x in iterable */
884 assert(0 <= n && n <= m);
885 assert((m == NUM_PARTIALS && p == ps) ||
886 (m > NUM_PARTIALS && p != NULL));
887
888 item = PyIter_Next(iter);
889 if (item == NULL) {
890 if (PyErr_Occurred())
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000891 goto _fsum_error;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000892 break;
893 }
894 x = PyFloat_AsDouble(item);
895 Py_DECREF(item);
896 if (PyErr_Occurred())
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000897 goto _fsum_error;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000898
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000899 xsave = x;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000900 for (i = j = 0; j < n; j++) { /* for y in partials */
901 y = p[j];
Georg Brandlf78e02b2008-06-10 17:40:04 +0000902 if (fabs(x) < fabs(y)) {
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000903 t = x; x = y; y = t;
Georg Brandlf78e02b2008-06-10 17:40:04 +0000904 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000905 hi = x + y;
Georg Brandlf78e02b2008-06-10 17:40:04 +0000906 yr = hi - x;
907 lo = y - yr;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000908 if (lo != 0.0)
909 p[i++] = lo;
910 x = hi;
911 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000912
913 n = i; /* ps[i:] = [x] */
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000914 if (x != 0.0) {
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000915 if (! Py_IS_FINITE(x)) {
916 /* a nonfinite x could arise either as
917 a result of intermediate overflow, or
918 as a result of a nan or inf in the
919 summands */
920 if (Py_IS_FINITE(xsave)) {
921 PyErr_SetString(PyExc_OverflowError,
922 "intermediate overflow in fsum");
923 goto _fsum_error;
924 }
925 if (Py_IS_INFINITY(xsave))
926 inf_sum += xsave;
927 special_sum += xsave;
928 /* reset partials */
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000929 n = 0;
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000930 }
931 else if (n >= m && _fsum_realloc(&p, n, ps, &m))
932 goto _fsum_error;
933 else
934 p[n++] = x;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000935 }
936 }
937
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000938 if (special_sum != 0.0) {
939 if (Py_IS_NAN(inf_sum))
940 PyErr_SetString(PyExc_ValueError,
941 "-inf + inf in fsum");
942 else
943 sum = PyFloat_FromDouble(special_sum);
944 goto _fsum_error;
945 }
946
Georg Brandlf78e02b2008-06-10 17:40:04 +0000947 hi = 0.0;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000948 if (n > 0) {
949 hi = p[--n];
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000950 /* sum_exact(ps, hi) from the top, stop when the sum becomes
951 inexact. */
952 while (n > 0) {
953 x = hi;
954 y = p[--n];
955 assert(fabs(y) < fabs(x));
956 hi = x + y;
957 yr = hi - x;
958 lo = y - yr;
959 if (lo != 0.0)
960 break;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000961 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000962 /* Make half-even rounding work across multiple partials.
963 Needed so that sum([1e-16, 1, 1e16]) will round-up the last
964 digit to two instead of down to zero (the 1e-16 makes the 1
965 slightly closer to two). With a potential 1 ULP rounding
966 error fixed-up, math.fsum() can guarantee commutativity. */
967 if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
968 (lo > 0.0 && p[n-1] > 0.0))) {
969 y = lo * 2.0;
970 x = hi + y;
971 yr = x - hi;
972 if (y == yr)
973 hi = x;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000974 }
975 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000976 sum = PyFloat_FromDouble(hi);
977
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000978_fsum_error:
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000979 PyFPE_END_PROTECT(hi)
980 Py_DECREF(iter);
981 if (p != ps)
982 PyMem_Free(p);
983 return sum;
984}
985
986#undef NUM_PARTIALS
987
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000988PyDoc_STRVAR(math_fsum_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000989"fsum(iterable)\n\n\
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000990Return an accurate floating point sum of values in the iterable.\n\
991Assumes IEEE-754 floating point arithmetic.");
992
Barry Warsaw8b43b191996-12-09 22:32:36 +0000993static PyObject *
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000994math_factorial(PyObject *self, PyObject *arg)
995{
996 long i, x;
997 PyObject *result, *iobj, *newresult;
998
999 if (PyFloat_Check(arg)) {
1000 double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
1001 if (dx != floor(dx)) {
1002 PyErr_SetString(PyExc_ValueError,
1003 "factorial() only accepts integral values");
1004 return NULL;
1005 }
1006 }
1007
1008 x = PyLong_AsLong(arg);
1009 if (x == -1 && PyErr_Occurred())
1010 return NULL;
1011 if (x < 0) {
1012 PyErr_SetString(PyExc_ValueError,
1013 "factorial() not defined for negative values");
1014 return NULL;
1015 }
1016
1017 result = (PyObject *)PyLong_FromLong(1);
1018 if (result == NULL)
1019 return NULL;
1020 for (i=1 ; i<=x ; i++) {
1021 iobj = (PyObject *)PyLong_FromLong(i);
1022 if (iobj == NULL)
1023 goto error;
1024 newresult = PyNumber_Multiply(result, iobj);
1025 Py_DECREF(iobj);
1026 if (newresult == NULL)
1027 goto error;
1028 Py_DECREF(result);
1029 result = newresult;
1030 }
1031 return result;
1032
1033error:
1034 Py_DECREF(result);
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001035 return NULL;
1036}
1037
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001038PyDoc_STRVAR(math_factorial_doc,
1039"factorial(x) -> Integral\n"
1040"\n"
1041"Find x!. Raise a ValueError if x is negative or non-integral.");
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001042
1043static PyObject *
Christian Heimes400adb02008-02-01 08:12:03 +00001044math_trunc(PyObject *self, PyObject *number)
1045{
1046 static PyObject *trunc_str = NULL;
1047 PyObject *trunc;
1048
1049 if (Py_TYPE(number)->tp_dict == NULL) {
1050 if (PyType_Ready(Py_TYPE(number)) < 0)
1051 return NULL;
1052 }
1053
1054 if (trunc_str == NULL) {
1055 trunc_str = PyUnicode_InternFromString("__trunc__");
1056 if (trunc_str == NULL)
1057 return NULL;
1058 }
1059
1060 trunc = _PyType_Lookup(Py_TYPE(number), trunc_str);
1061 if (trunc == NULL) {
1062 PyErr_Format(PyExc_TypeError,
1063 "type %.100s doesn't define __trunc__ method",
1064 Py_TYPE(number)->tp_name);
1065 return NULL;
1066 }
1067 return PyObject_CallFunctionObjArgs(trunc, number, NULL);
1068}
1069
1070PyDoc_STRVAR(math_trunc_doc,
1071"trunc(x:Real) -> Integral\n"
1072"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001073"Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.");
Christian Heimes400adb02008-02-01 08:12:03 +00001074
1075static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001076math_frexp(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001077{
Guido van Rossumd18ad581991-10-24 14:57:21 +00001078 int i;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001079 double x = PyFloat_AsDouble(arg);
1080 if (x == -1.0 && PyErr_Occurred())
Guido van Rossumd18ad581991-10-24 14:57:21 +00001081 return NULL;
Christian Heimes53876d92008-04-19 00:31:39 +00001082 /* deal with special cases directly, to sidestep platform
1083 differences */
1084 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
1085 i = 0;
1086 }
1087 else {
1088 PyFPE_START_PROTECT("in math_frexp", return 0);
1089 x = frexp(x, &i);
1090 PyFPE_END_PROTECT(x);
1091 }
1092 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001093}
1094
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001095PyDoc_STRVAR(math_frexp_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001096"frexp(x)\n"
1097"\n"
1098"Return the mantissa and exponent of x, as pair (m, e).\n"
1099"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 +00001100"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 +00001101
Barry Warsaw8b43b191996-12-09 22:32:36 +00001102static PyObject *
Fred Drake40c48682000-07-03 18:11:56 +00001103math_ldexp(PyObject *self, PyObject *args)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001104{
Christian Heimes53876d92008-04-19 00:31:39 +00001105 double x, r;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001106 PyObject *oexp;
1107 long exp;
1108 if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp))
Guido van Rossumd18ad581991-10-24 14:57:21 +00001109 return NULL;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001110
1111 if (PyLong_Check(oexp)) {
1112 /* on overflow, replace exponent with either LONG_MAX
1113 or LONG_MIN, depending on the sign. */
1114 exp = PyLong_AsLong(oexp);
1115 if (exp == -1 && PyErr_Occurred()) {
1116 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1117 if (Py_SIZE(oexp) < 0) {
1118 exp = LONG_MIN;
1119 }
1120 else {
1121 exp = LONG_MAX;
1122 }
1123 PyErr_Clear();
1124 }
1125 else {
1126 /* propagate any unexpected exception */
1127 return NULL;
1128 }
1129 }
1130 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001131 else {
1132 PyErr_SetString(PyExc_TypeError,
1133 "Expected an int or long as second argument "
1134 "to ldexp.");
1135 return NULL;
1136 }
1137
1138 if (x == 0. || !Py_IS_FINITE(x)) {
1139 /* NaNs, zeros and infinities are returned unchanged */
1140 r = x;
Christian Heimes53876d92008-04-19 00:31:39 +00001141 errno = 0;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001142 } else if (exp > INT_MAX) {
1143 /* overflow */
1144 r = copysign(Py_HUGE_VAL, x);
1145 errno = ERANGE;
1146 } else if (exp < INT_MIN) {
1147 /* underflow to +-0 */
1148 r = copysign(0., x);
1149 errno = 0;
1150 } else {
1151 errno = 0;
1152 PyFPE_START_PROTECT("in math_ldexp", return 0);
1153 r = ldexp(x, (int)exp);
1154 PyFPE_END_PROTECT(r);
1155 if (Py_IS_INFINITY(r))
1156 errno = ERANGE;
1157 }
1158
Christian Heimes53876d92008-04-19 00:31:39 +00001159 if (errno && is_error(r))
Tim Peters1d120612000-10-12 06:10:25 +00001160 return NULL;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001161 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001162}
1163
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001164PyDoc_STRVAR(math_ldexp_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001165"ldexp(x, i)\n\n\
1166Return x * (2**i).");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001167
Barry Warsaw8b43b191996-12-09 22:32:36 +00001168static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001169math_modf(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001170{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001171 double y, x = PyFloat_AsDouble(arg);
1172 if (x == -1.0 && PyErr_Occurred())
Guido van Rossumd18ad581991-10-24 14:57:21 +00001173 return NULL;
Christian Heimesa342c012008-04-20 21:01:16 +00001174 /* some platforms don't do the right thing for NaNs and
1175 infinities, so we take care of special cases directly. */
1176 if (!Py_IS_FINITE(x)) {
1177 if (Py_IS_INFINITY(x))
1178 return Py_BuildValue("(dd)", copysign(0., x), x);
1179 else if (Py_IS_NAN(x))
1180 return Py_BuildValue("(dd)", x, x);
1181 }
1182
Guido van Rossumd18ad581991-10-24 14:57:21 +00001183 errno = 0;
Christian Heimes53876d92008-04-19 00:31:39 +00001184 PyFPE_START_PROTECT("in math_modf", return 0);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001185 x = modf(x, &y);
Christian Heimes53876d92008-04-19 00:31:39 +00001186 PyFPE_END_PROTECT(x);
1187 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001188}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001189
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001190PyDoc_STRVAR(math_modf_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001191"modf(x)\n"
1192"\n"
1193"Return the fractional and integer parts of x. Both results carry the sign\n"
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001194"of x and are floats.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001195
Tim Peters78526162001-09-05 00:53:45 +00001196/* A decent logarithm is easy to compute even for huge longs, but libm can't
1197 do that by itself -- loghelper can. func is log or log10, and name is
1198 "log" or "log10". Note that overflow isn't possible: a long can contain
1199 no more than INT_MAX * SHIFT bits, so has value certainly less than
1200 2**(2**64 * 2**16) == 2**2**80, and log2 of that is 2**80, which is
1201 small enough to fit in an IEEE single. log and log10 are even smaller.
1202*/
1203
1204static PyObject*
Thomas Wouters89f507f2006-12-13 04:49:30 +00001205loghelper(PyObject* arg, double (*func)(double), char *funcname)
Tim Peters78526162001-09-05 00:53:45 +00001206{
Tim Peters78526162001-09-05 00:53:45 +00001207 /* If it is long, do it ourselves. */
1208 if (PyLong_Check(arg)) {
1209 double x;
1210 int e;
1211 x = _PyLong_AsScaledDouble(arg, &e);
1212 if (x <= 0.0) {
1213 PyErr_SetString(PyExc_ValueError,
1214 "math domain error");
1215 return NULL;
1216 }
Christian Heimesaf98da12008-01-27 15:18:18 +00001217 /* Value is ~= x * 2**(e*PyLong_SHIFT), so the log ~=
1218 log(x) + log(2) * e * PyLong_SHIFT.
1219 CAUTION: e*PyLong_SHIFT may overflow using int arithmetic,
Tim Peters78526162001-09-05 00:53:45 +00001220 so force use of double. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001221 x = func(x) + (e * (double)PyLong_SHIFT) * func(2.0);
Tim Peters78526162001-09-05 00:53:45 +00001222 return PyFloat_FromDouble(x);
1223 }
1224
1225 /* Else let libm handle it by itself. */
Christian Heimes53876d92008-04-19 00:31:39 +00001226 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +00001227}
1228
1229static PyObject *
1230math_log(PyObject *self, PyObject *args)
1231{
Raymond Hettinger866964c2002-12-14 19:51:34 +00001232 PyObject *arg;
1233 PyObject *base = NULL;
1234 PyObject *num, *den;
1235 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001236
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001237 if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base))
Raymond Hettinger866964c2002-12-14 19:51:34 +00001238 return NULL;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001239
Mark Dickinsone675f082008-12-11 21:56:00 +00001240 num = loghelper(arg, m_log, "log");
Thomas Wouters89f507f2006-12-13 04:49:30 +00001241 if (num == NULL || base == NULL)
1242 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001243
Mark Dickinsone675f082008-12-11 21:56:00 +00001244 den = loghelper(base, m_log, "log");
Raymond Hettinger866964c2002-12-14 19:51:34 +00001245 if (den == NULL) {
1246 Py_DECREF(num);
1247 return NULL;
1248 }
1249
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001250 ans = PyNumber_TrueDivide(num, den);
Raymond Hettinger866964c2002-12-14 19:51:34 +00001251 Py_DECREF(num);
1252 Py_DECREF(den);
1253 return ans;
Tim Peters78526162001-09-05 00:53:45 +00001254}
1255
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001256PyDoc_STRVAR(math_log_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001257"log(x[, base])\n\n\
1258Return the logarithm of x to the given base.\n\
Raymond Hettinger866964c2002-12-14 19:51:34 +00001259If the base not specified, returns the natural logarithm (base e) of x.");
Tim Peters78526162001-09-05 00:53:45 +00001260
1261static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001262math_log10(PyObject *self, PyObject *arg)
Tim Peters78526162001-09-05 00:53:45 +00001263{
Mark Dickinsone675f082008-12-11 21:56:00 +00001264 return loghelper(arg, m_log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +00001265}
1266
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001267PyDoc_STRVAR(math_log10_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001268"log10(x)\n\nReturn the base 10 logarithm of x.");
Tim Peters78526162001-09-05 00:53:45 +00001269
Christian Heimes53876d92008-04-19 00:31:39 +00001270static PyObject *
1271math_fmod(PyObject *self, PyObject *args)
1272{
1273 PyObject *ox, *oy;
1274 double r, x, y;
1275 if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy))
1276 return NULL;
1277 x = PyFloat_AsDouble(ox);
1278 y = PyFloat_AsDouble(oy);
1279 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1280 return NULL;
1281 /* fmod(x, +/-Inf) returns x for finite x. */
1282 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
1283 return PyFloat_FromDouble(x);
1284 errno = 0;
1285 PyFPE_START_PROTECT("in math_fmod", return 0);
1286 r = fmod(x, y);
1287 PyFPE_END_PROTECT(r);
1288 if (Py_IS_NAN(r)) {
1289 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1290 errno = EDOM;
1291 else
1292 errno = 0;
1293 }
1294 if (errno && is_error(r))
1295 return NULL;
1296 else
1297 return PyFloat_FromDouble(r);
1298}
1299
1300PyDoc_STRVAR(math_fmod_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001301"fmod(x, y)\n\nReturn fmod(x, y), according to platform C."
Christian Heimes53876d92008-04-19 00:31:39 +00001302" x % y may differ.");
1303
1304static PyObject *
1305math_hypot(PyObject *self, PyObject *args)
1306{
1307 PyObject *ox, *oy;
1308 double r, x, y;
1309 if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy))
1310 return NULL;
1311 x = PyFloat_AsDouble(ox);
1312 y = PyFloat_AsDouble(oy);
1313 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1314 return NULL;
1315 /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */
1316 if (Py_IS_INFINITY(x))
1317 return PyFloat_FromDouble(fabs(x));
1318 if (Py_IS_INFINITY(y))
1319 return PyFloat_FromDouble(fabs(y));
1320 errno = 0;
1321 PyFPE_START_PROTECT("in math_hypot", return 0);
1322 r = hypot(x, y);
1323 PyFPE_END_PROTECT(r);
1324 if (Py_IS_NAN(r)) {
1325 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1326 errno = EDOM;
1327 else
1328 errno = 0;
1329 }
1330 else if (Py_IS_INFINITY(r)) {
1331 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
1332 errno = ERANGE;
1333 else
1334 errno = 0;
1335 }
1336 if (errno && is_error(r))
1337 return NULL;
1338 else
1339 return PyFloat_FromDouble(r);
1340}
1341
1342PyDoc_STRVAR(math_hypot_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001343"hypot(x, y)\n\nReturn the Euclidean distance, sqrt(x*x + y*y).");
Christian Heimes53876d92008-04-19 00:31:39 +00001344
1345/* pow can't use math_2, but needs its own wrapper: the problem is
1346 that an infinite result can arise either as a result of overflow
1347 (in which case OverflowError should be raised) or as a result of
1348 e.g. 0.**-5. (for which ValueError needs to be raised.)
1349*/
1350
1351static PyObject *
1352math_pow(PyObject *self, PyObject *args)
1353{
1354 PyObject *ox, *oy;
1355 double r, x, y;
Christian Heimesa342c012008-04-20 21:01:16 +00001356 int odd_y;
Christian Heimes53876d92008-04-19 00:31:39 +00001357
1358 if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy))
1359 return NULL;
1360 x = PyFloat_AsDouble(ox);
1361 y = PyFloat_AsDouble(oy);
1362 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1363 return NULL;
Christian Heimesa342c012008-04-20 21:01:16 +00001364
1365 /* deal directly with IEEE specials, to cope with problems on various
1366 platforms whose semantics don't exactly match C99 */
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001367 r = 0.; /* silence compiler warning */
Christian Heimesa342c012008-04-20 21:01:16 +00001368 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
1369 errno = 0;
1370 if (Py_IS_NAN(x))
1371 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
1372 else if (Py_IS_NAN(y))
1373 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
1374 else if (Py_IS_INFINITY(x)) {
1375 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
1376 if (y > 0.)
1377 r = odd_y ? x : fabs(x);
1378 else if (y == 0.)
1379 r = 1.;
1380 else /* y < 0. */
1381 r = odd_y ? copysign(0., x) : 0.;
1382 }
1383 else if (Py_IS_INFINITY(y)) {
1384 if (fabs(x) == 1.0)
1385 r = 1.;
1386 else if (y > 0. && fabs(x) > 1.0)
1387 r = y;
1388 else if (y < 0. && fabs(x) < 1.0) {
1389 r = -y; /* result is +inf */
1390 if (x == 0.) /* 0**-inf: divide-by-zero */
1391 errno = EDOM;
1392 }
1393 else
1394 r = 0.;
1395 }
Christian Heimes53876d92008-04-19 00:31:39 +00001396 }
Christian Heimesa342c012008-04-20 21:01:16 +00001397 else {
1398 /* let libm handle finite**finite */
1399 errno = 0;
1400 PyFPE_START_PROTECT("in math_pow", return 0);
1401 r = pow(x, y);
1402 PyFPE_END_PROTECT(r);
1403 /* a NaN result should arise only from (-ve)**(finite
1404 non-integer); in this case we want to raise ValueError. */
1405 if (!Py_IS_FINITE(r)) {
1406 if (Py_IS_NAN(r)) {
1407 errno = EDOM;
1408 }
1409 /*
1410 an infinite result here arises either from:
1411 (A) (+/-0.)**negative (-> divide-by-zero)
1412 (B) overflow of x**y with x and y finite
1413 */
1414 else if (Py_IS_INFINITY(r)) {
1415 if (x == 0.)
1416 errno = EDOM;
1417 else
1418 errno = ERANGE;
1419 }
1420 }
Christian Heimes53876d92008-04-19 00:31:39 +00001421 }
1422
1423 if (errno && is_error(r))
1424 return NULL;
1425 else
1426 return PyFloat_FromDouble(r);
1427}
1428
1429PyDoc_STRVAR(math_pow_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001430"pow(x, y)\n\nReturn x**y (x to the power of y).");
Christian Heimes53876d92008-04-19 00:31:39 +00001431
Christian Heimes072c0f12008-01-03 23:01:04 +00001432static const double degToRad = Py_MATH_PI / 180.0;
1433static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001434
1435static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001436math_degrees(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001437{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001438 double x = PyFloat_AsDouble(arg);
1439 if (x == -1.0 && PyErr_Occurred())
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001440 return NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +00001441 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001442}
1443
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001444PyDoc_STRVAR(math_degrees_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001445"degrees(x)\n\n\
1446Convert angle x from radians to degrees.");
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001447
1448static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001449math_radians(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001450{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001451 double x = PyFloat_AsDouble(arg);
1452 if (x == -1.0 && PyErr_Occurred())
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001453 return NULL;
1454 return PyFloat_FromDouble(x * degToRad);
1455}
1456
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001457PyDoc_STRVAR(math_radians_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001458"radians(x)\n\n\
1459Convert angle x from degrees to radians.");
Tim Peters78526162001-09-05 00:53:45 +00001460
Christian Heimes072c0f12008-01-03 23:01:04 +00001461static PyObject *
1462math_isnan(PyObject *self, PyObject *arg)
1463{
1464 double x = PyFloat_AsDouble(arg);
1465 if (x == -1.0 && PyErr_Occurred())
1466 return NULL;
1467 return PyBool_FromLong((long)Py_IS_NAN(x));
1468}
1469
1470PyDoc_STRVAR(math_isnan_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001471"isnan(x) -> bool\n\n\
1472Check if float x is not a number (NaN).");
Christian Heimes072c0f12008-01-03 23:01:04 +00001473
1474static PyObject *
1475math_isinf(PyObject *self, PyObject *arg)
1476{
1477 double x = PyFloat_AsDouble(arg);
1478 if (x == -1.0 && PyErr_Occurred())
1479 return NULL;
1480 return PyBool_FromLong((long)Py_IS_INFINITY(x));
1481}
1482
1483PyDoc_STRVAR(math_isinf_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001484"isinf(x) -> bool\n\n\
1485Check if float x is infinite (positive or negative).");
Christian Heimes072c0f12008-01-03 23:01:04 +00001486
Barry Warsaw8b43b191996-12-09 22:32:36 +00001487static PyMethodDef math_methods[] = {
Thomas Wouters89f507f2006-12-13 04:49:30 +00001488 {"acos", math_acos, METH_O, math_acos_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001489 {"acosh", math_acosh, METH_O, math_acosh_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001490 {"asin", math_asin, METH_O, math_asin_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001491 {"asinh", math_asinh, METH_O, math_asinh_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001492 {"atan", math_atan, METH_O, math_atan_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001493 {"atan2", math_atan2, METH_VARARGS, math_atan2_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001494 {"atanh", math_atanh, METH_O, math_atanh_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001495 {"ceil", math_ceil, METH_O, math_ceil_doc},
Christian Heimes072c0f12008-01-03 23:01:04 +00001496 {"copysign", math_copysign, METH_VARARGS, math_copysign_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001497 {"cos", math_cos, METH_O, math_cos_doc},
1498 {"cosh", math_cosh, METH_O, math_cosh_doc},
1499 {"degrees", math_degrees, METH_O, math_degrees_doc},
1500 {"exp", math_exp, METH_O, math_exp_doc},
Mark Dickinson664b5112009-12-16 20:23:42 +00001501 {"expm1", math_expm1, METH_O, math_expm1_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001502 {"fabs", math_fabs, METH_O, math_fabs_doc},
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001503 {"factorial", math_factorial, METH_O, math_factorial_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001504 {"floor", math_floor, METH_O, math_floor_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001505 {"fmod", math_fmod, METH_VARARGS, math_fmod_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001506 {"frexp", math_frexp, METH_O, math_frexp_doc},
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001507 {"fsum", math_fsum, METH_O, math_fsum_doc},
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001508 {"gamma", math_gamma, METH_O, math_gamma_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001509 {"hypot", math_hypot, METH_VARARGS, math_hypot_doc},
Christian Heimes072c0f12008-01-03 23:01:04 +00001510 {"isinf", math_isinf, METH_O, math_isinf_doc},
1511 {"isnan", math_isnan, METH_O, math_isnan_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001512 {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc},
Mark Dickinson05d2e082009-12-11 20:17:17 +00001513 {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001514 {"log", math_log, METH_VARARGS, math_log_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001515 {"log1p", math_log1p, METH_O, math_log1p_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001516 {"log10", math_log10, METH_O, math_log10_doc},
1517 {"modf", math_modf, METH_O, math_modf_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001518 {"pow", math_pow, METH_VARARGS, math_pow_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001519 {"radians", math_radians, METH_O, math_radians_doc},
1520 {"sin", math_sin, METH_O, math_sin_doc},
1521 {"sinh", math_sinh, METH_O, math_sinh_doc},
1522 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
1523 {"tan", math_tan, METH_O, math_tan_doc},
1524 {"tanh", math_tanh, METH_O, math_tanh_doc},
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001525 {"trunc", math_trunc, METH_O, math_trunc_doc},
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001526 {NULL, NULL} /* sentinel */
1527};
1528
Guido van Rossumc6e22901998-12-04 19:26:43 +00001529
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001530PyDoc_STRVAR(module_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001531"This module is always available. It provides access to the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001532"mathematical functions defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001533
Martin v. Löwis1a214512008-06-11 05:26:20 +00001534
1535static struct PyModuleDef mathmodule = {
1536 PyModuleDef_HEAD_INIT,
1537 "math",
1538 module_doc,
1539 -1,
1540 math_methods,
1541 NULL,
1542 NULL,
1543 NULL,
1544 NULL
1545};
1546
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001547PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001548PyInit_math(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001549{
Christian Heimes53876d92008-04-19 00:31:39 +00001550 PyObject *m;
Tim Petersfe71f812001-08-07 22:10:00 +00001551
Martin v. Löwis1a214512008-06-11 05:26:20 +00001552 m = PyModule_Create(&mathmodule);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00001553 if (m == NULL)
1554 goto finally;
Barry Warsawfc93f751996-12-17 00:47:03 +00001555
Christian Heimes53876d92008-04-19 00:31:39 +00001556 PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
1557 PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
Barry Warsawfc93f751996-12-17 00:47:03 +00001558
Christian Heimes53876d92008-04-19 00:31:39 +00001559 finally:
Martin v. Löwis1a214512008-06-11 05:26:20 +00001560 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001561}