blob: 7ace9972c387bf9ea09c2c84cee54b58ae9e6aa9 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Math module -- standard C math library functions, pi and e */
2
Christian Heimes6f341092008-04-18 23:13:07 +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
Neal Norwitz5f95a792008-01-25 08:04:16 +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
Tim Peters1d120612000-10-12 06:10:25 +000063/* Call is_error when errno != 0, and where x is the result libm
64 * returned. is_error will usually set up an exception and return
65 * true (1), but may return false (0) without setting up an exception.
66 */
67static int
68is_error(double x)
Guido van Rossum8832b621991-12-16 15:44:24 +000069{
Tim Peters1d120612000-10-12 06:10:25 +000070 int result = 1; /* presumption of guilt */
Tim Peters2bf405a2000-10-12 19:42:00 +000071 assert(errno); /* non-zero errno is a precondition for calling */
Guido van Rossum8832b621991-12-16 15:44:24 +000072 if (errno == EDOM)
Barry Warsaw8b43b191996-12-09 22:32:36 +000073 PyErr_SetString(PyExc_ValueError, "math domain error");
Tim Petersa40c7932001-09-05 22:36:56 +000074
Tim Peters1d120612000-10-12 06:10:25 +000075 else if (errno == ERANGE) {
76 /* ANSI C generally requires libm functions to set ERANGE
77 * on overflow, but also generally *allows* them to set
78 * ERANGE on underflow too. There's no consistency about
Tim Petersa40c7932001-09-05 22:36:56 +000079 * the latter across platforms.
80 * Alas, C99 never requires that errno be set.
81 * Here we suppress the underflow errors (libm functions
82 * should return a zero on underflow, and +- HUGE_VAL on
83 * overflow, so testing the result for zero suffices to
84 * distinguish the cases).
Tim Peters1d120612000-10-12 06:10:25 +000085 */
86 if (x)
Tim Petersfe71f812001-08-07 22:10:00 +000087 PyErr_SetString(PyExc_OverflowError,
Tim Peters1d120612000-10-12 06:10:25 +000088 "math range error");
89 else
90 result = 0;
91 }
Guido van Rossum8832b621991-12-16 15:44:24 +000092 else
Barry Warsaw8b43b191996-12-09 22:32:36 +000093 /* Unexpected math error */
94 PyErr_SetFromErrno(PyExc_ValueError);
Tim Peters1d120612000-10-12 06:10:25 +000095 return result;
Guido van Rossum8832b621991-12-16 15:44:24 +000096}
97
Christian Heimes6f341092008-04-18 23:13:07 +000098/*
Mark Dickinson92483cd2008-04-20 21:39:04 +000099 wrapper for atan2 that deals directly with special cases before
100 delegating to the platform libm for the remaining cases. This
101 is necessary to get consistent behaviour across platforms.
102 Windows, FreeBSD and alpha Tru64 are amongst platforms that don't
103 always follow C99.
104*/
105
106static double
107m_atan2(double y, double x)
108{
109 if (Py_IS_NAN(x) || Py_IS_NAN(y))
110 return Py_NAN;
111 if (Py_IS_INFINITY(y)) {
112 if (Py_IS_INFINITY(x)) {
113 if (copysign(1., x) == 1.)
114 /* atan2(+-inf, +inf) == +-pi/4 */
115 return copysign(0.25*Py_MATH_PI, y);
116 else
117 /* atan2(+-inf, -inf) == +-pi*3/4 */
118 return copysign(0.75*Py_MATH_PI, y);
119 }
120 /* atan2(+-inf, x) == +-pi/2 for finite x */
121 return copysign(0.5*Py_MATH_PI, y);
122 }
123 if (Py_IS_INFINITY(x) || y == 0.) {
124 if (copysign(1., x) == 1.)
125 /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */
126 return copysign(0., y);
127 else
128 /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */
129 return copysign(Py_MATH_PI, y);
130 }
131 return atan2(y, x);
132}
133
134/*
Christian Heimes6f341092008-04-18 23:13:07 +0000135 math_1 is used to wrap a libm function f that takes a double
136 arguments and returns a double.
137
138 The error reporting follows these rules, which are designed to do
139 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
140 platforms.
141
142 - a NaN result from non-NaN inputs causes ValueError to be raised
143 - an infinite result from finite inputs causes OverflowError to be
144 raised if can_overflow is 1, or raises ValueError if can_overflow
145 is 0.
146 - if the result is finite and errno == EDOM then ValueError is
147 raised
148 - if the result is finite and nonzero and errno == ERANGE then
149 OverflowError is raised
150
151 The last rule is used to catch overflow on platforms which follow
152 C89 but for which HUGE_VAL is not an infinity.
153
154 For the majority of one-argument functions these rules are enough
155 to ensure that Python's functions behave as specified in 'Annex F'
156 of the C99 standard, with the 'invalid' and 'divide-by-zero'
157 floating-point exceptions mapping to Python's ValueError and the
158 'overflow' floating-point exception mapping to OverflowError.
159 math_1 only works for functions that don't have singularities *and*
160 the possibility of overflow; fortunately, that covers everything we
161 care about right now.
162*/
163
Barry Warsaw8b43b191996-12-09 22:32:36 +0000164static PyObject *
Christian Heimes6f341092008-04-18 23:13:07 +0000165math_1(PyObject *arg, double (*func) (double), int can_overflow)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000166{
Christian Heimes6f341092008-04-18 23:13:07 +0000167 double x, r;
168 x = PyFloat_AsDouble(arg);
Neal Norwitz45e230a2006-11-19 21:26:53 +0000169 if (x == -1.0 && PyErr_Occurred())
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000170 return NULL;
171 errno = 0;
Christian Heimes6f341092008-04-18 23:13:07 +0000172 PyFPE_START_PROTECT("in math_1", return 0);
173 r = (*func)(x);
174 PyFPE_END_PROTECT(r);
175 if (Py_IS_NAN(r)) {
176 if (!Py_IS_NAN(x))
177 errno = EDOM;
178 else
179 errno = 0;
180 }
181 else if (Py_IS_INFINITY(r)) {
182 if (Py_IS_FINITE(x))
183 errno = can_overflow ? ERANGE : EDOM;
184 else
185 errno = 0;
186 }
187 if (errno && is_error(r))
Tim Peters1d120612000-10-12 06:10:25 +0000188 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000189 else
Christian Heimes6f341092008-04-18 23:13:07 +0000190 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000191}
192
Christian Heimes6f341092008-04-18 23:13:07 +0000193/*
194 math_2 is used to wrap a libm function f that takes two double
195 arguments and returns a double.
196
197 The error reporting follows these rules, which are designed to do
198 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
199 platforms.
200
201 - a NaN result from non-NaN inputs causes ValueError to be raised
202 - an infinite result from finite inputs causes OverflowError to be
203 raised.
204 - if the result is finite and errno == EDOM then ValueError is
205 raised
206 - if the result is finite and nonzero and errno == ERANGE then
207 OverflowError is raised
208
209 The last rule is used to catch overflow on platforms which follow
210 C89 but for which HUGE_VAL is not an infinity.
211
212 For most two-argument functions (copysign, fmod, hypot, atan2)
213 these rules are enough to ensure that Python's functions behave as
214 specified in 'Annex F' of the C99 standard, with the 'invalid' and
215 'divide-by-zero' floating-point exceptions mapping to Python's
216 ValueError and the 'overflow' floating-point exception mapping to
217 OverflowError.
218*/
219
Barry Warsaw8b43b191996-12-09 22:32:36 +0000220static PyObject *
Neal Norwitz45e230a2006-11-19 21:26:53 +0000221math_2(PyObject *args, double (*func) (double, double), char *funcname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000222{
Neal Norwitz45e230a2006-11-19 21:26:53 +0000223 PyObject *ox, *oy;
Christian Heimes6f341092008-04-18 23:13:07 +0000224 double x, y, r;
Neal Norwitz45e230a2006-11-19 21:26:53 +0000225 if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy))
226 return NULL;
227 x = PyFloat_AsDouble(ox);
228 y = PyFloat_AsDouble(oy);
229 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000230 return NULL;
231 errno = 0;
Christian Heimes6f341092008-04-18 23:13:07 +0000232 PyFPE_START_PROTECT("in math_2", return 0);
233 r = (*func)(x, y);
234 PyFPE_END_PROTECT(r);
235 if (Py_IS_NAN(r)) {
236 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
237 errno = EDOM;
238 else
239 errno = 0;
240 }
241 else if (Py_IS_INFINITY(r)) {
242 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
243 errno = ERANGE;
244 else
245 errno = 0;
246 }
247 if (errno && is_error(r))
Tim Peters1d120612000-10-12 06:10:25 +0000248 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000249 else
Christian Heimes6f341092008-04-18 23:13:07 +0000250 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000251}
252
Christian Heimes6f341092008-04-18 23:13:07 +0000253#define FUNC1(funcname, func, can_overflow, docstring) \
Fred Drake40c48682000-07-03 18:11:56 +0000254 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
Christian Heimes6f341092008-04-18 23:13:07 +0000255 return math_1(args, func, can_overflow); \
Guido van Rossumc6e22901998-12-04 19:26:43 +0000256 }\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000257 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000258
Fred Drake40c48682000-07-03 18:11:56 +0000259#define FUNC2(funcname, func, docstring) \
260 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
Neal Norwitz45e230a2006-11-19 21:26:53 +0000261 return math_2(args, func, #funcname); \
Guido van Rossumc6e22901998-12-04 19:26:43 +0000262 }\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000263 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000264
Christian Heimes6f341092008-04-18 23:13:07 +0000265FUNC1(acos, acos, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000266 "acos(x)\n\nReturn the arc cosine (measured in radians) of x.")
Christian Heimes6f341092008-04-18 23:13:07 +0000267FUNC1(acosh, acosh, 0,
268 "acosh(x)\n\nReturn the hyperbolic arc cosine (measured in radians) of x.")
269FUNC1(asin, asin, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000270 "asin(x)\n\nReturn the arc sine (measured in radians) of x.")
Christian Heimes6f341092008-04-18 23:13:07 +0000271FUNC1(asinh, asinh, 0,
272 "asinh(x)\n\nReturn the hyperbolic arc sine (measured in radians) of x.")
273FUNC1(atan, atan, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000274 "atan(x)\n\nReturn the arc tangent (measured in radians) of x.")
Mark Dickinson92483cd2008-04-20 21:39:04 +0000275FUNC2(atan2, m_atan2,
Tim Petersfe71f812001-08-07 22:10:00 +0000276 "atan2(y, x)\n\nReturn the arc tangent (measured in radians) of y/x.\n"
277 "Unlike atan(y/x), the signs of both x and y are considered.")
Christian Heimes6f341092008-04-18 23:13:07 +0000278FUNC1(atanh, atanh, 0,
279 "atanh(x)\n\nReturn the hyperbolic arc tangent (measured in radians) of x.")
280FUNC1(ceil, ceil, 0,
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +0000281 "ceil(x)\n\nReturn the ceiling of x as a float.\n"
282 "This is the smallest integral value >= x.")
Christian Heimeseebb79c2008-01-03 22:32:26 +0000283FUNC2(copysign, copysign,
Christian Heimes6f341092008-04-18 23:13:07 +0000284 "copysign(x,y)\n\nReturn x with the sign of y.")
285FUNC1(cos, cos, 0,
286 "cos(x)\n\nReturn the cosine of x (measured in radians).")
287FUNC1(cosh, cosh, 1,
288 "cosh(x)\n\nReturn the hyperbolic cosine of x.")
289FUNC1(exp, exp, 1,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000290 "exp(x)\n\nReturn e raised to the power of x.")
Christian Heimes6f341092008-04-18 23:13:07 +0000291FUNC1(fabs, fabs, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000292 "fabs(x)\n\nReturn the absolute value of the float x.")
Christian Heimes6f341092008-04-18 23:13:07 +0000293FUNC1(floor, floor, 0,
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +0000294 "floor(x)\n\nReturn the floor of x as a float.\n"
295 "This is the largest integral value <= x.")
Christian Heimes6f341092008-04-18 23:13:07 +0000296FUNC1(log1p, log1p, 1,
297 "log1p(x)\n\nReturn the natural logarithm of 1+x (base e).\n\
298 The result is computed in a way which is accurate for x near zero.")
299FUNC1(sin, sin, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000300 "sin(x)\n\nReturn the sine of x (measured in radians).")
Christian Heimes6f341092008-04-18 23:13:07 +0000301FUNC1(sinh, sinh, 1,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000302 "sinh(x)\n\nReturn the hyperbolic sine of x.")
Christian Heimes6f341092008-04-18 23:13:07 +0000303FUNC1(sqrt, sqrt, 0,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000304 "sqrt(x)\n\nReturn the square root of x.")
Christian Heimes6f341092008-04-18 23:13:07 +0000305FUNC1(tan, tan, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000306 "tan(x)\n\nReturn the tangent of x (measured in radians).")
Christian Heimes6f341092008-04-18 23:13:07 +0000307FUNC1(tanh, tanh, 0,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000308 "tanh(x)\n\nReturn the hyperbolic tangent of x.")
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000309
Mark Dickinson99dfe922008-05-23 01:35:30 +0000310/* Precision summation function as msum() by Raymond Hettinger in
311 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
312 enhanced with the exact partials sum and roundoff from Mark
313 Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000314 See those links for more details, proofs and other references.
Mark Dickinson99dfe922008-05-23 01:35:30 +0000315
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000316 Note 1: IEEE 754R floating point semantics are assumed,
317 but the current implementation does not re-establish special
318 value semantics across iterations (i.e. handling -Inf + Inf).
Mark Dickinson99dfe922008-05-23 01:35:30 +0000319
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000320 Note 2: No provision is made for intermediate overflow handling;
Raymond Hettinger2a9179a2008-05-29 08:38:23 +0000321 therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000322 sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
323 overflow of the first partial sum.
Mark Dickinson99dfe922008-05-23 01:35:30 +0000324
Raymond Hettingeref712d62008-05-30 18:20:50 +0000325 Note 3: The itermediate values lo, yr, and hi are declared volatile so
326 aggressive compilers won't algebraicly reduce lo to always be exactly 0.0.
327 Also, the volatile declaration forces the values to be stored in memory as
328 regular doubles instead of extended long precision (80-bit) values. This
329 prevents double rounding because any addition or substraction of two doubles
330 can be resolved exactly into double-sized hi and lo values. As long as the
331 hi value gets forced into a double before yr and lo are computed, the extra
332 bits in downstream extended precision operations (x87 for example) will be
333 exactly zero and therefore can be losslessly stored back into a double,
334 thereby preventing double rounding.
Mark Dickinson99dfe922008-05-23 01:35:30 +0000335
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000336 Note 4: A similar implementation is in Modules/cmathmodule.c.
337 Be sure to update both when making changes.
Mark Dickinson99dfe922008-05-23 01:35:30 +0000338
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000339 Note 5: The signature of math.sum() differs from __builtin__.sum()
340 because the start argument doesn't make sense in the context of
341 accurate summation. Since the partials table is collapsed before
342 returning a result, sum(seq2, start=sum(seq1)) may not equal the
343 accurate result returned by sum(itertools.chain(seq1, seq2)).
Mark Dickinson99dfe922008-05-23 01:35:30 +0000344*/
345
346#define NUM_PARTIALS 32 /* initial partials array size, on stack */
347
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000348/* Extend the partials array p[] by doubling its size. */
349static int /* non-zero on error */
Mark Dickinson99dfe922008-05-23 01:35:30 +0000350_sum_realloc(double **p_ptr, Py_ssize_t n,
351 double *ps, Py_ssize_t *m_ptr)
352{
353 void *v = NULL;
354 Py_ssize_t m = *m_ptr;
355
356 m += m; /* double */
357 if (n < m && m < (PY_SSIZE_T_MAX / sizeof(double))) {
358 double *p = *p_ptr;
359 if (p == ps) {
360 v = PyMem_Malloc(sizeof(double) * m);
361 if (v != NULL)
362 memcpy(v, ps, sizeof(double) * n);
363 }
364 else
365 v = PyMem_Realloc(p, sizeof(double) * m);
366 }
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000367 if (v == NULL) { /* size overflow or no memory */
Mark Dickinson99dfe922008-05-23 01:35:30 +0000368 PyErr_SetString(PyExc_MemoryError, "math sum partials");
369 return 1;
370 }
371 *p_ptr = (double*) v;
372 *m_ptr = m;
373 return 0;
374}
375
376/* Full precision summation of a sequence of floats.
377
378 def msum(iterable):
379 partials = [] # sorted, non-overlapping partial sums
380 for x in iterable:
381 i = 0
382 for y in partials:
383 if abs(x) < abs(y):
384 x, y = y, x
385 hi = x + y
386 lo = y - (hi - x)
387 if lo:
388 partials[i] = lo
389 i += 1
390 x = hi
391 partials[i:] = [x]
392 return sum_exact(partials)
393
394 Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
395 are exactly equal to x+y. The inner loop applies hi/lo summation to each
396 partial so that the list of partial sums remains exact.
397
398 Sum_exact() adds the partial sums exactly and correctly rounds the final
399 result (using the round-half-to-even rule). The items in partials remain
400 non-zero, non-special, non-overlapping and strictly increasing in
401 magnitude, but possibly not all having the same sign.
402
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000403 Depends on IEEE 754 arithmetic guarantees and half-even rounding.
404*/
405
Mark Dickinson99dfe922008-05-23 01:35:30 +0000406static PyObject*
407math_sum(PyObject *self, PyObject *seq)
408{
409 PyObject *item, *iter, *sum = NULL;
410 Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
Raymond Hettingeref712d62008-05-30 18:20:50 +0000411 double x, y, t, ps[NUM_PARTIALS], *p = ps;
412 volatile double hi, yr, lo;
Mark Dickinson99dfe922008-05-23 01:35:30 +0000413
414 iter = PyObject_GetIter(seq);
415 if (iter == NULL)
416 return NULL;
417
418 PyFPE_START_PROTECT("sum", Py_DECREF(iter); return NULL)
419
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000420 for(;;) { /* for x in iterable */
Mark Dickinson99dfe922008-05-23 01:35:30 +0000421 assert(0 <= n && n <= m);
422 assert((m == NUM_PARTIALS && p == ps) ||
423 (m > NUM_PARTIALS && p != NULL));
424
425 item = PyIter_Next(iter);
426 if (item == NULL) {
427 if (PyErr_Occurred())
428 goto _sum_error;
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000429 break;
Mark Dickinson99dfe922008-05-23 01:35:30 +0000430 }
431 x = PyFloat_AsDouble(item);
432 Py_DECREF(item);
433 if (PyErr_Occurred())
434 goto _sum_error;
435
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000436 for (i = j = 0; j < n; j++) { /* for y in partials */
Mark Dickinson99dfe922008-05-23 01:35:30 +0000437 y = p[j];
Raymond Hettingeref712d62008-05-30 18:20:50 +0000438 if (fabs(x) < fabs(y)) {
439 t = x; x = y; y = t;
440 }
Mark Dickinson99dfe922008-05-23 01:35:30 +0000441 hi = x + y;
Raymond Hettingeref712d62008-05-30 18:20:50 +0000442 yr = hi - x;
443 lo = y - yr;
Mark Dickinson99dfe922008-05-23 01:35:30 +0000444 if (lo != 0.0)
445 p[i++] = lo;
446 x = hi;
447 }
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000448
449 n = i; /* ps[i:] = [x] */
Mark Dickinson99dfe922008-05-23 01:35:30 +0000450 if (x != 0.0) {
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000451 /* If non-finite, reset partials, effectively
Mark Dickinson99dfe922008-05-23 01:35:30 +0000452 adding subsequent items without roundoff
453 and yielding correct non-finite results,
454 provided IEEE 754 rules are observed */
455 if (! Py_IS_FINITE(x))
456 n = 0;
457 else if (n >= m && _sum_realloc(&p, n, ps, &m))
458 goto _sum_error;
459 p[n++] = x;
460 }
461 }
Mark Dickinson99dfe922008-05-23 01:35:30 +0000462
Raymond Hettingeref712d62008-05-30 18:20:50 +0000463 hi = 0.0;
Mark Dickinson99dfe922008-05-23 01:35:30 +0000464 if (n > 0) {
465 hi = p[--n];
466 if (Py_IS_FINITE(hi)) {
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000467 /* sum_exact(ps, hi) from the top, stop when the sum becomes inexact. */
Mark Dickinson99dfe922008-05-23 01:35:30 +0000468 while (n > 0) {
Raymond Hettingeref712d62008-05-30 18:20:50 +0000469 x = hi;
470 y = p[--n];
471 assert(fabs(y) < fabs(x));
Mark Dickinson99dfe922008-05-23 01:35:30 +0000472 hi = x + y;
Raymond Hettingeref712d62008-05-30 18:20:50 +0000473 yr = hi - x;
474 lo = y - yr;
Mark Dickinson99dfe922008-05-23 01:35:30 +0000475 if (lo != 0.0)
476 break;
477 }
Raymond Hettingeref712d62008-05-30 18:20:50 +0000478 /* Make half-even rounding work across multiple partials. Needed
479 so that sum([1e-16, 1, 1e16]) will round-up the last digit to
480 two instead of down to zero (the 1e-16 makes the 1 slightly
481 closer to two). With a potential 1 ULP rounding error fixed-up,
482 math.sum() can guarantee commutativity. */
Mark Dickinson99dfe922008-05-23 01:35:30 +0000483 if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
484 (lo > 0.0 && p[n-1] > 0.0))) {
485 y = lo * 2.0;
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000486 x = hi + y;
Raymond Hettingeref712d62008-05-30 18:20:50 +0000487 yr = x - hi;
488 if (y == yr)
Mark Dickinson99dfe922008-05-23 01:35:30 +0000489 hi = x;
490 }
491 }
Raymond Hettingeref712d62008-05-30 18:20:50 +0000492 else { /* raise exception corresponding to a special value */
Mark Dickinson99dfe922008-05-23 01:35:30 +0000493 errno = Py_IS_NAN(hi) ? EDOM : ERANGE;
494 if (is_error(hi))
495 goto _sum_error;
496 }
497 }
Mark Dickinson99dfe922008-05-23 01:35:30 +0000498 sum = PyFloat_FromDouble(hi);
499
500_sum_error:
501 PyFPE_END_PROTECT(hi)
Mark Dickinson99dfe922008-05-23 01:35:30 +0000502 Py_DECREF(iter);
503 if (p != ps)
504 PyMem_Free(p);
505 return sum;
506}
507
508#undef NUM_PARTIALS
509
510PyDoc_STRVAR(math_sum_doc,
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000511"sum(iterable)\n\n\
512Return an accurate floating point sum of values in the iterable.\n\
513Assumes IEEE-754 floating point arithmetic.");
Mark Dickinson99dfe922008-05-23 01:35:30 +0000514
Raymond Hettingerecbdd2e2008-06-09 06:54:45 +0000515
516static PyObject *
517math_factorial(PyObject *self, PyObject *arg)
518{
519 long i, x;
520 PyObject *result, *iobj, *newresult;
521
522 if (PyFloat_Check(arg)) {
523 double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
524 if (dx != floor(dx)) {
525 PyErr_SetString(PyExc_ValueError,
526 "factorial() only accepts integral values");
527 return NULL;
528 }
529 }
530
531 x = PyInt_AsLong(arg);
532 if (x == -1 && PyErr_Occurred())
533 return NULL;
534 if (x < 0) {
535 PyErr_SetString(PyExc_ValueError,
536 "factorial() not defined for negative values");
537 return NULL;
538 }
539
540 result = (PyObject *)PyInt_FromLong(1);
541 if (result == NULL)
542 return NULL;
543 for (i=1 ; i<=x ; i++) {
544 iobj = (PyObject *)PyInt_FromLong(i);
545 if (iobj == NULL)
546 goto error;
547 newresult = PyNumber_Multiply(result, iobj);
548 Py_DECREF(iobj);
549 if (newresult == NULL)
550 goto error;
551 Py_DECREF(result);
552 result = newresult;
553 }
554 return result;
555
556error:
557 Py_DECREF(result);
558 Py_XDECREF(iobj);
559 return NULL;
560}
561
562PyDoc_STRVAR(math_factorial_doc, "Return n!");
563
Barry Warsaw8b43b191996-12-09 22:32:36 +0000564static PyObject *
Jeffrey Yasskinca2b69f2008-02-01 06:22:46 +0000565math_trunc(PyObject *self, PyObject *number)
566{
Jeffrey Yasskinca2b69f2008-02-01 06:22:46 +0000567 return PyObject_CallMethod(number, "__trunc__", NULL);
568}
569
570PyDoc_STRVAR(math_trunc_doc,
571"trunc(x:Real) -> Integral\n"
572"\n"
Raymond Hettingerfe424f72008-02-02 05:24:44 +0000573"Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.");
Jeffrey Yasskinca2b69f2008-02-01 06:22:46 +0000574
575static PyObject *
Neal Norwitz45e230a2006-11-19 21:26:53 +0000576math_frexp(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +0000577{
Guido van Rossumd18ad581991-10-24 14:57:21 +0000578 int i;
Neal Norwitz45e230a2006-11-19 21:26:53 +0000579 double x = PyFloat_AsDouble(arg);
580 if (x == -1.0 && PyErr_Occurred())
Guido van Rossumd18ad581991-10-24 14:57:21 +0000581 return NULL;
Christian Heimes6f341092008-04-18 23:13:07 +0000582 /* deal with special cases directly, to sidestep platform
583 differences */
584 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
585 i = 0;
586 }
587 else {
588 PyFPE_START_PROTECT("in math_frexp", return 0);
589 x = frexp(x, &i);
590 PyFPE_END_PROTECT(x);
591 }
592 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +0000593}
594
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000595PyDoc_STRVAR(math_frexp_doc,
Tim Peters63c94532001-09-04 23:17:42 +0000596"frexp(x)\n"
597"\n"
598"Return the mantissa and exponent of x, as pair (m, e).\n"
599"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 +0000600"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 +0000601
Barry Warsaw8b43b191996-12-09 22:32:36 +0000602static PyObject *
Fred Drake40c48682000-07-03 18:11:56 +0000603math_ldexp(PyObject *self, PyObject *args)
Guido van Rossumd18ad581991-10-24 14:57:21 +0000604{
Christian Heimes6f341092008-04-18 23:13:07 +0000605 double x, r;
Mark Dickinsonf8476c12008-05-09 17:54:23 +0000606 PyObject *oexp;
607 long exp;
608 if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp))
Guido van Rossumd18ad581991-10-24 14:57:21 +0000609 return NULL;
Mark Dickinsonf8476c12008-05-09 17:54:23 +0000610
611 if (PyLong_Check(oexp)) {
612 /* on overflow, replace exponent with either LONG_MAX
613 or LONG_MIN, depending on the sign. */
614 exp = PyLong_AsLong(oexp);
615 if (exp == -1 && PyErr_Occurred()) {
616 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
617 if (Py_SIZE(oexp) < 0) {
618 exp = LONG_MIN;
619 }
620 else {
621 exp = LONG_MAX;
622 }
623 PyErr_Clear();
624 }
625 else {
626 /* propagate any unexpected exception */
627 return NULL;
628 }
629 }
630 }
631 else if (PyInt_Check(oexp)) {
632 exp = PyInt_AS_LONG(oexp);
633 }
634 else {
635 PyErr_SetString(PyExc_TypeError,
636 "Expected an int or long as second argument "
637 "to ldexp.");
638 return NULL;
639 }
640
641 if (x == 0. || !Py_IS_FINITE(x)) {
642 /* NaNs, zeros and infinities are returned unchanged */
643 r = x;
Christian Heimes6f341092008-04-18 23:13:07 +0000644 errno = 0;
Mark Dickinsonf8476c12008-05-09 17:54:23 +0000645 } else if (exp > INT_MAX) {
646 /* overflow */
647 r = copysign(Py_HUGE_VAL, x);
648 errno = ERANGE;
649 } else if (exp < INT_MIN) {
650 /* underflow to +-0 */
651 r = copysign(0., x);
652 errno = 0;
653 } else {
654 errno = 0;
655 PyFPE_START_PROTECT("in math_ldexp", return 0);
656 r = ldexp(x, (int)exp);
657 PyFPE_END_PROTECT(r);
658 if (Py_IS_INFINITY(r))
659 errno = ERANGE;
660 }
661
Christian Heimes6f341092008-04-18 23:13:07 +0000662 if (errno && is_error(r))
Tim Peters1d120612000-10-12 06:10:25 +0000663 return NULL;
Mark Dickinsonf8476c12008-05-09 17:54:23 +0000664 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +0000665}
666
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000667PyDoc_STRVAR(math_ldexp_doc,
668"ldexp(x, i) -> x * (2**i)");
Guido van Rossumc6e22901998-12-04 19:26:43 +0000669
Barry Warsaw8b43b191996-12-09 22:32:36 +0000670static PyObject *
Neal Norwitz45e230a2006-11-19 21:26:53 +0000671math_modf(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +0000672{
Neal Norwitz45e230a2006-11-19 21:26:53 +0000673 double y, x = PyFloat_AsDouble(arg);
674 if (x == -1.0 && PyErr_Occurred())
Guido van Rossumd18ad581991-10-24 14:57:21 +0000675 return NULL;
Mark Dickinsonb2f70902008-04-20 01:39:24 +0000676 /* some platforms don't do the right thing for NaNs and
677 infinities, so we take care of special cases directly. */
678 if (!Py_IS_FINITE(x)) {
679 if (Py_IS_INFINITY(x))
680 return Py_BuildValue("(dd)", copysign(0., x), x);
681 else if (Py_IS_NAN(x))
682 return Py_BuildValue("(dd)", x, x);
683 }
684
Guido van Rossumd18ad581991-10-24 14:57:21 +0000685 errno = 0;
Christian Heimes6f341092008-04-18 23:13:07 +0000686 PyFPE_START_PROTECT("in math_modf", return 0);
Guido van Rossumd18ad581991-10-24 14:57:21 +0000687 x = modf(x, &y);
Christian Heimes6f341092008-04-18 23:13:07 +0000688 PyFPE_END_PROTECT(x);
689 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +0000690}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000691
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000692PyDoc_STRVAR(math_modf_doc,
Tim Peters63c94532001-09-04 23:17:42 +0000693"modf(x)\n"
694"\n"
695"Return the fractional and integer parts of x. Both results carry the sign\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000696"of x. The integer part is returned as a real.");
Guido van Rossumc6e22901998-12-04 19:26:43 +0000697
Tim Peters78526162001-09-05 00:53:45 +0000698/* A decent logarithm is easy to compute even for huge longs, but libm can't
699 do that by itself -- loghelper can. func is log or log10, and name is
700 "log" or "log10". Note that overflow isn't possible: a long can contain
701 no more than INT_MAX * SHIFT bits, so has value certainly less than
702 2**(2**64 * 2**16) == 2**2**80, and log2 of that is 2**80, which is
703 small enough to fit in an IEEE single. log and log10 are even smaller.
704*/
705
706static PyObject*
Neal Norwitz45e230a2006-11-19 21:26:53 +0000707loghelper(PyObject* arg, double (*func)(double), char *funcname)
Tim Peters78526162001-09-05 00:53:45 +0000708{
Tim Peters78526162001-09-05 00:53:45 +0000709 /* If it is long, do it ourselves. */
710 if (PyLong_Check(arg)) {
711 double x;
712 int e;
713 x = _PyLong_AsScaledDouble(arg, &e);
714 if (x <= 0.0) {
715 PyErr_SetString(PyExc_ValueError,
716 "math domain error");
717 return NULL;
718 }
Christian Heimes543cabc2008-01-25 14:54:23 +0000719 /* Value is ~= x * 2**(e*PyLong_SHIFT), so the log ~=
720 log(x) + log(2) * e * PyLong_SHIFT.
721 CAUTION: e*PyLong_SHIFT may overflow using int arithmetic,
Tim Peters78526162001-09-05 00:53:45 +0000722 so force use of double. */
Christian Heimes543cabc2008-01-25 14:54:23 +0000723 x = func(x) + (e * (double)PyLong_SHIFT) * func(2.0);
Tim Peters78526162001-09-05 00:53:45 +0000724 return PyFloat_FromDouble(x);
725 }
726
727 /* Else let libm handle it by itself. */
Christian Heimes6f341092008-04-18 23:13:07 +0000728 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +0000729}
730
731static PyObject *
732math_log(PyObject *self, PyObject *args)
733{
Raymond Hettinger866964c2002-12-14 19:51:34 +0000734 PyObject *arg;
735 PyObject *base = NULL;
736 PyObject *num, *den;
737 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +0000738
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000739 if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base))
Raymond Hettinger866964c2002-12-14 19:51:34 +0000740 return NULL;
Raymond Hettinger866964c2002-12-14 19:51:34 +0000741
Neal Norwitz45e230a2006-11-19 21:26:53 +0000742 num = loghelper(arg, log, "log");
743 if (num == NULL || base == NULL)
744 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +0000745
Neal Norwitz45e230a2006-11-19 21:26:53 +0000746 den = loghelper(base, log, "log");
Raymond Hettinger866964c2002-12-14 19:51:34 +0000747 if (den == NULL) {
748 Py_DECREF(num);
749 return NULL;
750 }
751
752 ans = PyNumber_Divide(num, den);
753 Py_DECREF(num);
754 Py_DECREF(den);
755 return ans;
Tim Peters78526162001-09-05 00:53:45 +0000756}
757
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000758PyDoc_STRVAR(math_log_doc,
Raymond Hettinger866964c2002-12-14 19:51:34 +0000759"log(x[, base]) -> the logarithm of x to the given base.\n\
760If the base not specified, returns the natural logarithm (base e) of x.");
Tim Peters78526162001-09-05 00:53:45 +0000761
762static PyObject *
Neal Norwitz45e230a2006-11-19 21:26:53 +0000763math_log10(PyObject *self, PyObject *arg)
Tim Peters78526162001-09-05 00:53:45 +0000764{
Neal Norwitz45e230a2006-11-19 21:26:53 +0000765 return loghelper(arg, log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +0000766}
767
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000768PyDoc_STRVAR(math_log10_doc,
769"log10(x) -> the base 10 logarithm of x.");
Tim Peters78526162001-09-05 00:53:45 +0000770
Christian Heimes6f341092008-04-18 23:13:07 +0000771static PyObject *
772math_fmod(PyObject *self, PyObject *args)
773{
774 PyObject *ox, *oy;
775 double r, x, y;
776 if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy))
777 return NULL;
778 x = PyFloat_AsDouble(ox);
779 y = PyFloat_AsDouble(oy);
780 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
781 return NULL;
782 /* fmod(x, +/-Inf) returns x for finite x. */
783 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
784 return PyFloat_FromDouble(x);
785 errno = 0;
786 PyFPE_START_PROTECT("in math_fmod", return 0);
787 r = fmod(x, y);
788 PyFPE_END_PROTECT(r);
789 if (Py_IS_NAN(r)) {
790 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
791 errno = EDOM;
792 else
793 errno = 0;
794 }
795 if (errno && is_error(r))
796 return NULL;
797 else
798 return PyFloat_FromDouble(r);
799}
800
801PyDoc_STRVAR(math_fmod_doc,
802"fmod(x,y)\n\nReturn fmod(x, y), according to platform C."
803" x % y may differ.");
804
805static PyObject *
806math_hypot(PyObject *self, PyObject *args)
807{
808 PyObject *ox, *oy;
809 double r, x, y;
810 if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy))
811 return NULL;
812 x = PyFloat_AsDouble(ox);
813 y = PyFloat_AsDouble(oy);
814 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
815 return NULL;
816 /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */
817 if (Py_IS_INFINITY(x))
818 return PyFloat_FromDouble(fabs(x));
819 if (Py_IS_INFINITY(y))
820 return PyFloat_FromDouble(fabs(y));
821 errno = 0;
822 PyFPE_START_PROTECT("in math_hypot", return 0);
823 r = hypot(x, y);
824 PyFPE_END_PROTECT(r);
825 if (Py_IS_NAN(r)) {
826 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
827 errno = EDOM;
828 else
829 errno = 0;
830 }
831 else if (Py_IS_INFINITY(r)) {
832 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
833 errno = ERANGE;
834 else
835 errno = 0;
836 }
837 if (errno && is_error(r))
838 return NULL;
839 else
840 return PyFloat_FromDouble(r);
841}
842
843PyDoc_STRVAR(math_hypot_doc,
844"hypot(x,y)\n\nReturn the Euclidean distance, sqrt(x*x + y*y).");
845
846/* pow can't use math_2, but needs its own wrapper: the problem is
847 that an infinite result can arise either as a result of overflow
848 (in which case OverflowError should be raised) or as a result of
849 e.g. 0.**-5. (for which ValueError needs to be raised.)
850*/
851
852static PyObject *
853math_pow(PyObject *self, PyObject *args)
854{
855 PyObject *ox, *oy;
856 double r, x, y;
Mark Dickinsoncec3f132008-04-20 04:13:13 +0000857 int odd_y;
Christian Heimes6f341092008-04-18 23:13:07 +0000858
859 if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy))
860 return NULL;
861 x = PyFloat_AsDouble(ox);
862 y = PyFloat_AsDouble(oy);
863 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
864 return NULL;
Mark Dickinsona1293eb2008-04-19 19:41:52 +0000865
Mark Dickinsoncec3f132008-04-20 04:13:13 +0000866 /* deal directly with IEEE specials, to cope with problems on various
867 platforms whose semantics don't exactly match C99 */
Mark Dickinson0da94c82008-04-21 01:55:50 +0000868 r = 0.; /* silence compiler warning */
Mark Dickinsoncec3f132008-04-20 04:13:13 +0000869 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
870 errno = 0;
871 if (Py_IS_NAN(x))
872 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
873 else if (Py_IS_NAN(y))
874 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
875 else if (Py_IS_INFINITY(x)) {
876 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
877 if (y > 0.)
878 r = odd_y ? x : fabs(x);
879 else if (y == 0.)
880 r = 1.;
881 else /* y < 0. */
882 r = odd_y ? copysign(0., x) : 0.;
883 }
884 else if (Py_IS_INFINITY(y)) {
885 if (fabs(x) == 1.0)
886 r = 1.;
887 else if (y > 0. && fabs(x) > 1.0)
888 r = y;
889 else if (y < 0. && fabs(x) < 1.0) {
890 r = -y; /* result is +inf */
891 if (x == 0.) /* 0**-inf: divide-by-zero */
892 errno = EDOM;
893 }
894 else
895 r = 0.;
896 }
Mark Dickinsone941d972008-04-19 18:51:48 +0000897 }
Mark Dickinsoncec3f132008-04-20 04:13:13 +0000898 else {
899 /* let libm handle finite**finite */
900 errno = 0;
901 PyFPE_START_PROTECT("in math_pow", return 0);
902 r = pow(x, y);
903 PyFPE_END_PROTECT(r);
904 /* a NaN result should arise only from (-ve)**(finite
905 non-integer); in this case we want to raise ValueError. */
906 if (!Py_IS_FINITE(r)) {
907 if (Py_IS_NAN(r)) {
908 errno = EDOM;
909 }
910 /*
911 an infinite result here arises either from:
912 (A) (+/-0.)**negative (-> divide-by-zero)
913 (B) overflow of x**y with x and y finite
914 */
915 else if (Py_IS_INFINITY(r)) {
916 if (x == 0.)
917 errno = EDOM;
918 else
919 errno = ERANGE;
920 }
921 }
Christian Heimes6f341092008-04-18 23:13:07 +0000922 }
923
924 if (errno && is_error(r))
925 return NULL;
926 else
927 return PyFloat_FromDouble(r);
928}
929
930PyDoc_STRVAR(math_pow_doc,
931"pow(x,y)\n\nReturn x**y (x to the power of y).");
932
Christian Heimese2ca4242008-01-03 20:23:15 +0000933static const double degToRad = Py_MATH_PI / 180.0;
934static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +0000935
936static PyObject *
Neal Norwitz45e230a2006-11-19 21:26:53 +0000937math_degrees(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +0000938{
Neal Norwitz45e230a2006-11-19 21:26:53 +0000939 double x = PyFloat_AsDouble(arg);
940 if (x == -1.0 && PyErr_Occurred())
Raymond Hettingerd6f22672002-05-13 03:56:10 +0000941 return NULL;
Christian Heimese2ca4242008-01-03 20:23:15 +0000942 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +0000943}
944
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000945PyDoc_STRVAR(math_degrees_doc,
946"degrees(x) -> converts angle x from radians to degrees");
Raymond Hettingerd6f22672002-05-13 03:56:10 +0000947
948static PyObject *
Neal Norwitz45e230a2006-11-19 21:26:53 +0000949math_radians(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +0000950{
Neal Norwitz45e230a2006-11-19 21:26:53 +0000951 double x = PyFloat_AsDouble(arg);
952 if (x == -1.0 && PyErr_Occurred())
Raymond Hettingerd6f22672002-05-13 03:56:10 +0000953 return NULL;
954 return PyFloat_FromDouble(x * degToRad);
955}
956
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000957PyDoc_STRVAR(math_radians_doc,
958"radians(x) -> converts angle x from degrees to radians");
Tim Peters78526162001-09-05 00:53:45 +0000959
Christian Heimese2ca4242008-01-03 20:23:15 +0000960static PyObject *
961math_isnan(PyObject *self, PyObject *arg)
962{
963 double x = PyFloat_AsDouble(arg);
964 if (x == -1.0 && PyErr_Occurred())
965 return NULL;
966 return PyBool_FromLong((long)Py_IS_NAN(x));
967}
968
969PyDoc_STRVAR(math_isnan_doc,
970"isnan(x) -> bool\n\
971Checks if float x is not a number (NaN)");
972
973static PyObject *
974math_isinf(PyObject *self, PyObject *arg)
975{
976 double x = PyFloat_AsDouble(arg);
977 if (x == -1.0 && PyErr_Occurred())
978 return NULL;
979 return PyBool_FromLong((long)Py_IS_INFINITY(x));
980}
981
982PyDoc_STRVAR(math_isinf_doc,
983"isinf(x) -> bool\n\
984Checks if float x is infinite (positive or negative)");
985
Barry Warsaw8b43b191996-12-09 22:32:36 +0000986static PyMethodDef math_methods[] = {
Neal Norwitz45e230a2006-11-19 21:26:53 +0000987 {"acos", math_acos, METH_O, math_acos_doc},
Christian Heimes6f341092008-04-18 23:13:07 +0000988 {"acosh", math_acosh, METH_O, math_acosh_doc},
Neal Norwitz45e230a2006-11-19 21:26:53 +0000989 {"asin", math_asin, METH_O, math_asin_doc},
Christian Heimes6f341092008-04-18 23:13:07 +0000990 {"asinh", math_asinh, METH_O, math_asinh_doc},
Neal Norwitz45e230a2006-11-19 21:26:53 +0000991 {"atan", math_atan, METH_O, math_atan_doc},
Fred Drake40c48682000-07-03 18:11:56 +0000992 {"atan2", math_atan2, METH_VARARGS, math_atan2_doc},
Christian Heimes6f341092008-04-18 23:13:07 +0000993 {"atanh", math_atanh, METH_O, math_atanh_doc},
Neal Norwitz45e230a2006-11-19 21:26:53 +0000994 {"ceil", math_ceil, METH_O, math_ceil_doc},
Christian Heimeseebb79c2008-01-03 22:32:26 +0000995 {"copysign", math_copysign, METH_VARARGS, math_copysign_doc},
Neal Norwitz45e230a2006-11-19 21:26:53 +0000996 {"cos", math_cos, METH_O, math_cos_doc},
997 {"cosh", math_cosh, METH_O, math_cosh_doc},
998 {"degrees", math_degrees, METH_O, math_degrees_doc},
999 {"exp", math_exp, METH_O, math_exp_doc},
1000 {"fabs", math_fabs, METH_O, math_fabs_doc},
Raymond Hettingerecbdd2e2008-06-09 06:54:45 +00001001 {"factorial", math_factorial, METH_O, math_factorial_doc},
Neal Norwitz45e230a2006-11-19 21:26:53 +00001002 {"floor", math_floor, METH_O, math_floor_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001003 {"fmod", math_fmod, METH_VARARGS, math_fmod_doc},
Neal Norwitz45e230a2006-11-19 21:26:53 +00001004 {"frexp", math_frexp, METH_O, math_frexp_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001005 {"hypot", math_hypot, METH_VARARGS, math_hypot_doc},
Christian Heimese2ca4242008-01-03 20:23:15 +00001006 {"isinf", math_isinf, METH_O, math_isinf_doc},
1007 {"isnan", math_isnan, METH_O, math_isnan_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001008 {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc},
1009 {"log", math_log, METH_VARARGS, math_log_doc},
Christian Heimes6f341092008-04-18 23:13:07 +00001010 {"log1p", math_log1p, METH_O, math_log1p_doc},
Neal Norwitz45e230a2006-11-19 21:26:53 +00001011 {"log10", math_log10, METH_O, math_log10_doc},
1012 {"modf", math_modf, METH_O, math_modf_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001013 {"pow", math_pow, METH_VARARGS, math_pow_doc},
Neal Norwitz45e230a2006-11-19 21:26:53 +00001014 {"radians", math_radians, METH_O, math_radians_doc},
1015 {"sin", math_sin, METH_O, math_sin_doc},
1016 {"sinh", math_sinh, METH_O, math_sinh_doc},
1017 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
Mark Dickinson99dfe922008-05-23 01:35:30 +00001018 {"sum", math_sum, METH_O, math_sum_doc},
Neal Norwitz45e230a2006-11-19 21:26:53 +00001019 {"tan", math_tan, METH_O, math_tan_doc},
1020 {"tanh", math_tanh, METH_O, math_tanh_doc},
Jeffrey Yasskinca2b69f2008-02-01 06:22:46 +00001021 {"trunc", math_trunc, METH_O, math_trunc_doc},
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001022 {NULL, NULL} /* sentinel */
1023};
1024
Guido van Rossumc6e22901998-12-04 19:26:43 +00001025
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001026PyDoc_STRVAR(module_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001027"This module is always available. It provides access to the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001028"mathematical functions defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001029
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001030PyMODINIT_FUNC
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001031initmath(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001032{
Christian Heimes6f341092008-04-18 23:13:07 +00001033 PyObject *m;
Tim Petersfe71f812001-08-07 22:10:00 +00001034
Guido van Rossumc6e22901998-12-04 19:26:43 +00001035 m = Py_InitModule3("math", math_methods, module_doc);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00001036 if (m == NULL)
1037 goto finally;
Barry Warsawfc93f751996-12-17 00:47:03 +00001038
Christian Heimes6f341092008-04-18 23:13:07 +00001039 PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
1040 PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
Barry Warsawfc93f751996-12-17 00:47:03 +00001041
Christian Heimes6f341092008-04-18 23:13:07 +00001042 finally:
Barry Warsaw9bfd2bf2000-09-01 09:01:32 +00001043 return;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001044}