blob: a196834de4a09a874da3ec44e52ef8fe8616c15a [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
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).
Benjamin Petersonc2c5e002008-06-17 22:39:26 +000085 *
86 * On some platforms (Ubuntu/ia64) it seems that errno can be
87 * set to ERANGE for subnormal results that do *not* underflow
88 * to zero. So to be safe, we'll ignore ERANGE whenever the
89 * function result is less than one in absolute value.
Tim Peters1d120612000-10-12 06:10:25 +000090 */
Benjamin Petersonc2c5e002008-06-17 22:39:26 +000091 if (fabs(x) < 1.0)
92 result = 0;
93 else
Tim Petersfe71f812001-08-07 22:10:00 +000094 PyErr_SetString(PyExc_OverflowError,
Tim Peters1d120612000-10-12 06:10:25 +000095 "math range error");
Tim Peters1d120612000-10-12 06:10:25 +000096 }
Guido van Rossum8832b621991-12-16 15:44:24 +000097 else
Barry Warsaw8b43b191996-12-09 22:32:36 +000098 /* Unexpected math error */
99 PyErr_SetFromErrno(PyExc_ValueError);
Tim Peters1d120612000-10-12 06:10:25 +0000100 return result;
Guido van Rossum8832b621991-12-16 15:44:24 +0000101}
102
Christian Heimes53876d92008-04-19 00:31:39 +0000103/*
Christian Heimese57950f2008-04-21 13:08:03 +0000104 wrapper for atan2 that deals directly with special cases before
105 delegating to the platform libm for the remaining cases. This
106 is necessary to get consistent behaviour across platforms.
107 Windows, FreeBSD and alpha Tru64 are amongst platforms that don't
108 always follow C99.
109*/
110
111static double
112m_atan2(double y, double x)
113{
114 if (Py_IS_NAN(x) || Py_IS_NAN(y))
115 return Py_NAN;
116 if (Py_IS_INFINITY(y)) {
117 if (Py_IS_INFINITY(x)) {
118 if (copysign(1., x) == 1.)
119 /* atan2(+-inf, +inf) == +-pi/4 */
120 return copysign(0.25*Py_MATH_PI, y);
121 else
122 /* atan2(+-inf, -inf) == +-pi*3/4 */
123 return copysign(0.75*Py_MATH_PI, y);
124 }
125 /* atan2(+-inf, x) == +-pi/2 for finite x */
126 return copysign(0.5*Py_MATH_PI, y);
127 }
128 if (Py_IS_INFINITY(x) || y == 0.) {
129 if (copysign(1., x) == 1.)
130 /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */
131 return copysign(0., y);
132 else
133 /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */
134 return copysign(Py_MATH_PI, y);
135 }
136 return atan2(y, x);
137}
138
139/*
Christian Heimes53876d92008-04-19 00:31:39 +0000140 math_1 is used to wrap a libm function f that takes a double
141 arguments and returns a double.
142
143 The error reporting follows these rules, which are designed to do
144 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
145 platforms.
146
147 - a NaN result from non-NaN inputs causes ValueError to be raised
148 - an infinite result from finite inputs causes OverflowError to be
149 raised if can_overflow is 1, or raises ValueError if can_overflow
150 is 0.
151 - if the result is finite and errno == EDOM then ValueError is
152 raised
153 - if the result is finite and nonzero and errno == ERANGE then
154 OverflowError is raised
155
156 The last rule is used to catch overflow on platforms which follow
157 C89 but for which HUGE_VAL is not an infinity.
158
159 For the majority of one-argument functions these rules are enough
160 to ensure that Python's functions behave as specified in 'Annex F'
161 of the C99 standard, with the 'invalid' and 'divide-by-zero'
162 floating-point exceptions mapping to Python's ValueError and the
163 'overflow' floating-point exception mapping to OverflowError.
164 math_1 only works for functions that don't have singularities *and*
165 the possibility of overflow; fortunately, that covers everything we
166 care about right now.
167*/
168
Barry Warsaw8b43b191996-12-09 22:32:36 +0000169static PyObject *
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000170math_1_to_whatever(PyObject *arg, double (*func) (double),
Christian Heimes53876d92008-04-19 00:31:39 +0000171 PyObject *(*from_double_func) (double),
172 int can_overflow)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000173{
Christian Heimes53876d92008-04-19 00:31:39 +0000174 double x, r;
175 x = PyFloat_AsDouble(arg);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000176 if (x == -1.0 && PyErr_Occurred())
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000177 return NULL;
178 errno = 0;
Christian Heimes53876d92008-04-19 00:31:39 +0000179 PyFPE_START_PROTECT("in math_1", return 0);
180 r = (*func)(x);
181 PyFPE_END_PROTECT(r);
Mark Dickinsona0de26c2008-04-30 23:30:57 +0000182 if (Py_IS_NAN(r) && !Py_IS_NAN(x)) {
183 PyErr_SetString(PyExc_ValueError,
Mark Dickinson66bada52008-06-18 10:04:31 +0000184 "math domain error"); /* invalid arg */
Mark Dickinsona0de26c2008-04-30 23:30:57 +0000185 return NULL;
Christian Heimes53876d92008-04-19 00:31:39 +0000186 }
Mark Dickinsona0de26c2008-04-30 23:30:57 +0000187 if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) {
188 if (can_overflow)
189 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson66bada52008-06-18 10:04:31 +0000190 "math range error"); /* overflow */
Mark Dickinsonb63aff12008-05-09 14:10:27 +0000191 else
192 PyErr_SetString(PyExc_ValueError,
Mark Dickinson66bada52008-06-18 10:04:31 +0000193 "math domain error"); /* singularity */
Mark Dickinsona0de26c2008-04-30 23:30:57 +0000194 return NULL;
Christian Heimes53876d92008-04-19 00:31:39 +0000195 }
Mark Dickinsonde429622008-05-01 00:19:23 +0000196 if (Py_IS_FINITE(r) && errno && is_error(r))
197 /* this branch unnecessary on most platforms */
Tim Peters1d120612000-10-12 06:10:25 +0000198 return NULL;
Mark Dickinsonde429622008-05-01 00:19:23 +0000199
200 return (*from_double_func)(r);
Christian Heimes53876d92008-04-19 00:31:39 +0000201}
202
203/*
204 math_2 is used to wrap a libm function f that takes two double
205 arguments and returns a double.
206
207 The error reporting follows these rules, which are designed to do
208 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
209 platforms.
210
211 - a NaN result from non-NaN inputs causes ValueError to be raised
212 - an infinite result from finite inputs causes OverflowError to be
213 raised.
214 - if the result is finite and errno == EDOM then ValueError is
215 raised
216 - if the result is finite and nonzero and errno == ERANGE then
217 OverflowError is raised
218
219 The last rule is used to catch overflow on platforms which follow
220 C89 but for which HUGE_VAL is not an infinity.
221
222 For most two-argument functions (copysign, fmod, hypot, atan2)
223 these rules are enough to ensure that Python's functions behave as
224 specified in 'Annex F' of the C99 standard, with the 'invalid' and
225 'divide-by-zero' floating-point exceptions mapping to Python's
226 ValueError and the 'overflow' floating-point exception mapping to
227 OverflowError.
228*/
229
230static PyObject *
231math_1(PyObject *arg, double (*func) (double), int can_overflow)
232{
233 return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow);
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000234}
235
236static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000237math_1_to_int(PyObject *arg, double (*func) (double), int can_overflow)
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000238{
Christian Heimes53876d92008-04-19 00:31:39 +0000239 return math_1_to_whatever(arg, func, PyLong_FromDouble, can_overflow);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000240}
241
Barry Warsaw8b43b191996-12-09 22:32:36 +0000242static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +0000243math_2(PyObject *args, double (*func) (double, double), char *funcname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000244{
Thomas Wouters89f507f2006-12-13 04:49:30 +0000245 PyObject *ox, *oy;
Christian Heimes53876d92008-04-19 00:31:39 +0000246 double x, y, r;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000247 if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy))
248 return NULL;
249 x = PyFloat_AsDouble(ox);
250 y = PyFloat_AsDouble(oy);
251 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000252 return NULL;
253 errno = 0;
Christian Heimes53876d92008-04-19 00:31:39 +0000254 PyFPE_START_PROTECT("in math_2", return 0);
255 r = (*func)(x, y);
256 PyFPE_END_PROTECT(r);
257 if (Py_IS_NAN(r)) {
258 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
259 errno = EDOM;
260 else
261 errno = 0;
262 }
263 else if (Py_IS_INFINITY(r)) {
264 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
265 errno = ERANGE;
266 else
267 errno = 0;
268 }
269 if (errno && is_error(r))
Tim Peters1d120612000-10-12 06:10:25 +0000270 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000271 else
Christian Heimes53876d92008-04-19 00:31:39 +0000272 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000273}
274
Christian Heimes53876d92008-04-19 00:31:39 +0000275#define FUNC1(funcname, func, can_overflow, docstring) \
Fred Drake40c48682000-07-03 18:11:56 +0000276 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
Christian Heimes53876d92008-04-19 00:31:39 +0000277 return math_1(args, func, can_overflow); \
Guido van Rossumc6e22901998-12-04 19:26:43 +0000278 }\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000279 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000280
Fred Drake40c48682000-07-03 18:11:56 +0000281#define FUNC2(funcname, func, docstring) \
282 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
Thomas Wouters89f507f2006-12-13 04:49:30 +0000283 return math_2(args, func, #funcname); \
Guido van Rossumc6e22901998-12-04 19:26:43 +0000284 }\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000285 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000286
Christian Heimes53876d92008-04-19 00:31:39 +0000287FUNC1(acos, acos, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000288 "acos(x)\n\nReturn the arc cosine (measured in radians) of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000289FUNC1(acosh, acosh, 0,
290 "acosh(x)\n\nReturn the hyperbolic arc cosine (measured in radians) of x.")
291FUNC1(asin, asin, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000292 "asin(x)\n\nReturn the arc sine (measured in radians) of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000293FUNC1(asinh, asinh, 0,
294 "asinh(x)\n\nReturn the hyperbolic arc sine (measured in radians) of x.")
295FUNC1(atan, atan, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000296 "atan(x)\n\nReturn the arc tangent (measured in radians) of x.")
Christian Heimese57950f2008-04-21 13:08:03 +0000297FUNC2(atan2, m_atan2,
Tim Petersfe71f812001-08-07 22:10:00 +0000298 "atan2(y, x)\n\nReturn the arc tangent (measured in radians) of y/x.\n"
299 "Unlike atan(y/x), the signs of both x and y are considered.")
Christian Heimes53876d92008-04-19 00:31:39 +0000300FUNC1(atanh, atanh, 0,
301 "atanh(x)\n\nReturn the hyperbolic arc tangent (measured in radians) of x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +0000302
303static PyObject * math_ceil(PyObject *self, PyObject *number) {
304 static PyObject *ceil_str = NULL;
305 PyObject *method;
306
307 if (ceil_str == NULL) {
Christian Heimesfe82e772008-01-28 02:38:20 +0000308 ceil_str = PyUnicode_InternFromString("__ceil__");
Guido van Rossum13e05de2007-08-23 22:56:55 +0000309 if (ceil_str == NULL)
310 return NULL;
311 }
312
Christian Heimes90aa7642007-12-19 02:45:37 +0000313 method = _PyType_Lookup(Py_TYPE(number), ceil_str);
Guido van Rossum13e05de2007-08-23 22:56:55 +0000314 if (method == NULL)
Christian Heimes53876d92008-04-19 00:31:39 +0000315 return math_1_to_int(number, ceil, 0);
Guido van Rossum13e05de2007-08-23 22:56:55 +0000316 else
317 return PyObject_CallFunction(method, "O", number);
318}
319
320PyDoc_STRVAR(math_ceil_doc,
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000321 "ceil(x)\n\nReturn the ceiling of x as an int.\n"
Guido van Rossum13e05de2007-08-23 22:56:55 +0000322 "This is the smallest integral value >= x.");
323
Christian Heimes072c0f12008-01-03 23:01:04 +0000324FUNC2(copysign, copysign,
Christian Heimes53876d92008-04-19 00:31:39 +0000325 "copysign(x,y)\n\nReturn x with the sign of y.")
326FUNC1(cos, cos, 0,
327 "cos(x)\n\nReturn the cosine of x (measured in radians).")
328FUNC1(cosh, cosh, 1,
329 "cosh(x)\n\nReturn the hyperbolic cosine of x.")
330FUNC1(exp, exp, 1,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000331 "exp(x)\n\nReturn e raised to the power of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000332FUNC1(fabs, fabs, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000333 "fabs(x)\n\nReturn the absolute value of the float x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +0000334
335static PyObject * math_floor(PyObject *self, PyObject *number) {
336 static PyObject *floor_str = NULL;
337 PyObject *method;
338
339 if (floor_str == NULL) {
Christian Heimesfe82e772008-01-28 02:38:20 +0000340 floor_str = PyUnicode_InternFromString("__floor__");
Guido van Rossum13e05de2007-08-23 22:56:55 +0000341 if (floor_str == NULL)
342 return NULL;
343 }
344
Christian Heimes90aa7642007-12-19 02:45:37 +0000345 method = _PyType_Lookup(Py_TYPE(number), floor_str);
Guido van Rossum13e05de2007-08-23 22:56:55 +0000346 if (method == NULL)
Christian Heimes53876d92008-04-19 00:31:39 +0000347 return math_1_to_int(number, floor, 0);
Guido van Rossum13e05de2007-08-23 22:56:55 +0000348 else
349 return PyObject_CallFunction(method, "O", number);
350}
351
352PyDoc_STRVAR(math_floor_doc,
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000353 "floor(x)\n\nReturn the floor of x as an int.\n"
Guido van Rossum13e05de2007-08-23 22:56:55 +0000354 "This is the largest integral value <= x.");
355
Christian Heimes53876d92008-04-19 00:31:39 +0000356FUNC1(log1p, log1p, 1,
357 "log1p(x)\n\nReturn the natural logarithm of 1+x (base e).\n\
358 The result is computed in a way which is accurate for x near zero.")
359FUNC1(sin, sin, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000360 "sin(x)\n\nReturn the sine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +0000361FUNC1(sinh, sinh, 1,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000362 "sinh(x)\n\nReturn the hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000363FUNC1(sqrt, sqrt, 0,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000364 "sqrt(x)\n\nReturn the square root of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000365FUNC1(tan, tan, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000366 "tan(x)\n\nReturn the tangent of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +0000367FUNC1(tanh, tanh, 0,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000368 "tanh(x)\n\nReturn the hyperbolic tangent of x.")
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000369
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000370/* Precision summation function as msum() by Raymond Hettinger in
371 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
372 enhanced with the exact partials sum and roundoff from Mark
373 Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
374 See those links for more details, proofs and other references.
375
376 Note 1: IEEE 754R floating point semantics are assumed,
377 but the current implementation does not re-establish special
378 value semantics across iterations (i.e. handling -Inf + Inf).
379
380 Note 2: No provision is made for intermediate overflow handling;
Georg Brandlf78e02b2008-06-10 17:40:04 +0000381 therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000382 sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
383 overflow of the first partial sum.
384
Benjamin Petersonfea6a942008-07-02 16:11:42 +0000385 Note 3: The intermediate values lo, yr, and hi are declared volatile so
386 aggressive compilers won't algebraically reduce lo to always be exactly 0.0.
Georg Brandlf78e02b2008-06-10 17:40:04 +0000387 Also, the volatile declaration forces the values to be stored in memory as
388 regular doubles instead of extended long precision (80-bit) values. This
Benjamin Petersonfea6a942008-07-02 16:11:42 +0000389 prevents double rounding because any addition or subtraction of two doubles
Georg Brandlf78e02b2008-06-10 17:40:04 +0000390 can be resolved exactly into double-sized hi and lo values. As long as the
391 hi value gets forced into a double before yr and lo are computed, the extra
392 bits in downstream extended precision operations (x87 for example) will be
393 exactly zero and therefore can be losslessly stored back into a double,
394 thereby preventing double rounding.
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000395
396 Note 4: A similar implementation is in Modules/cmathmodule.c.
397 Be sure to update both when making changes.
398
399 Note 5: The signature of math.sum() differs from __builtin__.sum()
400 because the start argument doesn't make sense in the context of
401 accurate summation. Since the partials table is collapsed before
402 returning a result, sum(seq2, start=sum(seq1)) may not equal the
403 accurate result returned by sum(itertools.chain(seq1, seq2)).
404*/
405
406#define NUM_PARTIALS 32 /* initial partials array size, on stack */
407
408/* Extend the partials array p[] by doubling its size. */
409static int /* non-zero on error */
410_sum_realloc(double **p_ptr, Py_ssize_t n,
411 double *ps, Py_ssize_t *m_ptr)
412{
413 void *v = NULL;
414 Py_ssize_t m = *m_ptr;
415
416 m += m; /* double */
417 if (n < m && m < (PY_SSIZE_T_MAX / sizeof(double))) {
418 double *p = *p_ptr;
419 if (p == ps) {
420 v = PyMem_Malloc(sizeof(double) * m);
421 if (v != NULL)
422 memcpy(v, ps, sizeof(double) * n);
423 }
424 else
425 v = PyMem_Realloc(p, sizeof(double) * m);
426 }
427 if (v == NULL) { /* size overflow or no memory */
428 PyErr_SetString(PyExc_MemoryError, "math sum partials");
429 return 1;
430 }
431 *p_ptr = (double*) v;
432 *m_ptr = m;
433 return 0;
434}
435
436/* Full precision summation of a sequence of floats.
437
438 def msum(iterable):
439 partials = [] # sorted, non-overlapping partial sums
440 for x in iterable:
441 i = 0
442 for y in partials:
443 if abs(x) < abs(y):
444 x, y = y, x
445 hi = x + y
446 lo = y - (hi - x)
447 if lo:
448 partials[i] = lo
449 i += 1
450 x = hi
451 partials[i:] = [x]
452 return sum_exact(partials)
453
454 Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
455 are exactly equal to x+y. The inner loop applies hi/lo summation to each
456 partial so that the list of partial sums remains exact.
457
458 Sum_exact() adds the partial sums exactly and correctly rounds the final
459 result (using the round-half-to-even rule). The items in partials remain
460 non-zero, non-special, non-overlapping and strictly increasing in
461 magnitude, but possibly not all having the same sign.
462
463 Depends on IEEE 754 arithmetic guarantees and half-even rounding.
464*/
465
466static PyObject*
467math_sum(PyObject *self, PyObject *seq)
468{
469 PyObject *item, *iter, *sum = NULL;
470 Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
Georg Brandlf78e02b2008-06-10 17:40:04 +0000471 double x, y, t, ps[NUM_PARTIALS], *p = ps;
472 volatile double hi, yr, lo;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000473
474 iter = PyObject_GetIter(seq);
475 if (iter == NULL)
476 return NULL;
477
478 PyFPE_START_PROTECT("sum", Py_DECREF(iter); return NULL)
479
480 for(;;) { /* for x in iterable */
481 assert(0 <= n && n <= m);
482 assert((m == NUM_PARTIALS && p == ps) ||
483 (m > NUM_PARTIALS && p != NULL));
484
485 item = PyIter_Next(iter);
486 if (item == NULL) {
487 if (PyErr_Occurred())
488 goto _sum_error;
489 break;
490 }
491 x = PyFloat_AsDouble(item);
492 Py_DECREF(item);
493 if (PyErr_Occurred())
494 goto _sum_error;
495
496 for (i = j = 0; j < n; j++) { /* for y in partials */
497 y = p[j];
Georg Brandlf78e02b2008-06-10 17:40:04 +0000498 if (fabs(x) < fabs(y)) {
499 t = x; x = y; y = t;
500 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000501 hi = x + y;
Georg Brandlf78e02b2008-06-10 17:40:04 +0000502 yr = hi - x;
503 lo = y - yr;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000504 if (lo != 0.0)
505 p[i++] = lo;
506 x = hi;
507 }
508
509 n = i; /* ps[i:] = [x] */
510 if (x != 0.0) {
511 /* If non-finite, reset partials, effectively
512 adding subsequent items without roundoff
513 and yielding correct non-finite results,
514 provided IEEE 754 rules are observed */
515 if (! Py_IS_FINITE(x))
516 n = 0;
517 else if (n >= m && _sum_realloc(&p, n, ps, &m))
518 goto _sum_error;
519 p[n++] = x;
520 }
521 }
522
Georg Brandlf78e02b2008-06-10 17:40:04 +0000523 hi = 0.0;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000524 if (n > 0) {
525 hi = p[--n];
526 if (Py_IS_FINITE(hi)) {
527 /* sum_exact(ps, hi) from the top, stop when the sum becomes inexact. */
528 while (n > 0) {
Georg Brandlf78e02b2008-06-10 17:40:04 +0000529 x = hi;
530 y = p[--n];
531 assert(fabs(y) < fabs(x));
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000532 hi = x + y;
Georg Brandlf78e02b2008-06-10 17:40:04 +0000533 yr = hi - x;
534 lo = y - yr;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000535 if (lo != 0.0)
536 break;
537 }
Georg Brandlf78e02b2008-06-10 17:40:04 +0000538 /* Make half-even rounding work across multiple partials. Needed
539 so that sum([1e-16, 1, 1e16]) will round-up the last digit to
540 two instead of down to zero (the 1e-16 makes the 1 slightly
541 closer to two). With a potential 1 ULP rounding error fixed-up,
542 math.sum() can guarantee commutativity. */
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000543 if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
544 (lo > 0.0 && p[n-1] > 0.0))) {
545 y = lo * 2.0;
546 x = hi + y;
Georg Brandlf78e02b2008-06-10 17:40:04 +0000547 yr = x - hi;
548 if (y == yr)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000549 hi = x;
550 }
551 }
Georg Brandlf78e02b2008-06-10 17:40:04 +0000552 else { /* raise exception corresponding to a special value */
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000553 errno = Py_IS_NAN(hi) ? EDOM : ERANGE;
554 if (is_error(hi))
555 goto _sum_error;
556 }
557 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000558 sum = PyFloat_FromDouble(hi);
559
560_sum_error:
561 PyFPE_END_PROTECT(hi)
562 Py_DECREF(iter);
563 if (p != ps)
564 PyMem_Free(p);
565 return sum;
566}
567
568#undef NUM_PARTIALS
569
570PyDoc_STRVAR(math_sum_doc,
571"sum(iterable)\n\n\
572Return an accurate floating point sum of values in the iterable.\n\
573Assumes IEEE-754 floating point arithmetic.");
574
Barry Warsaw8b43b191996-12-09 22:32:36 +0000575static PyObject *
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000576math_factorial(PyObject *self, PyObject *arg)
577{
578 long i, x;
579 PyObject *result, *iobj, *newresult;
580
581 if (PyFloat_Check(arg)) {
582 double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
583 if (dx != floor(dx)) {
584 PyErr_SetString(PyExc_ValueError,
585 "factorial() only accepts integral values");
586 return NULL;
587 }
588 }
589
590 x = PyLong_AsLong(arg);
591 if (x == -1 && PyErr_Occurred())
592 return NULL;
593 if (x < 0) {
594 PyErr_SetString(PyExc_ValueError,
595 "factorial() not defined for negative values");
596 return NULL;
597 }
598
599 result = (PyObject *)PyLong_FromLong(1);
600 if (result == NULL)
601 return NULL;
602 for (i=1 ; i<=x ; i++) {
603 iobj = (PyObject *)PyLong_FromLong(i);
604 if (iobj == NULL)
605 goto error;
606 newresult = PyNumber_Multiply(result, iobj);
607 Py_DECREF(iobj);
608 if (newresult == NULL)
609 goto error;
610 Py_DECREF(result);
611 result = newresult;
612 }
613 return result;
614
615error:
616 Py_DECREF(result);
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000617 return NULL;
618}
619
620PyDoc_STRVAR(math_factorial_doc, "Return n!");
621
622static PyObject *
Christian Heimes400adb02008-02-01 08:12:03 +0000623math_trunc(PyObject *self, PyObject *number)
624{
625 static PyObject *trunc_str = NULL;
626 PyObject *trunc;
627
628 if (Py_TYPE(number)->tp_dict == NULL) {
629 if (PyType_Ready(Py_TYPE(number)) < 0)
630 return NULL;
631 }
632
633 if (trunc_str == NULL) {
634 trunc_str = PyUnicode_InternFromString("__trunc__");
635 if (trunc_str == NULL)
636 return NULL;
637 }
638
639 trunc = _PyType_Lookup(Py_TYPE(number), trunc_str);
640 if (trunc == NULL) {
641 PyErr_Format(PyExc_TypeError,
642 "type %.100s doesn't define __trunc__ method",
643 Py_TYPE(number)->tp_name);
644 return NULL;
645 }
646 return PyObject_CallFunctionObjArgs(trunc, number, NULL);
647}
648
649PyDoc_STRVAR(math_trunc_doc,
650"trunc(x:Real) -> Integral\n"
651"\n"
Christian Heimes292d3512008-02-03 16:51:08 +0000652"Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.");
Christian Heimes400adb02008-02-01 08:12:03 +0000653
654static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +0000655math_frexp(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +0000656{
Guido van Rossumd18ad581991-10-24 14:57:21 +0000657 int i;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000658 double x = PyFloat_AsDouble(arg);
659 if (x == -1.0 && PyErr_Occurred())
Guido van Rossumd18ad581991-10-24 14:57:21 +0000660 return NULL;
Christian Heimes53876d92008-04-19 00:31:39 +0000661 /* deal with special cases directly, to sidestep platform
662 differences */
663 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
664 i = 0;
665 }
666 else {
667 PyFPE_START_PROTECT("in math_frexp", return 0);
668 x = frexp(x, &i);
669 PyFPE_END_PROTECT(x);
670 }
671 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +0000672}
673
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000674PyDoc_STRVAR(math_frexp_doc,
Tim Peters63c94532001-09-04 23:17:42 +0000675"frexp(x)\n"
676"\n"
677"Return the mantissa and exponent of x, as pair (m, e).\n"
678"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 +0000679"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 +0000680
Barry Warsaw8b43b191996-12-09 22:32:36 +0000681static PyObject *
Fred Drake40c48682000-07-03 18:11:56 +0000682math_ldexp(PyObject *self, PyObject *args)
Guido van Rossumd18ad581991-10-24 14:57:21 +0000683{
Christian Heimes53876d92008-04-19 00:31:39 +0000684 double x, r;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000685 PyObject *oexp;
686 long exp;
687 if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp))
Guido van Rossumd18ad581991-10-24 14:57:21 +0000688 return NULL;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000689
690 if (PyLong_Check(oexp)) {
691 /* on overflow, replace exponent with either LONG_MAX
692 or LONG_MIN, depending on the sign. */
693 exp = PyLong_AsLong(oexp);
694 if (exp == -1 && PyErr_Occurred()) {
695 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
696 if (Py_SIZE(oexp) < 0) {
697 exp = LONG_MIN;
698 }
699 else {
700 exp = LONG_MAX;
701 }
702 PyErr_Clear();
703 }
704 else {
705 /* propagate any unexpected exception */
706 return NULL;
707 }
708 }
709 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000710 else {
711 PyErr_SetString(PyExc_TypeError,
712 "Expected an int or long as second argument "
713 "to ldexp.");
714 return NULL;
715 }
716
717 if (x == 0. || !Py_IS_FINITE(x)) {
718 /* NaNs, zeros and infinities are returned unchanged */
719 r = x;
Christian Heimes53876d92008-04-19 00:31:39 +0000720 errno = 0;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000721 } else if (exp > INT_MAX) {
722 /* overflow */
723 r = copysign(Py_HUGE_VAL, x);
724 errno = ERANGE;
725 } else if (exp < INT_MIN) {
726 /* underflow to +-0 */
727 r = copysign(0., x);
728 errno = 0;
729 } else {
730 errno = 0;
731 PyFPE_START_PROTECT("in math_ldexp", return 0);
732 r = ldexp(x, (int)exp);
733 PyFPE_END_PROTECT(r);
734 if (Py_IS_INFINITY(r))
735 errno = ERANGE;
736 }
737
Christian Heimes53876d92008-04-19 00:31:39 +0000738 if (errno && is_error(r))
Tim Peters1d120612000-10-12 06:10:25 +0000739 return NULL;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000740 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +0000741}
742
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000743PyDoc_STRVAR(math_ldexp_doc,
744"ldexp(x, i) -> x * (2**i)");
Guido van Rossumc6e22901998-12-04 19:26:43 +0000745
Barry Warsaw8b43b191996-12-09 22:32:36 +0000746static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +0000747math_modf(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +0000748{
Thomas Wouters89f507f2006-12-13 04:49:30 +0000749 double y, x = PyFloat_AsDouble(arg);
750 if (x == -1.0 && PyErr_Occurred())
Guido van Rossumd18ad581991-10-24 14:57:21 +0000751 return NULL;
Christian Heimesa342c012008-04-20 21:01:16 +0000752 /* some platforms don't do the right thing for NaNs and
753 infinities, so we take care of special cases directly. */
754 if (!Py_IS_FINITE(x)) {
755 if (Py_IS_INFINITY(x))
756 return Py_BuildValue("(dd)", copysign(0., x), x);
757 else if (Py_IS_NAN(x))
758 return Py_BuildValue("(dd)", x, x);
759 }
760
Guido van Rossumd18ad581991-10-24 14:57:21 +0000761 errno = 0;
Christian Heimes53876d92008-04-19 00:31:39 +0000762 PyFPE_START_PROTECT("in math_modf", return 0);
Guido van Rossumd18ad581991-10-24 14:57:21 +0000763 x = modf(x, &y);
Christian Heimes53876d92008-04-19 00:31:39 +0000764 PyFPE_END_PROTECT(x);
765 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +0000766}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000767
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000768PyDoc_STRVAR(math_modf_doc,
Tim Peters63c94532001-09-04 23:17:42 +0000769"modf(x)\n"
770"\n"
771"Return the fractional and integer parts of x. Both results carry the sign\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000772"of x. The integer part is returned as a real.");
Guido van Rossumc6e22901998-12-04 19:26:43 +0000773
Tim Peters78526162001-09-05 00:53:45 +0000774/* A decent logarithm is easy to compute even for huge longs, but libm can't
775 do that by itself -- loghelper can. func is log or log10, and name is
776 "log" or "log10". Note that overflow isn't possible: a long can contain
777 no more than INT_MAX * SHIFT bits, so has value certainly less than
778 2**(2**64 * 2**16) == 2**2**80, and log2 of that is 2**80, which is
779 small enough to fit in an IEEE single. log and log10 are even smaller.
780*/
781
782static PyObject*
Thomas Wouters89f507f2006-12-13 04:49:30 +0000783loghelper(PyObject* arg, double (*func)(double), char *funcname)
Tim Peters78526162001-09-05 00:53:45 +0000784{
Tim Peters78526162001-09-05 00:53:45 +0000785 /* If it is long, do it ourselves. */
786 if (PyLong_Check(arg)) {
787 double x;
788 int e;
789 x = _PyLong_AsScaledDouble(arg, &e);
790 if (x <= 0.0) {
791 PyErr_SetString(PyExc_ValueError,
792 "math domain error");
793 return NULL;
794 }
Christian Heimesaf98da12008-01-27 15:18:18 +0000795 /* Value is ~= x * 2**(e*PyLong_SHIFT), so the log ~=
796 log(x) + log(2) * e * PyLong_SHIFT.
797 CAUTION: e*PyLong_SHIFT may overflow using int arithmetic,
Tim Peters78526162001-09-05 00:53:45 +0000798 so force use of double. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000799 x = func(x) + (e * (double)PyLong_SHIFT) * func(2.0);
Tim Peters78526162001-09-05 00:53:45 +0000800 return PyFloat_FromDouble(x);
801 }
802
803 /* Else let libm handle it by itself. */
Christian Heimes53876d92008-04-19 00:31:39 +0000804 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +0000805}
806
807static PyObject *
808math_log(PyObject *self, PyObject *args)
809{
Raymond Hettinger866964c2002-12-14 19:51:34 +0000810 PyObject *arg;
811 PyObject *base = NULL;
812 PyObject *num, *den;
813 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +0000814
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000815 if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base))
Raymond Hettinger866964c2002-12-14 19:51:34 +0000816 return NULL;
Raymond Hettinger866964c2002-12-14 19:51:34 +0000817
Thomas Wouters89f507f2006-12-13 04:49:30 +0000818 num = loghelper(arg, log, "log");
819 if (num == NULL || base == NULL)
820 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +0000821
Thomas Wouters89f507f2006-12-13 04:49:30 +0000822 den = loghelper(base, log, "log");
Raymond Hettinger866964c2002-12-14 19:51:34 +0000823 if (den == NULL) {
824 Py_DECREF(num);
825 return NULL;
826 }
827
Neal Norwitzbcc0db82006-03-24 08:14:36 +0000828 ans = PyNumber_TrueDivide(num, den);
Raymond Hettinger866964c2002-12-14 19:51:34 +0000829 Py_DECREF(num);
830 Py_DECREF(den);
831 return ans;
Tim Peters78526162001-09-05 00:53:45 +0000832}
833
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000834PyDoc_STRVAR(math_log_doc,
Raymond Hettinger866964c2002-12-14 19:51:34 +0000835"log(x[, base]) -> the logarithm of x to the given base.\n\
836If the base not specified, returns the natural logarithm (base e) of x.");
Tim Peters78526162001-09-05 00:53:45 +0000837
838static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +0000839math_log10(PyObject *self, PyObject *arg)
Tim Peters78526162001-09-05 00:53:45 +0000840{
Thomas Wouters89f507f2006-12-13 04:49:30 +0000841 return loghelper(arg, log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +0000842}
843
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000844PyDoc_STRVAR(math_log10_doc,
845"log10(x) -> the base 10 logarithm of x.");
Tim Peters78526162001-09-05 00:53:45 +0000846
Christian Heimes53876d92008-04-19 00:31:39 +0000847static PyObject *
848math_fmod(PyObject *self, PyObject *args)
849{
850 PyObject *ox, *oy;
851 double r, x, y;
852 if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy))
853 return NULL;
854 x = PyFloat_AsDouble(ox);
855 y = PyFloat_AsDouble(oy);
856 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
857 return NULL;
858 /* fmod(x, +/-Inf) returns x for finite x. */
859 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
860 return PyFloat_FromDouble(x);
861 errno = 0;
862 PyFPE_START_PROTECT("in math_fmod", return 0);
863 r = fmod(x, y);
864 PyFPE_END_PROTECT(r);
865 if (Py_IS_NAN(r)) {
866 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
867 errno = EDOM;
868 else
869 errno = 0;
870 }
871 if (errno && is_error(r))
872 return NULL;
873 else
874 return PyFloat_FromDouble(r);
875}
876
877PyDoc_STRVAR(math_fmod_doc,
878"fmod(x,y)\n\nReturn fmod(x, y), according to platform C."
879" x % y may differ.");
880
881static PyObject *
882math_hypot(PyObject *self, PyObject *args)
883{
884 PyObject *ox, *oy;
885 double r, x, y;
886 if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy))
887 return NULL;
888 x = PyFloat_AsDouble(ox);
889 y = PyFloat_AsDouble(oy);
890 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
891 return NULL;
892 /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */
893 if (Py_IS_INFINITY(x))
894 return PyFloat_FromDouble(fabs(x));
895 if (Py_IS_INFINITY(y))
896 return PyFloat_FromDouble(fabs(y));
897 errno = 0;
898 PyFPE_START_PROTECT("in math_hypot", return 0);
899 r = hypot(x, y);
900 PyFPE_END_PROTECT(r);
901 if (Py_IS_NAN(r)) {
902 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
903 errno = EDOM;
904 else
905 errno = 0;
906 }
907 else if (Py_IS_INFINITY(r)) {
908 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
909 errno = ERANGE;
910 else
911 errno = 0;
912 }
913 if (errno && is_error(r))
914 return NULL;
915 else
916 return PyFloat_FromDouble(r);
917}
918
919PyDoc_STRVAR(math_hypot_doc,
920"hypot(x,y)\n\nReturn the Euclidean distance, sqrt(x*x + y*y).");
921
922/* pow can't use math_2, but needs its own wrapper: the problem is
923 that an infinite result can arise either as a result of overflow
924 (in which case OverflowError should be raised) or as a result of
925 e.g. 0.**-5. (for which ValueError needs to be raised.)
926*/
927
928static PyObject *
929math_pow(PyObject *self, PyObject *args)
930{
931 PyObject *ox, *oy;
932 double r, x, y;
Christian Heimesa342c012008-04-20 21:01:16 +0000933 int odd_y;
Christian Heimes53876d92008-04-19 00:31:39 +0000934
935 if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy))
936 return NULL;
937 x = PyFloat_AsDouble(ox);
938 y = PyFloat_AsDouble(oy);
939 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
940 return NULL;
Christian Heimesa342c012008-04-20 21:01:16 +0000941
942 /* deal directly with IEEE specials, to cope with problems on various
943 platforms whose semantics don't exactly match C99 */
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000944 r = 0.; /* silence compiler warning */
Christian Heimesa342c012008-04-20 21:01:16 +0000945 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
946 errno = 0;
947 if (Py_IS_NAN(x))
948 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
949 else if (Py_IS_NAN(y))
950 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
951 else if (Py_IS_INFINITY(x)) {
952 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
953 if (y > 0.)
954 r = odd_y ? x : fabs(x);
955 else if (y == 0.)
956 r = 1.;
957 else /* y < 0. */
958 r = odd_y ? copysign(0., x) : 0.;
959 }
960 else if (Py_IS_INFINITY(y)) {
961 if (fabs(x) == 1.0)
962 r = 1.;
963 else if (y > 0. && fabs(x) > 1.0)
964 r = y;
965 else if (y < 0. && fabs(x) < 1.0) {
966 r = -y; /* result is +inf */
967 if (x == 0.) /* 0**-inf: divide-by-zero */
968 errno = EDOM;
969 }
970 else
971 r = 0.;
972 }
Christian Heimes53876d92008-04-19 00:31:39 +0000973 }
Christian Heimesa342c012008-04-20 21:01:16 +0000974 else {
975 /* let libm handle finite**finite */
976 errno = 0;
977 PyFPE_START_PROTECT("in math_pow", return 0);
978 r = pow(x, y);
979 PyFPE_END_PROTECT(r);
980 /* a NaN result should arise only from (-ve)**(finite
981 non-integer); in this case we want to raise ValueError. */
982 if (!Py_IS_FINITE(r)) {
983 if (Py_IS_NAN(r)) {
984 errno = EDOM;
985 }
986 /*
987 an infinite result here arises either from:
988 (A) (+/-0.)**negative (-> divide-by-zero)
989 (B) overflow of x**y with x and y finite
990 */
991 else if (Py_IS_INFINITY(r)) {
992 if (x == 0.)
993 errno = EDOM;
994 else
995 errno = ERANGE;
996 }
997 }
Christian Heimes53876d92008-04-19 00:31:39 +0000998 }
999
1000 if (errno && is_error(r))
1001 return NULL;
1002 else
1003 return PyFloat_FromDouble(r);
1004}
1005
1006PyDoc_STRVAR(math_pow_doc,
1007"pow(x,y)\n\nReturn x**y (x to the power of y).");
1008
Christian Heimes072c0f12008-01-03 23:01:04 +00001009static const double degToRad = Py_MATH_PI / 180.0;
1010static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001011
1012static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001013math_degrees(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001014{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001015 double x = PyFloat_AsDouble(arg);
1016 if (x == -1.0 && PyErr_Occurred())
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001017 return NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +00001018 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001019}
1020
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001021PyDoc_STRVAR(math_degrees_doc,
1022"degrees(x) -> converts angle x from radians to degrees");
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001023
1024static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001025math_radians(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001026{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001027 double x = PyFloat_AsDouble(arg);
1028 if (x == -1.0 && PyErr_Occurred())
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001029 return NULL;
1030 return PyFloat_FromDouble(x * degToRad);
1031}
1032
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001033PyDoc_STRVAR(math_radians_doc,
1034"radians(x) -> converts angle x from degrees to radians");
Tim Peters78526162001-09-05 00:53:45 +00001035
Christian Heimes072c0f12008-01-03 23:01:04 +00001036static PyObject *
1037math_isnan(PyObject *self, PyObject *arg)
1038{
1039 double x = PyFloat_AsDouble(arg);
1040 if (x == -1.0 && PyErr_Occurred())
1041 return NULL;
1042 return PyBool_FromLong((long)Py_IS_NAN(x));
1043}
1044
1045PyDoc_STRVAR(math_isnan_doc,
1046"isnan(x) -> bool\n\
1047Checks if float x is not a number (NaN)");
1048
1049static PyObject *
1050math_isinf(PyObject *self, PyObject *arg)
1051{
1052 double x = PyFloat_AsDouble(arg);
1053 if (x == -1.0 && PyErr_Occurred())
1054 return NULL;
1055 return PyBool_FromLong((long)Py_IS_INFINITY(x));
1056}
1057
1058PyDoc_STRVAR(math_isinf_doc,
1059"isinf(x) -> bool\n\
1060Checks if float x is infinite (positive or negative)");
1061
Barry Warsaw8b43b191996-12-09 22:32:36 +00001062static PyMethodDef math_methods[] = {
Thomas Wouters89f507f2006-12-13 04:49:30 +00001063 {"acos", math_acos, METH_O, math_acos_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001064 {"acosh", math_acosh, METH_O, math_acosh_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001065 {"asin", math_asin, METH_O, math_asin_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001066 {"asinh", math_asinh, METH_O, math_asinh_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001067 {"atan", math_atan, METH_O, math_atan_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001068 {"atan2", math_atan2, METH_VARARGS, math_atan2_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001069 {"atanh", math_atanh, METH_O, math_atanh_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001070 {"ceil", math_ceil, METH_O, math_ceil_doc},
Christian Heimes072c0f12008-01-03 23:01:04 +00001071 {"copysign", math_copysign, METH_VARARGS, math_copysign_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001072 {"cos", math_cos, METH_O, math_cos_doc},
1073 {"cosh", math_cosh, METH_O, math_cosh_doc},
1074 {"degrees", math_degrees, METH_O, math_degrees_doc},
1075 {"exp", math_exp, METH_O, math_exp_doc},
1076 {"fabs", math_fabs, METH_O, math_fabs_doc},
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001077 {"factorial", math_factorial, METH_O, math_factorial_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001078 {"floor", math_floor, METH_O, math_floor_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001079 {"fmod", math_fmod, METH_VARARGS, math_fmod_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001080 {"frexp", math_frexp, METH_O, math_frexp_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001081 {"hypot", math_hypot, METH_VARARGS, math_hypot_doc},
Christian Heimes072c0f12008-01-03 23:01:04 +00001082 {"isinf", math_isinf, METH_O, math_isinf_doc},
1083 {"isnan", math_isnan, METH_O, math_isnan_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001084 {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc},
1085 {"log", math_log, METH_VARARGS, math_log_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001086 {"log1p", math_log1p, METH_O, math_log1p_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001087 {"log10", math_log10, METH_O, math_log10_doc},
1088 {"modf", math_modf, METH_O, math_modf_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001089 {"pow", math_pow, METH_VARARGS, math_pow_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001090 {"radians", math_radians, METH_O, math_radians_doc},
1091 {"sin", math_sin, METH_O, math_sin_doc},
1092 {"sinh", math_sinh, METH_O, math_sinh_doc},
1093 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001094 {"sum", math_sum, METH_O, math_sum_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001095 {"tan", math_tan, METH_O, math_tan_doc},
1096 {"tanh", math_tanh, METH_O, math_tanh_doc},
Christian Heimes400adb02008-02-01 08:12:03 +00001097 {"trunc", math_trunc, METH_O, math_trunc_doc},
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001098 {NULL, NULL} /* sentinel */
1099};
1100
Guido van Rossumc6e22901998-12-04 19:26:43 +00001101
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001102PyDoc_STRVAR(module_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001103"This module is always available. It provides access to the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001104"mathematical functions defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001105
Martin v. Löwis1a214512008-06-11 05:26:20 +00001106
1107static struct PyModuleDef mathmodule = {
1108 PyModuleDef_HEAD_INIT,
1109 "math",
1110 module_doc,
1111 -1,
1112 math_methods,
1113 NULL,
1114 NULL,
1115 NULL,
1116 NULL
1117};
1118
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001119PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001120PyInit_math(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001121{
Christian Heimes53876d92008-04-19 00:31:39 +00001122 PyObject *m;
Tim Petersfe71f812001-08-07 22:10:00 +00001123
Martin v. Löwis1a214512008-06-11 05:26:20 +00001124 m = PyModule_Create(&mathmodule);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00001125 if (m == NULL)
1126 goto finally;
Barry Warsawfc93f751996-12-17 00:47:03 +00001127
Christian Heimes53876d92008-04-19 00:31:39 +00001128 PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
1129 PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
Barry Warsawfc93f751996-12-17 00:47:03 +00001130
Christian Heimes53876d92008-04-19 00:31:39 +00001131 finally:
Martin v. Löwis1a214512008-06-11 05:26:20 +00001132 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001133}