blob: ece68a742c803eb56d79bc0c823fd50351a93672 [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"
Michael W. Hudson9ef852c2005-04-06 13:05:18 +000056#include "longintrepr.h" /* just for SHIFT */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000057
Christian Heimes969fe572008-01-25 11:23:10 +000058#ifdef _OSF_SOURCE
59/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
60extern double copysign(double, double);
61#endif
62
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000063/*
64 sin(pi*x), giving accurate results for all finite x (especially x
65 integral or close to an integer). This is here for use in the
66 reflection formula for the gamma function. It conforms to IEEE
67 754-2008 for finite arguments, but not for infinities or nans.
68*/
Tim Petersa40c7932001-09-05 22:36:56 +000069
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000070static const double pi = 3.141592653589793238462643383279502884197;
71
72static double
73sinpi(double x)
74{
75 double y, r;
76 int n;
77 /* this function should only ever be called for finite arguments */
78 assert(Py_IS_FINITE(x));
79 y = fmod(fabs(x), 2.0);
80 n = (int)round(2.0*y);
81 assert(0 <= n && n <= 4);
82 switch (n) {
83 case 0:
84 r = sin(pi*y);
85 break;
86 case 1:
87 r = cos(pi*(y-0.5));
88 break;
89 case 2:
90 /* N.B. -sin(pi*(y-1.0)) is *not* equivalent: it would give
91 -0.0 instead of 0.0 when y == 1.0. */
92 r = sin(pi*(1.0-y));
93 break;
94 case 3:
95 r = -cos(pi*(y-1.5));
96 break;
97 case 4:
98 r = sin(pi*(y-2.0));
99 break;
100 default:
101 assert(0); /* should never get here */
102 r = -1.23e200; /* silence gcc warning */
Tim Peters1d120612000-10-12 06:10:25 +0000103 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000104 return copysign(1.0, x)*r;
105}
106
107/* Implementation of the real gamma function. In extensive but non-exhaustive
108 random tests, this function proved accurate to within <= 10 ulps across the
109 entire float domain. Note that accuracy may depend on the quality of the
110 system math functions, the pow function in particular. Special cases
111 follow C99 annex F. The parameters and method are tailored to platforms
112 whose double format is the IEEE 754 binary64 format.
113
114 Method: for x > 0.0 we use the Lanczos approximation with parameters N=13
115 and g=6.024680040776729583740234375; these parameters are amongst those
116 used by the Boost library. Following Boost (again), we re-express the
117 Lanczos sum as a rational function, and compute it that way. The
118 coefficients below were computed independently using MPFR, and have been
119 double-checked against the coefficients in the Boost source code.
120
121 For x < 0.0 we use the reflection formula.
122
123 There's one minor tweak that deserves explanation: Lanczos' formula for
124 Gamma(x) involves computing pow(x+g-0.5, x-0.5) / exp(x+g-0.5). For many x
125 values, x+g-0.5 can be represented exactly. However, in cases where it
126 can't be represented exactly the small error in x+g-0.5 can be magnified
127 significantly by the pow and exp calls, especially for large x. A cheap
128 correction is to multiply by (1 + e*g/(x+g-0.5)), where e is the error
129 involved in the computation of x+g-0.5 (that is, e = computed value of
130 x+g-0.5 - exact value of x+g-0.5). Here's the proof:
131
132 Correction factor
133 -----------------
134 Write x+g-0.5 = y-e, where y is exactly representable as an IEEE 754
135 double, and e is tiny. Then:
136
137 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) = pow(y-e, x-0.5)/exp(y-e)
138 = pow(y, x-0.5)/exp(y) * C,
139
140 where the correction_factor C is given by
141
142 C = pow(1-e/y, x-0.5) * exp(e)
143
144 Since e is tiny, pow(1-e/y, x-0.5) ~ 1-(x-0.5)*e/y, and exp(x) ~ 1+e, so:
145
146 C ~ (1-(x-0.5)*e/y) * (1+e) ~ 1 + e*(y-(x-0.5))/y
147
148 But y-(x-0.5) = g+e, and g+e ~ g. So we get C ~ 1 + e*g/y, and
149
150 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) ~ pow(y, x-0.5)/exp(y) * (1 + e*g/y),
151
152 Note that for accuracy, when computing r*C it's better to do
153
154 r + e*g/y*r;
155
156 than
157
158 r * (1 + e*g/y);
159
160 since the addition in the latter throws away most of the bits of
161 information in e*g/y.
162*/
163
164#define LANCZOS_N 13
165static const double lanczos_g = 6.024680040776729583740234375;
166static const double lanczos_g_minus_half = 5.524680040776729583740234375;
167static const double lanczos_num_coeffs[LANCZOS_N] = {
168 23531376880.410759688572007674451636754734846804940,
169 42919803642.649098768957899047001988850926355848959,
170 35711959237.355668049440185451547166705960488635843,
171 17921034426.037209699919755754458931112671403265390,
172 6039542586.3520280050642916443072979210699388420708,
173 1439720407.3117216736632230727949123939715485786772,
174 248874557.86205415651146038641322942321632125127801,
175 31426415.585400194380614231628318205362874684987640,
176 2876370.6289353724412254090516208496135991145378768,
177 186056.26539522349504029498971604569928220784236328,
178 8071.6720023658162106380029022722506138218516325024,
179 210.82427775157934587250973392071336271166969580291,
180 2.5066282746310002701649081771338373386264310793408
181};
182
183/* denominator is x*(x+1)*...*(x+LANCZOS_N-2) */
184static const double lanczos_den_coeffs[LANCZOS_N] = {
185 0.0, 39916800.0, 120543840.0, 150917976.0, 105258076.0, 45995730.0,
186 13339535.0, 2637558.0, 357423.0, 32670.0, 1925.0, 66.0, 1.0};
187
188/* gamma values for small positive integers, 1 though NGAMMA_INTEGRAL */
189#define NGAMMA_INTEGRAL 23
190static const double gamma_integral[NGAMMA_INTEGRAL] = {
191 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0,
192 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0,
193 1307674368000.0, 20922789888000.0, 355687428096000.0,
194 6402373705728000.0, 121645100408832000.0, 2432902008176640000.0,
195 51090942171709440000.0, 1124000727777607680000.0,
196};
197
198/* Lanczos' sum L_g(x), for positive x */
199
200static double
201lanczos_sum(double x)
202{
203 double num = 0.0, den = 0.0;
204 int i;
205 assert(x > 0.0);
206 /* evaluate the rational function lanczos_sum(x). For large
207 x, the obvious algorithm risks overflow, so we instead
208 rescale the denominator and numerator of the rational
209 function by x**(1-LANCZOS_N) and treat this as a
210 rational function in 1/x. This also reduces the error for
211 larger x values. The choice of cutoff point (5.0 below) is
212 somewhat arbitrary; in tests, smaller cutoff values than
213 this resulted in lower accuracy. */
214 if (x < 5.0) {
215 for (i = LANCZOS_N; --i >= 0; ) {
216 num = num * x + lanczos_num_coeffs[i];
217 den = den * x + lanczos_den_coeffs[i];
218 }
219 }
220 else {
221 for (i = 0; i < LANCZOS_N; i++) {
222 num = num / x + lanczos_num_coeffs[i];
223 den = den / x + lanczos_den_coeffs[i];
224 }
225 }
226 return num/den;
227}
228
229static double
230m_tgamma(double x)
231{
232 double absx, r, y, z, sqrtpow;
233
234 /* special cases */
235 if (!Py_IS_FINITE(x)) {
236 if (Py_IS_NAN(x) || x > 0.0)
237 return x; /* tgamma(nan) = nan, tgamma(inf) = inf */
238 else {
239 errno = EDOM;
240 return Py_NAN; /* tgamma(-inf) = nan, invalid */
241 }
242 }
243 if (x == 0.0) {
244 errno = EDOM;
245 return 1.0/x; /* tgamma(+-0.0) = +-inf, divide-by-zero */
246 }
247
248 /* integer arguments */
249 if (x == floor(x)) {
250 if (x < 0.0) {
251 errno = EDOM; /* tgamma(n) = nan, invalid for */
252 return Py_NAN; /* negative integers n */
253 }
254 if (x <= NGAMMA_INTEGRAL)
255 return gamma_integral[(int)x - 1];
256 }
257 absx = fabs(x);
258
259 /* tiny arguments: tgamma(x) ~ 1/x for x near 0 */
260 if (absx < 1e-20) {
261 r = 1.0/x;
262 if (Py_IS_INFINITY(r))
263 errno = ERANGE;
264 return r;
265 }
266
267 /* large arguments: assuming IEEE 754 doubles, tgamma(x) overflows for
268 x > 200, and underflows to +-0.0 for x < -200, not a negative
269 integer. */
270 if (absx > 200.0) {
271 if (x < 0.0) {
272 return 0.0/sinpi(x);
273 }
274 else {
275 errno = ERANGE;
276 return Py_HUGE_VAL;
277 }
278 }
279
280 y = absx + lanczos_g_minus_half;
281 /* compute error in sum */
282 if (absx > lanczos_g_minus_half) {
283 /* note: the correction can be foiled by an optimizing
284 compiler that (incorrectly) thinks that an expression like
285 a + b - a - b can be optimized to 0.0. This shouldn't
286 happen in a standards-conforming compiler. */
287 double q = y - absx;
288 z = q - lanczos_g_minus_half;
289 }
290 else {
291 double q = y - lanczos_g_minus_half;
292 z = q - absx;
293 }
294 z = z * lanczos_g / y;
295 if (x < 0.0) {
296 r = -pi / sinpi(absx) / absx * exp(y) / lanczos_sum(absx);
297 r -= z * r;
298 if (absx < 140.0) {
299 r /= pow(y, absx - 0.5);
300 }
301 else {
302 sqrtpow = pow(y, absx / 2.0 - 0.25);
303 r /= sqrtpow;
304 r /= sqrtpow;
305 }
306 }
307 else {
308 r = lanczos_sum(absx) / exp(y);
309 r += z * r;
310 if (absx < 140.0) {
311 r *= pow(y, absx - 0.5);
312 }
313 else {
314 sqrtpow = pow(y, absx / 2.0 - 0.25);
315 r *= sqrtpow;
316 r *= sqrtpow;
317 }
318 }
319 if (Py_IS_INFINITY(r))
320 errno = ERANGE;
321 return r;
Guido van Rossum8832b621991-12-16 15:44:24 +0000322}
323
Christian Heimes53876d92008-04-19 00:31:39 +0000324/*
Mark Dickinson05d2e082009-12-11 20:17:17 +0000325 lgamma: natural log of the absolute value of the Gamma function.
326 For large arguments, Lanczos' formula works extremely well here.
327*/
328
329static double
330m_lgamma(double x)
331{
332 double r, absx;
333
334 /* special cases */
335 if (!Py_IS_FINITE(x)) {
336 if (Py_IS_NAN(x))
337 return x; /* lgamma(nan) = nan */
338 else
339 return Py_HUGE_VAL; /* lgamma(+-inf) = +inf */
340 }
341
342 /* integer arguments */
343 if (x == floor(x) && x <= 2.0) {
344 if (x <= 0.0) {
345 errno = EDOM; /* lgamma(n) = inf, divide-by-zero for */
346 return Py_HUGE_VAL; /* integers n <= 0 */
347 }
348 else {
349 return 0.0; /* lgamma(1) = lgamma(2) = 0.0 */
350 }
351 }
352
353 absx = fabs(x);
354 /* tiny arguments: lgamma(x) ~ -log(fabs(x)) for small x */
355 if (absx < 1e-20)
356 return -log(absx);
357
358 /* Lanczos' formula */
359 if (x > 0.0) {
360 /* we could save a fraction of a ulp in accuracy by having a
361 second set of numerator coefficients for lanczos_sum that
362 absorbed the exp(-lanczos_g) term, and throwing out the
363 lanczos_g subtraction below; it's probably not worth it. */
364 r = log(lanczos_sum(x)) - lanczos_g +
365 (x-0.5)*(log(x+lanczos_g-0.5)-1);
366 }
367 else {
368 r = log(pi) - log(fabs(sinpi(absx))) - log(absx) -
369 (log(lanczos_sum(absx)) - lanczos_g +
370 (absx-0.5)*(log(absx+lanczos_g-0.5)-1));
371 }
372 if (Py_IS_INFINITY(r))
373 errno = ERANGE;
374 return r;
375}
376
377
378/*
Christian Heimese57950f2008-04-21 13:08:03 +0000379 wrapper for atan2 that deals directly with special cases before
380 delegating to the platform libm for the remaining cases. This
381 is necessary to get consistent behaviour across platforms.
382 Windows, FreeBSD and alpha Tru64 are amongst platforms that don't
383 always follow C99.
384*/
385
386static double
387m_atan2(double y, double x)
388{
389 if (Py_IS_NAN(x) || Py_IS_NAN(y))
390 return Py_NAN;
391 if (Py_IS_INFINITY(y)) {
392 if (Py_IS_INFINITY(x)) {
393 if (copysign(1., x) == 1.)
394 /* atan2(+-inf, +inf) == +-pi/4 */
395 return copysign(0.25*Py_MATH_PI, y);
396 else
397 /* atan2(+-inf, -inf) == +-pi*3/4 */
398 return copysign(0.75*Py_MATH_PI, y);
399 }
400 /* atan2(+-inf, x) == +-pi/2 for finite x */
401 return copysign(0.5*Py_MATH_PI, y);
402 }
403 if (Py_IS_INFINITY(x) || y == 0.) {
404 if (copysign(1., x) == 1.)
405 /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */
406 return copysign(0., y);
407 else
408 /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */
409 return copysign(Py_MATH_PI, y);
410 }
411 return atan2(y, x);
412}
413
414/*
Mark Dickinsone675f082008-12-11 21:56:00 +0000415 Various platforms (Solaris, OpenBSD) do nonstandard things for log(0),
416 log(-ve), log(NaN). Here are wrappers for log and log10 that deal with
417 special values directly, passing positive non-special values through to
418 the system log/log10.
419 */
420
421static double
422m_log(double x)
423{
424 if (Py_IS_FINITE(x)) {
425 if (x > 0.0)
426 return log(x);
427 errno = EDOM;
428 if (x == 0.0)
429 return -Py_HUGE_VAL; /* log(0) = -inf */
430 else
431 return Py_NAN; /* log(-ve) = nan */
432 }
433 else if (Py_IS_NAN(x))
434 return x; /* log(nan) = nan */
435 else if (x > 0.0)
436 return x; /* log(inf) = inf */
437 else {
438 errno = EDOM;
439 return Py_NAN; /* log(-inf) = nan */
440 }
441}
442
443static double
444m_log10(double x)
445{
446 if (Py_IS_FINITE(x)) {
447 if (x > 0.0)
448 return log10(x);
449 errno = EDOM;
450 if (x == 0.0)
451 return -Py_HUGE_VAL; /* log10(0) = -inf */
452 else
453 return Py_NAN; /* log10(-ve) = nan */
454 }
455 else if (Py_IS_NAN(x))
456 return x; /* log10(nan) = nan */
457 else if (x > 0.0)
458 return x; /* log10(inf) = inf */
459 else {
460 errno = EDOM;
461 return Py_NAN; /* log10(-inf) = nan */
462 }
463}
464
465
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000466/* Call is_error when errno != 0, and where x is the result libm
467 * returned. is_error will usually set up an exception and return
468 * true (1), but may return false (0) without setting up an exception.
469 */
470static int
471is_error(double x)
472{
473 int result = 1; /* presumption of guilt */
474 assert(errno); /* non-zero errno is a precondition for calling */
475 if (errno == EDOM)
476 PyErr_SetString(PyExc_ValueError, "math domain error");
477
478 else if (errno == ERANGE) {
479 /* ANSI C generally requires libm functions to set ERANGE
480 * on overflow, but also generally *allows* them to set
481 * ERANGE on underflow too. There's no consistency about
482 * the latter across platforms.
483 * Alas, C99 never requires that errno be set.
484 * Here we suppress the underflow errors (libm functions
485 * should return a zero on underflow, and +- HUGE_VAL on
486 * overflow, so testing the result for zero suffices to
487 * distinguish the cases).
488 *
489 * On some platforms (Ubuntu/ia64) it seems that errno can be
490 * set to ERANGE for subnormal results that do *not* underflow
491 * to zero. So to be safe, we'll ignore ERANGE whenever the
492 * function result is less than one in absolute value.
493 */
494 if (fabs(x) < 1.0)
495 result = 0;
496 else
497 PyErr_SetString(PyExc_OverflowError,
498 "math range error");
499 }
500 else
501 /* Unexpected math error */
502 PyErr_SetFromErrno(PyExc_ValueError);
503 return result;
504}
505
Mark Dickinsone675f082008-12-11 21:56:00 +0000506/*
Christian Heimes53876d92008-04-19 00:31:39 +0000507 math_1 is used to wrap a libm function f that takes a double
508 arguments and returns a double.
509
510 The error reporting follows these rules, which are designed to do
511 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
512 platforms.
513
514 - a NaN result from non-NaN inputs causes ValueError to be raised
515 - an infinite result from finite inputs causes OverflowError to be
516 raised if can_overflow is 1, or raises ValueError if can_overflow
517 is 0.
518 - if the result is finite and errno == EDOM then ValueError is
519 raised
520 - if the result is finite and nonzero and errno == ERANGE then
521 OverflowError is raised
522
523 The last rule is used to catch overflow on platforms which follow
524 C89 but for which HUGE_VAL is not an infinity.
525
526 For the majority of one-argument functions these rules are enough
527 to ensure that Python's functions behave as specified in 'Annex F'
528 of the C99 standard, with the 'invalid' and 'divide-by-zero'
529 floating-point exceptions mapping to Python's ValueError and the
530 'overflow' floating-point exception mapping to OverflowError.
531 math_1 only works for functions that don't have singularities *and*
532 the possibility of overflow; fortunately, that covers everything we
533 care about right now.
534*/
535
Barry Warsaw8b43b191996-12-09 22:32:36 +0000536static PyObject *
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000537math_1_to_whatever(PyObject *arg, double (*func) (double),
Christian Heimes53876d92008-04-19 00:31:39 +0000538 PyObject *(*from_double_func) (double),
539 int can_overflow)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000540{
Christian Heimes53876d92008-04-19 00:31:39 +0000541 double x, r;
542 x = PyFloat_AsDouble(arg);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000543 if (x == -1.0 && PyErr_Occurred())
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000544 return NULL;
545 errno = 0;
Christian Heimes53876d92008-04-19 00:31:39 +0000546 PyFPE_START_PROTECT("in math_1", return 0);
547 r = (*func)(x);
548 PyFPE_END_PROTECT(r);
Mark Dickinsona0de26c2008-04-30 23:30:57 +0000549 if (Py_IS_NAN(r) && !Py_IS_NAN(x)) {
550 PyErr_SetString(PyExc_ValueError,
Mark Dickinson66bada52008-06-18 10:04:31 +0000551 "math domain error"); /* invalid arg */
Mark Dickinsona0de26c2008-04-30 23:30:57 +0000552 return NULL;
Christian Heimes53876d92008-04-19 00:31:39 +0000553 }
Mark Dickinsona0de26c2008-04-30 23:30:57 +0000554 if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) {
555 if (can_overflow)
556 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson66bada52008-06-18 10:04:31 +0000557 "math range error"); /* overflow */
Mark Dickinsonb63aff12008-05-09 14:10:27 +0000558 else
559 PyErr_SetString(PyExc_ValueError,
Mark Dickinson66bada52008-06-18 10:04:31 +0000560 "math domain error"); /* singularity */
Mark Dickinsona0de26c2008-04-30 23:30:57 +0000561 return NULL;
Christian Heimes53876d92008-04-19 00:31:39 +0000562 }
Mark Dickinsonde429622008-05-01 00:19:23 +0000563 if (Py_IS_FINITE(r) && errno && is_error(r))
564 /* this branch unnecessary on most platforms */
Tim Peters1d120612000-10-12 06:10:25 +0000565 return NULL;
Mark Dickinsonde429622008-05-01 00:19:23 +0000566
567 return (*from_double_func)(r);
Christian Heimes53876d92008-04-19 00:31:39 +0000568}
569
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000570/* variant of math_1, to be used when the function being wrapped is known to
571 set errno properly (that is, errno = EDOM for invalid or divide-by-zero,
572 errno = ERANGE for overflow). */
573
574static PyObject *
575math_1a(PyObject *arg, double (*func) (double))
576{
577 double x, r;
578 x = PyFloat_AsDouble(arg);
579 if (x == -1.0 && PyErr_Occurred())
580 return NULL;
581 errno = 0;
582 PyFPE_START_PROTECT("in math_1a", return 0);
583 r = (*func)(x);
584 PyFPE_END_PROTECT(r);
585 if (errno && is_error(r))
586 return NULL;
587 return PyFloat_FromDouble(r);
588}
589
Christian Heimes53876d92008-04-19 00:31:39 +0000590/*
591 math_2 is used to wrap a libm function f that takes two double
592 arguments and returns a double.
593
594 The error reporting follows these rules, which are designed to do
595 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
596 platforms.
597
598 - a NaN result from non-NaN inputs causes ValueError to be raised
599 - an infinite result from finite inputs causes OverflowError to be
600 raised.
601 - if the result is finite and errno == EDOM then ValueError is
602 raised
603 - if the result is finite and nonzero and errno == ERANGE then
604 OverflowError is raised
605
606 The last rule is used to catch overflow on platforms which follow
607 C89 but for which HUGE_VAL is not an infinity.
608
609 For most two-argument functions (copysign, fmod, hypot, atan2)
610 these rules are enough to ensure that Python's functions behave as
611 specified in 'Annex F' of the C99 standard, with the 'invalid' and
612 'divide-by-zero' floating-point exceptions mapping to Python's
613 ValueError and the 'overflow' floating-point exception mapping to
614 OverflowError.
615*/
616
617static PyObject *
618math_1(PyObject *arg, double (*func) (double), int can_overflow)
619{
620 return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow);
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000621}
622
623static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000624math_1_to_int(PyObject *arg, double (*func) (double), int can_overflow)
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000625{
Christian Heimes53876d92008-04-19 00:31:39 +0000626 return math_1_to_whatever(arg, func, PyLong_FromDouble, can_overflow);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000627}
628
Barry Warsaw8b43b191996-12-09 22:32:36 +0000629static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +0000630math_2(PyObject *args, double (*func) (double, double), char *funcname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000631{
Thomas Wouters89f507f2006-12-13 04:49:30 +0000632 PyObject *ox, *oy;
Christian Heimes53876d92008-04-19 00:31:39 +0000633 double x, y, r;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000634 if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy))
635 return NULL;
636 x = PyFloat_AsDouble(ox);
637 y = PyFloat_AsDouble(oy);
638 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000639 return NULL;
640 errno = 0;
Christian Heimes53876d92008-04-19 00:31:39 +0000641 PyFPE_START_PROTECT("in math_2", return 0);
642 r = (*func)(x, y);
643 PyFPE_END_PROTECT(r);
644 if (Py_IS_NAN(r)) {
645 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
646 errno = EDOM;
647 else
648 errno = 0;
649 }
650 else if (Py_IS_INFINITY(r)) {
651 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
652 errno = ERANGE;
653 else
654 errno = 0;
655 }
656 if (errno && is_error(r))
Tim Peters1d120612000-10-12 06:10:25 +0000657 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000658 else
Christian Heimes53876d92008-04-19 00:31:39 +0000659 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000660}
661
Christian Heimes53876d92008-04-19 00:31:39 +0000662#define FUNC1(funcname, func, can_overflow, docstring) \
Fred Drake40c48682000-07-03 18:11:56 +0000663 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
Christian Heimes53876d92008-04-19 00:31:39 +0000664 return math_1(args, func, can_overflow); \
Guido van Rossumc6e22901998-12-04 19:26:43 +0000665 }\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000666 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000667
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000668#define FUNC1A(funcname, func, docstring) \
669 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
670 return math_1a(args, func); \
671 }\
672 PyDoc_STRVAR(math_##funcname##_doc, docstring);
673
Fred Drake40c48682000-07-03 18:11:56 +0000674#define FUNC2(funcname, func, docstring) \
675 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
Thomas Wouters89f507f2006-12-13 04:49:30 +0000676 return math_2(args, func, #funcname); \
Guido van Rossumc6e22901998-12-04 19:26:43 +0000677 }\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000678 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000679
Christian Heimes53876d92008-04-19 00:31:39 +0000680FUNC1(acos, acos, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000681 "acos(x)\n\nReturn the arc cosine (measured in radians) of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000682FUNC1(acosh, acosh, 0,
683 "acosh(x)\n\nReturn the hyperbolic arc cosine (measured in radians) of x.")
684FUNC1(asin, asin, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000685 "asin(x)\n\nReturn the arc sine (measured in radians) of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000686FUNC1(asinh, asinh, 0,
687 "asinh(x)\n\nReturn the hyperbolic arc sine (measured in radians) of x.")
688FUNC1(atan, atan, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000689 "atan(x)\n\nReturn the arc tangent (measured in radians) of x.")
Christian Heimese57950f2008-04-21 13:08:03 +0000690FUNC2(atan2, m_atan2,
Tim Petersfe71f812001-08-07 22:10:00 +0000691 "atan2(y, x)\n\nReturn the arc tangent (measured in radians) of y/x.\n"
692 "Unlike atan(y/x), the signs of both x and y are considered.")
Christian Heimes53876d92008-04-19 00:31:39 +0000693FUNC1(atanh, atanh, 0,
694 "atanh(x)\n\nReturn the hyperbolic arc tangent (measured in radians) of x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +0000695
696static PyObject * math_ceil(PyObject *self, PyObject *number) {
697 static PyObject *ceil_str = NULL;
698 PyObject *method;
699
700 if (ceil_str == NULL) {
Christian Heimesfe82e772008-01-28 02:38:20 +0000701 ceil_str = PyUnicode_InternFromString("__ceil__");
Guido van Rossum13e05de2007-08-23 22:56:55 +0000702 if (ceil_str == NULL)
703 return NULL;
704 }
705
Christian Heimes90aa7642007-12-19 02:45:37 +0000706 method = _PyType_Lookup(Py_TYPE(number), ceil_str);
Guido van Rossum13e05de2007-08-23 22:56:55 +0000707 if (method == NULL)
Christian Heimes53876d92008-04-19 00:31:39 +0000708 return math_1_to_int(number, ceil, 0);
Guido van Rossum13e05de2007-08-23 22:56:55 +0000709 else
710 return PyObject_CallFunction(method, "O", number);
711}
712
713PyDoc_STRVAR(math_ceil_doc,
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000714 "ceil(x)\n\nReturn the ceiling of x as an int.\n"
Guido van Rossum13e05de2007-08-23 22:56:55 +0000715 "This is the smallest integral value >= x.");
716
Christian Heimes072c0f12008-01-03 23:01:04 +0000717FUNC2(copysign, copysign,
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000718 "copysign(x, y)\n\nReturn x with the sign of y.")
Christian Heimes53876d92008-04-19 00:31:39 +0000719FUNC1(cos, cos, 0,
720 "cos(x)\n\nReturn the cosine of x (measured in radians).")
721FUNC1(cosh, cosh, 1,
722 "cosh(x)\n\nReturn the hyperbolic cosine of x.")
723FUNC1(exp, exp, 1,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000724 "exp(x)\n\nReturn e raised to the power of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000725FUNC1(fabs, fabs, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000726 "fabs(x)\n\nReturn the absolute value of the float x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +0000727
728static PyObject * math_floor(PyObject *self, PyObject *number) {
729 static PyObject *floor_str = NULL;
730 PyObject *method;
731
732 if (floor_str == NULL) {
Christian Heimesfe82e772008-01-28 02:38:20 +0000733 floor_str = PyUnicode_InternFromString("__floor__");
Guido van Rossum13e05de2007-08-23 22:56:55 +0000734 if (floor_str == NULL)
735 return NULL;
736 }
737
Christian Heimes90aa7642007-12-19 02:45:37 +0000738 method = _PyType_Lookup(Py_TYPE(number), floor_str);
Guido van Rossum13e05de2007-08-23 22:56:55 +0000739 if (method == NULL)
Christian Heimes53876d92008-04-19 00:31:39 +0000740 return math_1_to_int(number, floor, 0);
Guido van Rossum13e05de2007-08-23 22:56:55 +0000741 else
742 return PyObject_CallFunction(method, "O", number);
743}
744
745PyDoc_STRVAR(math_floor_doc,
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000746 "floor(x)\n\nReturn the floor of x as an int.\n"
Guido van Rossum13e05de2007-08-23 22:56:55 +0000747 "This is the largest integral value <= x.");
748
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000749FUNC1A(gamma, m_tgamma,
750 "gamma(x)\n\nGamma function at x.")
Mark Dickinson05d2e082009-12-11 20:17:17 +0000751FUNC1A(lgamma, m_lgamma,
752 "lgamma(x)\n\nNatural logarithm of absolute value of Gamma function at x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000753FUNC1(log1p, log1p, 1,
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000754 "log1p(x)\n\nReturn the natural logarithm of 1+x (base e).\n"
755 "The result is computed in a way which is accurate for x near zero.")
Christian Heimes53876d92008-04-19 00:31:39 +0000756FUNC1(sin, sin, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000757 "sin(x)\n\nReturn the sine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +0000758FUNC1(sinh, sinh, 1,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000759 "sinh(x)\n\nReturn the hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000760FUNC1(sqrt, sqrt, 0,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000761 "sqrt(x)\n\nReturn the square root of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000762FUNC1(tan, tan, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000763 "tan(x)\n\nReturn the tangent of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +0000764FUNC1(tanh, tanh, 0,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000765 "tanh(x)\n\nReturn the hyperbolic tangent of x.")
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000766
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000767/* Precision summation function as msum() by Raymond Hettinger in
768 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
769 enhanced with the exact partials sum and roundoff from Mark
770 Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
771 See those links for more details, proofs and other references.
772
773 Note 1: IEEE 754R floating point semantics are assumed,
774 but the current implementation does not re-establish special
775 value semantics across iterations (i.e. handling -Inf + Inf).
776
777 Note 2: No provision is made for intermediate overflow handling;
Georg Brandlf78e02b2008-06-10 17:40:04 +0000778 therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000779 sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
780 overflow of the first partial sum.
781
Benjamin Petersonfea6a942008-07-02 16:11:42 +0000782 Note 3: The intermediate values lo, yr, and hi are declared volatile so
783 aggressive compilers won't algebraically reduce lo to always be exactly 0.0.
Georg Brandlf78e02b2008-06-10 17:40:04 +0000784 Also, the volatile declaration forces the values to be stored in memory as
785 regular doubles instead of extended long precision (80-bit) values. This
Benjamin Petersonfea6a942008-07-02 16:11:42 +0000786 prevents double rounding because any addition or subtraction of two doubles
Georg Brandlf78e02b2008-06-10 17:40:04 +0000787 can be resolved exactly into double-sized hi and lo values. As long as the
788 hi value gets forced into a double before yr and lo are computed, the extra
789 bits in downstream extended precision operations (x87 for example) will be
790 exactly zero and therefore can be losslessly stored back into a double,
791 thereby preventing double rounding.
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000792
793 Note 4: A similar implementation is in Modules/cmathmodule.c.
794 Be sure to update both when making changes.
795
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000796 Note 5: The signature of math.fsum() differs from __builtin__.sum()
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000797 because the start argument doesn't make sense in the context of
798 accurate summation. Since the partials table is collapsed before
799 returning a result, sum(seq2, start=sum(seq1)) may not equal the
800 accurate result returned by sum(itertools.chain(seq1, seq2)).
801*/
802
803#define NUM_PARTIALS 32 /* initial partials array size, on stack */
804
805/* Extend the partials array p[] by doubling its size. */
806static int /* non-zero on error */
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000807_fsum_realloc(double **p_ptr, Py_ssize_t n,
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000808 double *ps, Py_ssize_t *m_ptr)
809{
810 void *v = NULL;
811 Py_ssize_t m = *m_ptr;
812
813 m += m; /* double */
814 if (n < m && m < (PY_SSIZE_T_MAX / sizeof(double))) {
815 double *p = *p_ptr;
816 if (p == ps) {
817 v = PyMem_Malloc(sizeof(double) * m);
818 if (v != NULL)
819 memcpy(v, ps, sizeof(double) * n);
820 }
821 else
822 v = PyMem_Realloc(p, sizeof(double) * m);
823 }
824 if (v == NULL) { /* size overflow or no memory */
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000825 PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000826 return 1;
827 }
828 *p_ptr = (double*) v;
829 *m_ptr = m;
830 return 0;
831}
832
833/* Full precision summation of a sequence of floats.
834
835 def msum(iterable):
836 partials = [] # sorted, non-overlapping partial sums
837 for x in iterable:
838 i = 0
839 for y in partials:
840 if abs(x) < abs(y):
841 x, y = y, x
842 hi = x + y
843 lo = y - (hi - x)
844 if lo:
845 partials[i] = lo
846 i += 1
847 x = hi
848 partials[i:] = [x]
849 return sum_exact(partials)
850
851 Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
852 are exactly equal to x+y. The inner loop applies hi/lo summation to each
853 partial so that the list of partial sums remains exact.
854
855 Sum_exact() adds the partial sums exactly and correctly rounds the final
856 result (using the round-half-to-even rule). The items in partials remain
857 non-zero, non-special, non-overlapping and strictly increasing in
858 magnitude, but possibly not all having the same sign.
859
860 Depends on IEEE 754 arithmetic guarantees and half-even rounding.
861*/
862
863static PyObject*
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000864math_fsum(PyObject *self, PyObject *seq)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000865{
866 PyObject *item, *iter, *sum = NULL;
867 Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
Georg Brandlf78e02b2008-06-10 17:40:04 +0000868 double x, y, t, ps[NUM_PARTIALS], *p = ps;
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000869 double xsave, special_sum = 0.0, inf_sum = 0.0;
Georg Brandlf78e02b2008-06-10 17:40:04 +0000870 volatile double hi, yr, lo;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000871
872 iter = PyObject_GetIter(seq);
873 if (iter == NULL)
874 return NULL;
875
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000876 PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000877
878 for(;;) { /* for x in iterable */
879 assert(0 <= n && n <= m);
880 assert((m == NUM_PARTIALS && p == ps) ||
881 (m > NUM_PARTIALS && p != NULL));
882
883 item = PyIter_Next(iter);
884 if (item == NULL) {
885 if (PyErr_Occurred())
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000886 goto _fsum_error;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000887 break;
888 }
889 x = PyFloat_AsDouble(item);
890 Py_DECREF(item);
891 if (PyErr_Occurred())
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000892 goto _fsum_error;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000893
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000894 xsave = x;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000895 for (i = j = 0; j < n; j++) { /* for y in partials */
896 y = p[j];
Georg Brandlf78e02b2008-06-10 17:40:04 +0000897 if (fabs(x) < fabs(y)) {
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000898 t = x; x = y; y = t;
Georg Brandlf78e02b2008-06-10 17:40:04 +0000899 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000900 hi = x + y;
Georg Brandlf78e02b2008-06-10 17:40:04 +0000901 yr = hi - x;
902 lo = y - yr;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000903 if (lo != 0.0)
904 p[i++] = lo;
905 x = hi;
906 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000907
908 n = i; /* ps[i:] = [x] */
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000909 if (x != 0.0) {
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000910 if (! Py_IS_FINITE(x)) {
911 /* a nonfinite x could arise either as
912 a result of intermediate overflow, or
913 as a result of a nan or inf in the
914 summands */
915 if (Py_IS_FINITE(xsave)) {
916 PyErr_SetString(PyExc_OverflowError,
917 "intermediate overflow in fsum");
918 goto _fsum_error;
919 }
920 if (Py_IS_INFINITY(xsave))
921 inf_sum += xsave;
922 special_sum += xsave;
923 /* reset partials */
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000924 n = 0;
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000925 }
926 else if (n >= m && _fsum_realloc(&p, n, ps, &m))
927 goto _fsum_error;
928 else
929 p[n++] = x;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000930 }
931 }
932
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000933 if (special_sum != 0.0) {
934 if (Py_IS_NAN(inf_sum))
935 PyErr_SetString(PyExc_ValueError,
936 "-inf + inf in fsum");
937 else
938 sum = PyFloat_FromDouble(special_sum);
939 goto _fsum_error;
940 }
941
Georg Brandlf78e02b2008-06-10 17:40:04 +0000942 hi = 0.0;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000943 if (n > 0) {
944 hi = p[--n];
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000945 /* sum_exact(ps, hi) from the top, stop when the sum becomes
946 inexact. */
947 while (n > 0) {
948 x = hi;
949 y = p[--n];
950 assert(fabs(y) < fabs(x));
951 hi = x + y;
952 yr = hi - x;
953 lo = y - yr;
954 if (lo != 0.0)
955 break;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000956 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000957 /* Make half-even rounding work across multiple partials.
958 Needed so that sum([1e-16, 1, 1e16]) will round-up the last
959 digit to two instead of down to zero (the 1e-16 makes the 1
960 slightly closer to two). With a potential 1 ULP rounding
961 error fixed-up, math.fsum() can guarantee commutativity. */
962 if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
963 (lo > 0.0 && p[n-1] > 0.0))) {
964 y = lo * 2.0;
965 x = hi + y;
966 yr = x - hi;
967 if (y == yr)
968 hi = x;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000969 }
970 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000971 sum = PyFloat_FromDouble(hi);
972
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000973_fsum_error:
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000974 PyFPE_END_PROTECT(hi)
975 Py_DECREF(iter);
976 if (p != ps)
977 PyMem_Free(p);
978 return sum;
979}
980
981#undef NUM_PARTIALS
982
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000983PyDoc_STRVAR(math_fsum_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000984"fsum(iterable)\n\n\
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000985Return an accurate floating point sum of values in the iterable.\n\
986Assumes IEEE-754 floating point arithmetic.");
987
Barry Warsaw8b43b191996-12-09 22:32:36 +0000988static PyObject *
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000989math_factorial(PyObject *self, PyObject *arg)
990{
991 long i, x;
992 PyObject *result, *iobj, *newresult;
993
994 if (PyFloat_Check(arg)) {
995 double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
996 if (dx != floor(dx)) {
997 PyErr_SetString(PyExc_ValueError,
998 "factorial() only accepts integral values");
999 return NULL;
1000 }
1001 }
1002
1003 x = PyLong_AsLong(arg);
1004 if (x == -1 && PyErr_Occurred())
1005 return NULL;
1006 if (x < 0) {
1007 PyErr_SetString(PyExc_ValueError,
1008 "factorial() not defined for negative values");
1009 return NULL;
1010 }
1011
1012 result = (PyObject *)PyLong_FromLong(1);
1013 if (result == NULL)
1014 return NULL;
1015 for (i=1 ; i<=x ; i++) {
1016 iobj = (PyObject *)PyLong_FromLong(i);
1017 if (iobj == NULL)
1018 goto error;
1019 newresult = PyNumber_Multiply(result, iobj);
1020 Py_DECREF(iobj);
1021 if (newresult == NULL)
1022 goto error;
1023 Py_DECREF(result);
1024 result = newresult;
1025 }
1026 return result;
1027
1028error:
1029 Py_DECREF(result);
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001030 return NULL;
1031}
1032
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001033PyDoc_STRVAR(math_factorial_doc,
1034"factorial(x) -> Integral\n"
1035"\n"
1036"Find x!. Raise a ValueError if x is negative or non-integral.");
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001037
1038static PyObject *
Christian Heimes400adb02008-02-01 08:12:03 +00001039math_trunc(PyObject *self, PyObject *number)
1040{
1041 static PyObject *trunc_str = NULL;
1042 PyObject *trunc;
1043
1044 if (Py_TYPE(number)->tp_dict == NULL) {
1045 if (PyType_Ready(Py_TYPE(number)) < 0)
1046 return NULL;
1047 }
1048
1049 if (trunc_str == NULL) {
1050 trunc_str = PyUnicode_InternFromString("__trunc__");
1051 if (trunc_str == NULL)
1052 return NULL;
1053 }
1054
1055 trunc = _PyType_Lookup(Py_TYPE(number), trunc_str);
1056 if (trunc == NULL) {
1057 PyErr_Format(PyExc_TypeError,
1058 "type %.100s doesn't define __trunc__ method",
1059 Py_TYPE(number)->tp_name);
1060 return NULL;
1061 }
1062 return PyObject_CallFunctionObjArgs(trunc, number, NULL);
1063}
1064
1065PyDoc_STRVAR(math_trunc_doc,
1066"trunc(x:Real) -> Integral\n"
1067"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001068"Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.");
Christian Heimes400adb02008-02-01 08:12:03 +00001069
1070static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001071math_frexp(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001072{
Guido van Rossumd18ad581991-10-24 14:57:21 +00001073 int i;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001074 double x = PyFloat_AsDouble(arg);
1075 if (x == -1.0 && PyErr_Occurred())
Guido van Rossumd18ad581991-10-24 14:57:21 +00001076 return NULL;
Christian Heimes53876d92008-04-19 00:31:39 +00001077 /* deal with special cases directly, to sidestep platform
1078 differences */
1079 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
1080 i = 0;
1081 }
1082 else {
1083 PyFPE_START_PROTECT("in math_frexp", return 0);
1084 x = frexp(x, &i);
1085 PyFPE_END_PROTECT(x);
1086 }
1087 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001088}
1089
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001090PyDoc_STRVAR(math_frexp_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001091"frexp(x)\n"
1092"\n"
1093"Return the mantissa and exponent of x, as pair (m, e).\n"
1094"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 +00001095"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 +00001096
Barry Warsaw8b43b191996-12-09 22:32:36 +00001097static PyObject *
Fred Drake40c48682000-07-03 18:11:56 +00001098math_ldexp(PyObject *self, PyObject *args)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001099{
Christian Heimes53876d92008-04-19 00:31:39 +00001100 double x, r;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001101 PyObject *oexp;
1102 long exp;
1103 if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp))
Guido van Rossumd18ad581991-10-24 14:57:21 +00001104 return NULL;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001105
1106 if (PyLong_Check(oexp)) {
1107 /* on overflow, replace exponent with either LONG_MAX
1108 or LONG_MIN, depending on the sign. */
1109 exp = PyLong_AsLong(oexp);
1110 if (exp == -1 && PyErr_Occurred()) {
1111 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1112 if (Py_SIZE(oexp) < 0) {
1113 exp = LONG_MIN;
1114 }
1115 else {
1116 exp = LONG_MAX;
1117 }
1118 PyErr_Clear();
1119 }
1120 else {
1121 /* propagate any unexpected exception */
1122 return NULL;
1123 }
1124 }
1125 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001126 else {
1127 PyErr_SetString(PyExc_TypeError,
1128 "Expected an int or long as second argument "
1129 "to ldexp.");
1130 return NULL;
1131 }
1132
1133 if (x == 0. || !Py_IS_FINITE(x)) {
1134 /* NaNs, zeros and infinities are returned unchanged */
1135 r = x;
Christian Heimes53876d92008-04-19 00:31:39 +00001136 errno = 0;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001137 } else if (exp > INT_MAX) {
1138 /* overflow */
1139 r = copysign(Py_HUGE_VAL, x);
1140 errno = ERANGE;
1141 } else if (exp < INT_MIN) {
1142 /* underflow to +-0 */
1143 r = copysign(0., x);
1144 errno = 0;
1145 } else {
1146 errno = 0;
1147 PyFPE_START_PROTECT("in math_ldexp", return 0);
1148 r = ldexp(x, (int)exp);
1149 PyFPE_END_PROTECT(r);
1150 if (Py_IS_INFINITY(r))
1151 errno = ERANGE;
1152 }
1153
Christian Heimes53876d92008-04-19 00:31:39 +00001154 if (errno && is_error(r))
Tim Peters1d120612000-10-12 06:10:25 +00001155 return NULL;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001156 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001157}
1158
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001159PyDoc_STRVAR(math_ldexp_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001160"ldexp(x, i)\n\n\
1161Return x * (2**i).");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001162
Barry Warsaw8b43b191996-12-09 22:32:36 +00001163static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001164math_modf(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +00001165{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001166 double y, x = PyFloat_AsDouble(arg);
1167 if (x == -1.0 && PyErr_Occurred())
Guido van Rossumd18ad581991-10-24 14:57:21 +00001168 return NULL;
Christian Heimesa342c012008-04-20 21:01:16 +00001169 /* some platforms don't do the right thing for NaNs and
1170 infinities, so we take care of special cases directly. */
1171 if (!Py_IS_FINITE(x)) {
1172 if (Py_IS_INFINITY(x))
1173 return Py_BuildValue("(dd)", copysign(0., x), x);
1174 else if (Py_IS_NAN(x))
1175 return Py_BuildValue("(dd)", x, x);
1176 }
1177
Guido van Rossumd18ad581991-10-24 14:57:21 +00001178 errno = 0;
Christian Heimes53876d92008-04-19 00:31:39 +00001179 PyFPE_START_PROTECT("in math_modf", return 0);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001180 x = modf(x, &y);
Christian Heimes53876d92008-04-19 00:31:39 +00001181 PyFPE_END_PROTECT(x);
1182 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001183}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001184
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001185PyDoc_STRVAR(math_modf_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001186"modf(x)\n"
1187"\n"
1188"Return the fractional and integer parts of x. Both results carry the sign\n"
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001189"of x and are floats.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001190
Tim Peters78526162001-09-05 00:53:45 +00001191/* A decent logarithm is easy to compute even for huge longs, but libm can't
1192 do that by itself -- loghelper can. func is log or log10, and name is
1193 "log" or "log10". Note that overflow isn't possible: a long can contain
1194 no more than INT_MAX * SHIFT bits, so has value certainly less than
1195 2**(2**64 * 2**16) == 2**2**80, and log2 of that is 2**80, which is
1196 small enough to fit in an IEEE single. log and log10 are even smaller.
1197*/
1198
1199static PyObject*
Thomas Wouters89f507f2006-12-13 04:49:30 +00001200loghelper(PyObject* arg, double (*func)(double), char *funcname)
Tim Peters78526162001-09-05 00:53:45 +00001201{
Tim Peters78526162001-09-05 00:53:45 +00001202 /* If it is long, do it ourselves. */
1203 if (PyLong_Check(arg)) {
1204 double x;
1205 int e;
1206 x = _PyLong_AsScaledDouble(arg, &e);
1207 if (x <= 0.0) {
1208 PyErr_SetString(PyExc_ValueError,
1209 "math domain error");
1210 return NULL;
1211 }
Christian Heimesaf98da12008-01-27 15:18:18 +00001212 /* Value is ~= x * 2**(e*PyLong_SHIFT), so the log ~=
1213 log(x) + log(2) * e * PyLong_SHIFT.
1214 CAUTION: e*PyLong_SHIFT may overflow using int arithmetic,
Tim Peters78526162001-09-05 00:53:45 +00001215 so force use of double. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001216 x = func(x) + (e * (double)PyLong_SHIFT) * func(2.0);
Tim Peters78526162001-09-05 00:53:45 +00001217 return PyFloat_FromDouble(x);
1218 }
1219
1220 /* Else let libm handle it by itself. */
Christian Heimes53876d92008-04-19 00:31:39 +00001221 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +00001222}
1223
1224static PyObject *
1225math_log(PyObject *self, PyObject *args)
1226{
Raymond Hettinger866964c2002-12-14 19:51:34 +00001227 PyObject *arg;
1228 PyObject *base = NULL;
1229 PyObject *num, *den;
1230 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001231
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001232 if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base))
Raymond Hettinger866964c2002-12-14 19:51:34 +00001233 return NULL;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001234
Mark Dickinsone675f082008-12-11 21:56:00 +00001235 num = loghelper(arg, m_log, "log");
Thomas Wouters89f507f2006-12-13 04:49:30 +00001236 if (num == NULL || base == NULL)
1237 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001238
Mark Dickinsone675f082008-12-11 21:56:00 +00001239 den = loghelper(base, m_log, "log");
Raymond Hettinger866964c2002-12-14 19:51:34 +00001240 if (den == NULL) {
1241 Py_DECREF(num);
1242 return NULL;
1243 }
1244
Neal Norwitzbcc0db82006-03-24 08:14:36 +00001245 ans = PyNumber_TrueDivide(num, den);
Raymond Hettinger866964c2002-12-14 19:51:34 +00001246 Py_DECREF(num);
1247 Py_DECREF(den);
1248 return ans;
Tim Peters78526162001-09-05 00:53:45 +00001249}
1250
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001251PyDoc_STRVAR(math_log_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001252"log(x[, base])\n\n\
1253Return the logarithm of x to the given base.\n\
Raymond Hettinger866964c2002-12-14 19:51:34 +00001254If the base not specified, returns the natural logarithm (base e) of x.");
Tim Peters78526162001-09-05 00:53:45 +00001255
1256static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001257math_log10(PyObject *self, PyObject *arg)
Tim Peters78526162001-09-05 00:53:45 +00001258{
Mark Dickinsone675f082008-12-11 21:56:00 +00001259 return loghelper(arg, m_log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +00001260}
1261
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001262PyDoc_STRVAR(math_log10_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001263"log10(x)\n\nReturn the base 10 logarithm of x.");
Tim Peters78526162001-09-05 00:53:45 +00001264
Christian Heimes53876d92008-04-19 00:31:39 +00001265static PyObject *
1266math_fmod(PyObject *self, PyObject *args)
1267{
1268 PyObject *ox, *oy;
1269 double r, x, y;
1270 if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy))
1271 return NULL;
1272 x = PyFloat_AsDouble(ox);
1273 y = PyFloat_AsDouble(oy);
1274 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1275 return NULL;
1276 /* fmod(x, +/-Inf) returns x for finite x. */
1277 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
1278 return PyFloat_FromDouble(x);
1279 errno = 0;
1280 PyFPE_START_PROTECT("in math_fmod", return 0);
1281 r = fmod(x, y);
1282 PyFPE_END_PROTECT(r);
1283 if (Py_IS_NAN(r)) {
1284 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1285 errno = EDOM;
1286 else
1287 errno = 0;
1288 }
1289 if (errno && is_error(r))
1290 return NULL;
1291 else
1292 return PyFloat_FromDouble(r);
1293}
1294
1295PyDoc_STRVAR(math_fmod_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001296"fmod(x, y)\n\nReturn fmod(x, y), according to platform C."
Christian Heimes53876d92008-04-19 00:31:39 +00001297" x % y may differ.");
1298
1299static PyObject *
1300math_hypot(PyObject *self, PyObject *args)
1301{
1302 PyObject *ox, *oy;
1303 double r, x, y;
1304 if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy))
1305 return NULL;
1306 x = PyFloat_AsDouble(ox);
1307 y = PyFloat_AsDouble(oy);
1308 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1309 return NULL;
1310 /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */
1311 if (Py_IS_INFINITY(x))
1312 return PyFloat_FromDouble(fabs(x));
1313 if (Py_IS_INFINITY(y))
1314 return PyFloat_FromDouble(fabs(y));
1315 errno = 0;
1316 PyFPE_START_PROTECT("in math_hypot", return 0);
1317 r = hypot(x, y);
1318 PyFPE_END_PROTECT(r);
1319 if (Py_IS_NAN(r)) {
1320 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1321 errno = EDOM;
1322 else
1323 errno = 0;
1324 }
1325 else if (Py_IS_INFINITY(r)) {
1326 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
1327 errno = ERANGE;
1328 else
1329 errno = 0;
1330 }
1331 if (errno && is_error(r))
1332 return NULL;
1333 else
1334 return PyFloat_FromDouble(r);
1335}
1336
1337PyDoc_STRVAR(math_hypot_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001338"hypot(x, y)\n\nReturn the Euclidean distance, sqrt(x*x + y*y).");
Christian Heimes53876d92008-04-19 00:31:39 +00001339
1340/* pow can't use math_2, but needs its own wrapper: the problem is
1341 that an infinite result can arise either as a result of overflow
1342 (in which case OverflowError should be raised) or as a result of
1343 e.g. 0.**-5. (for which ValueError needs to be raised.)
1344*/
1345
1346static PyObject *
1347math_pow(PyObject *self, PyObject *args)
1348{
1349 PyObject *ox, *oy;
1350 double r, x, y;
Christian Heimesa342c012008-04-20 21:01:16 +00001351 int odd_y;
Christian Heimes53876d92008-04-19 00:31:39 +00001352
1353 if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy))
1354 return NULL;
1355 x = PyFloat_AsDouble(ox);
1356 y = PyFloat_AsDouble(oy);
1357 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1358 return NULL;
Christian Heimesa342c012008-04-20 21:01:16 +00001359
1360 /* deal directly with IEEE specials, to cope with problems on various
1361 platforms whose semantics don't exactly match C99 */
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001362 r = 0.; /* silence compiler warning */
Christian Heimesa342c012008-04-20 21:01:16 +00001363 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
1364 errno = 0;
1365 if (Py_IS_NAN(x))
1366 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
1367 else if (Py_IS_NAN(y))
1368 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
1369 else if (Py_IS_INFINITY(x)) {
1370 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
1371 if (y > 0.)
1372 r = odd_y ? x : fabs(x);
1373 else if (y == 0.)
1374 r = 1.;
1375 else /* y < 0. */
1376 r = odd_y ? copysign(0., x) : 0.;
1377 }
1378 else if (Py_IS_INFINITY(y)) {
1379 if (fabs(x) == 1.0)
1380 r = 1.;
1381 else if (y > 0. && fabs(x) > 1.0)
1382 r = y;
1383 else if (y < 0. && fabs(x) < 1.0) {
1384 r = -y; /* result is +inf */
1385 if (x == 0.) /* 0**-inf: divide-by-zero */
1386 errno = EDOM;
1387 }
1388 else
1389 r = 0.;
1390 }
Christian Heimes53876d92008-04-19 00:31:39 +00001391 }
Christian Heimesa342c012008-04-20 21:01:16 +00001392 else {
1393 /* let libm handle finite**finite */
1394 errno = 0;
1395 PyFPE_START_PROTECT("in math_pow", return 0);
1396 r = pow(x, y);
1397 PyFPE_END_PROTECT(r);
1398 /* a NaN result should arise only from (-ve)**(finite
1399 non-integer); in this case we want to raise ValueError. */
1400 if (!Py_IS_FINITE(r)) {
1401 if (Py_IS_NAN(r)) {
1402 errno = EDOM;
1403 }
1404 /*
1405 an infinite result here arises either from:
1406 (A) (+/-0.)**negative (-> divide-by-zero)
1407 (B) overflow of x**y with x and y finite
1408 */
1409 else if (Py_IS_INFINITY(r)) {
1410 if (x == 0.)
1411 errno = EDOM;
1412 else
1413 errno = ERANGE;
1414 }
1415 }
Christian Heimes53876d92008-04-19 00:31:39 +00001416 }
1417
1418 if (errno && is_error(r))
1419 return NULL;
1420 else
1421 return PyFloat_FromDouble(r);
1422}
1423
1424PyDoc_STRVAR(math_pow_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001425"pow(x, y)\n\nReturn x**y (x to the power of y).");
Christian Heimes53876d92008-04-19 00:31:39 +00001426
Christian Heimes072c0f12008-01-03 23:01:04 +00001427static const double degToRad = Py_MATH_PI / 180.0;
1428static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001429
1430static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001431math_degrees(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001432{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001433 double x = PyFloat_AsDouble(arg);
1434 if (x == -1.0 && PyErr_Occurred())
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001435 return NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +00001436 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001437}
1438
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001439PyDoc_STRVAR(math_degrees_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001440"degrees(x)\n\n\
1441Convert angle x from radians to degrees.");
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001442
1443static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001444math_radians(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001445{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001446 double x = PyFloat_AsDouble(arg);
1447 if (x == -1.0 && PyErr_Occurred())
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001448 return NULL;
1449 return PyFloat_FromDouble(x * degToRad);
1450}
1451
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001452PyDoc_STRVAR(math_radians_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001453"radians(x)\n\n\
1454Convert angle x from degrees to radians.");
Tim Peters78526162001-09-05 00:53:45 +00001455
Christian Heimes072c0f12008-01-03 23:01:04 +00001456static PyObject *
1457math_isnan(PyObject *self, PyObject *arg)
1458{
1459 double x = PyFloat_AsDouble(arg);
1460 if (x == -1.0 && PyErr_Occurred())
1461 return NULL;
1462 return PyBool_FromLong((long)Py_IS_NAN(x));
1463}
1464
1465PyDoc_STRVAR(math_isnan_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001466"isnan(x) -> bool\n\n\
1467Check if float x is not a number (NaN).");
Christian Heimes072c0f12008-01-03 23:01:04 +00001468
1469static PyObject *
1470math_isinf(PyObject *self, PyObject *arg)
1471{
1472 double x = PyFloat_AsDouble(arg);
1473 if (x == -1.0 && PyErr_Occurred())
1474 return NULL;
1475 return PyBool_FromLong((long)Py_IS_INFINITY(x));
1476}
1477
1478PyDoc_STRVAR(math_isinf_doc,
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001479"isinf(x) -> bool\n\n\
1480Check if float x is infinite (positive or negative).");
Christian Heimes072c0f12008-01-03 23:01:04 +00001481
Barry Warsaw8b43b191996-12-09 22:32:36 +00001482static PyMethodDef math_methods[] = {
Thomas Wouters89f507f2006-12-13 04:49:30 +00001483 {"acos", math_acos, METH_O, math_acos_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001484 {"acosh", math_acosh, METH_O, math_acosh_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001485 {"asin", math_asin, METH_O, math_asin_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001486 {"asinh", math_asinh, METH_O, math_asinh_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001487 {"atan", math_atan, METH_O, math_atan_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001488 {"atan2", math_atan2, METH_VARARGS, math_atan2_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001489 {"atanh", math_atanh, METH_O, math_atanh_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001490 {"ceil", math_ceil, METH_O, math_ceil_doc},
Christian Heimes072c0f12008-01-03 23:01:04 +00001491 {"copysign", math_copysign, METH_VARARGS, math_copysign_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001492 {"cos", math_cos, METH_O, math_cos_doc},
1493 {"cosh", math_cosh, METH_O, math_cosh_doc},
1494 {"degrees", math_degrees, METH_O, math_degrees_doc},
1495 {"exp", math_exp, METH_O, math_exp_doc},
1496 {"fabs", math_fabs, METH_O, math_fabs_doc},
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001497 {"factorial", math_factorial, METH_O, math_factorial_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001498 {"floor", math_floor, METH_O, math_floor_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001499 {"fmod", math_fmod, METH_VARARGS, math_fmod_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001500 {"frexp", math_frexp, METH_O, math_frexp_doc},
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001501 {"fsum", math_fsum, METH_O, math_fsum_doc},
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001502 {"gamma", math_gamma, METH_O, math_gamma_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001503 {"hypot", math_hypot, METH_VARARGS, math_hypot_doc},
Christian Heimes072c0f12008-01-03 23:01:04 +00001504 {"isinf", math_isinf, METH_O, math_isinf_doc},
1505 {"isnan", math_isnan, METH_O, math_isnan_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001506 {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc},
Mark Dickinson05d2e082009-12-11 20:17:17 +00001507 {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001508 {"log", math_log, METH_VARARGS, math_log_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001509 {"log1p", math_log1p, METH_O, math_log1p_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001510 {"log10", math_log10, METH_O, math_log10_doc},
1511 {"modf", math_modf, METH_O, math_modf_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001512 {"pow", math_pow, METH_VARARGS, math_pow_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001513 {"radians", math_radians, METH_O, math_radians_doc},
1514 {"sin", math_sin, METH_O, math_sin_doc},
1515 {"sinh", math_sinh, METH_O, math_sinh_doc},
1516 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
1517 {"tan", math_tan, METH_O, math_tan_doc},
1518 {"tanh", math_tanh, METH_O, math_tanh_doc},
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001519 {"trunc", math_trunc, METH_O, math_trunc_doc},
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001520 {NULL, NULL} /* sentinel */
1521};
1522
Guido van Rossumc6e22901998-12-04 19:26:43 +00001523
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001524PyDoc_STRVAR(module_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001525"This module is always available. It provides access to the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001526"mathematical functions defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001527
Martin v. Löwis1a214512008-06-11 05:26:20 +00001528
1529static struct PyModuleDef mathmodule = {
1530 PyModuleDef_HEAD_INIT,
1531 "math",
1532 module_doc,
1533 -1,
1534 math_methods,
1535 NULL,
1536 NULL,
1537 NULL,
1538 NULL
1539};
1540
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001541PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001542PyInit_math(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001543{
Christian Heimes53876d92008-04-19 00:31:39 +00001544 PyObject *m;
Tim Petersfe71f812001-08-07 22:10:00 +00001545
Martin v. Löwis1a214512008-06-11 05:26:20 +00001546 m = PyModule_Create(&mathmodule);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00001547 if (m == NULL)
1548 goto finally;
Barry Warsawfc93f751996-12-17 00:47:03 +00001549
Christian Heimes53876d92008-04-19 00:31:39 +00001550 PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
1551 PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
Barry Warsawfc93f751996-12-17 00:47:03 +00001552
Christian Heimes53876d92008-04-19 00:31:39 +00001553 finally:
Martin v. Löwis1a214512008-06-11 05:26:20 +00001554 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001555}