blob: 4c820c584881bd5313103fab72fa14e06aecd43c [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,
184 "math domain error (invalid argument)");
185 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,
190 "math range error (overflow)");
Mark Dickinsonb63aff12008-05-09 14:10:27 +0000191 else
192 PyErr_SetString(PyExc_ValueError,
193 "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
Georg Brandlf78e02b2008-06-10 17:40:04 +0000385 Note 3: The itermediate values lo, yr, and hi are declared volatile so
386 aggressive compilers won't algebraicly reduce lo to always be exactly 0.0.
387 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
389 prevents double rounding because any addition or substraction of two doubles
390 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);
617 Py_XDECREF(iobj);
618 return NULL;
619}
620
621PyDoc_STRVAR(math_factorial_doc, "Return n!");
622
623static PyObject *
Christian Heimes400adb02008-02-01 08:12:03 +0000624math_trunc(PyObject *self, PyObject *number)
625{
626 static PyObject *trunc_str = NULL;
627 PyObject *trunc;
628
629 if (Py_TYPE(number)->tp_dict == NULL) {
630 if (PyType_Ready(Py_TYPE(number)) < 0)
631 return NULL;
632 }
633
634 if (trunc_str == NULL) {
635 trunc_str = PyUnicode_InternFromString("__trunc__");
636 if (trunc_str == NULL)
637 return NULL;
638 }
639
640 trunc = _PyType_Lookup(Py_TYPE(number), trunc_str);
641 if (trunc == NULL) {
642 PyErr_Format(PyExc_TypeError,
643 "type %.100s doesn't define __trunc__ method",
644 Py_TYPE(number)->tp_name);
645 return NULL;
646 }
647 return PyObject_CallFunctionObjArgs(trunc, number, NULL);
648}
649
650PyDoc_STRVAR(math_trunc_doc,
651"trunc(x:Real) -> Integral\n"
652"\n"
Christian Heimes292d3512008-02-03 16:51:08 +0000653"Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.");
Christian Heimes400adb02008-02-01 08:12:03 +0000654
655static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +0000656math_frexp(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +0000657{
Guido van Rossumd18ad581991-10-24 14:57:21 +0000658 int i;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000659 double x = PyFloat_AsDouble(arg);
660 if (x == -1.0 && PyErr_Occurred())
Guido van Rossumd18ad581991-10-24 14:57:21 +0000661 return NULL;
Christian Heimes53876d92008-04-19 00:31:39 +0000662 /* deal with special cases directly, to sidestep platform
663 differences */
664 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
665 i = 0;
666 }
667 else {
668 PyFPE_START_PROTECT("in math_frexp", return 0);
669 x = frexp(x, &i);
670 PyFPE_END_PROTECT(x);
671 }
672 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +0000673}
674
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000675PyDoc_STRVAR(math_frexp_doc,
Tim Peters63c94532001-09-04 23:17:42 +0000676"frexp(x)\n"
677"\n"
678"Return the mantissa and exponent of x, as pair (m, e).\n"
679"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 +0000680"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 +0000681
Barry Warsaw8b43b191996-12-09 22:32:36 +0000682static PyObject *
Fred Drake40c48682000-07-03 18:11:56 +0000683math_ldexp(PyObject *self, PyObject *args)
Guido van Rossumd18ad581991-10-24 14:57:21 +0000684{
Christian Heimes53876d92008-04-19 00:31:39 +0000685 double x, r;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000686 PyObject *oexp;
687 long exp;
688 if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp))
Guido van Rossumd18ad581991-10-24 14:57:21 +0000689 return NULL;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000690
691 if (PyLong_Check(oexp)) {
692 /* on overflow, replace exponent with either LONG_MAX
693 or LONG_MIN, depending on the sign. */
694 exp = PyLong_AsLong(oexp);
695 if (exp == -1 && PyErr_Occurred()) {
696 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
697 if (Py_SIZE(oexp) < 0) {
698 exp = LONG_MIN;
699 }
700 else {
701 exp = LONG_MAX;
702 }
703 PyErr_Clear();
704 }
705 else {
706 /* propagate any unexpected exception */
707 return NULL;
708 }
709 }
710 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000711 else {
712 PyErr_SetString(PyExc_TypeError,
713 "Expected an int or long as second argument "
714 "to ldexp.");
715 return NULL;
716 }
717
718 if (x == 0. || !Py_IS_FINITE(x)) {
719 /* NaNs, zeros and infinities are returned unchanged */
720 r = x;
Christian Heimes53876d92008-04-19 00:31:39 +0000721 errno = 0;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000722 } else if (exp > INT_MAX) {
723 /* overflow */
724 r = copysign(Py_HUGE_VAL, x);
725 errno = ERANGE;
726 } else if (exp < INT_MIN) {
727 /* underflow to +-0 */
728 r = copysign(0., x);
729 errno = 0;
730 } else {
731 errno = 0;
732 PyFPE_START_PROTECT("in math_ldexp", return 0);
733 r = ldexp(x, (int)exp);
734 PyFPE_END_PROTECT(r);
735 if (Py_IS_INFINITY(r))
736 errno = ERANGE;
737 }
738
Christian Heimes53876d92008-04-19 00:31:39 +0000739 if (errno && is_error(r))
Tim Peters1d120612000-10-12 06:10:25 +0000740 return NULL;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000741 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +0000742}
743
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000744PyDoc_STRVAR(math_ldexp_doc,
745"ldexp(x, i) -> x * (2**i)");
Guido van Rossumc6e22901998-12-04 19:26:43 +0000746
Barry Warsaw8b43b191996-12-09 22:32:36 +0000747static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +0000748math_modf(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +0000749{
Thomas Wouters89f507f2006-12-13 04:49:30 +0000750 double y, x = PyFloat_AsDouble(arg);
751 if (x == -1.0 && PyErr_Occurred())
Guido van Rossumd18ad581991-10-24 14:57:21 +0000752 return NULL;
Christian Heimesa342c012008-04-20 21:01:16 +0000753 /* some platforms don't do the right thing for NaNs and
754 infinities, so we take care of special cases directly. */
755 if (!Py_IS_FINITE(x)) {
756 if (Py_IS_INFINITY(x))
757 return Py_BuildValue("(dd)", copysign(0., x), x);
758 else if (Py_IS_NAN(x))
759 return Py_BuildValue("(dd)", x, x);
760 }
761
Guido van Rossumd18ad581991-10-24 14:57:21 +0000762 errno = 0;
Christian Heimes53876d92008-04-19 00:31:39 +0000763 PyFPE_START_PROTECT("in math_modf", return 0);
Guido van Rossumd18ad581991-10-24 14:57:21 +0000764 x = modf(x, &y);
Christian Heimes53876d92008-04-19 00:31:39 +0000765 PyFPE_END_PROTECT(x);
766 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +0000767}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000768
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000769PyDoc_STRVAR(math_modf_doc,
Tim Peters63c94532001-09-04 23:17:42 +0000770"modf(x)\n"
771"\n"
772"Return the fractional and integer parts of x. Both results carry the sign\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000773"of x. The integer part is returned as a real.");
Guido van Rossumc6e22901998-12-04 19:26:43 +0000774
Tim Peters78526162001-09-05 00:53:45 +0000775/* A decent logarithm is easy to compute even for huge longs, but libm can't
776 do that by itself -- loghelper can. func is log or log10, and name is
777 "log" or "log10". Note that overflow isn't possible: a long can contain
778 no more than INT_MAX * SHIFT bits, so has value certainly less than
779 2**(2**64 * 2**16) == 2**2**80, and log2 of that is 2**80, which is
780 small enough to fit in an IEEE single. log and log10 are even smaller.
781*/
782
783static PyObject*
Thomas Wouters89f507f2006-12-13 04:49:30 +0000784loghelper(PyObject* arg, double (*func)(double), char *funcname)
Tim Peters78526162001-09-05 00:53:45 +0000785{
Tim Peters78526162001-09-05 00:53:45 +0000786 /* If it is long, do it ourselves. */
787 if (PyLong_Check(arg)) {
788 double x;
789 int e;
790 x = _PyLong_AsScaledDouble(arg, &e);
791 if (x <= 0.0) {
792 PyErr_SetString(PyExc_ValueError,
793 "math domain error");
794 return NULL;
795 }
Christian Heimesaf98da12008-01-27 15:18:18 +0000796 /* Value is ~= x * 2**(e*PyLong_SHIFT), so the log ~=
797 log(x) + log(2) * e * PyLong_SHIFT.
798 CAUTION: e*PyLong_SHIFT may overflow using int arithmetic,
Tim Peters78526162001-09-05 00:53:45 +0000799 so force use of double. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000800 x = func(x) + (e * (double)PyLong_SHIFT) * func(2.0);
Tim Peters78526162001-09-05 00:53:45 +0000801 return PyFloat_FromDouble(x);
802 }
803
804 /* Else let libm handle it by itself. */
Christian Heimes53876d92008-04-19 00:31:39 +0000805 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +0000806}
807
808static PyObject *
809math_log(PyObject *self, PyObject *args)
810{
Raymond Hettinger866964c2002-12-14 19:51:34 +0000811 PyObject *arg;
812 PyObject *base = NULL;
813 PyObject *num, *den;
814 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +0000815
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000816 if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base))
Raymond Hettinger866964c2002-12-14 19:51:34 +0000817 return NULL;
Raymond Hettinger866964c2002-12-14 19:51:34 +0000818
Thomas Wouters89f507f2006-12-13 04:49:30 +0000819 num = loghelper(arg, log, "log");
820 if (num == NULL || base == NULL)
821 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +0000822
Thomas Wouters89f507f2006-12-13 04:49:30 +0000823 den = loghelper(base, log, "log");
Raymond Hettinger866964c2002-12-14 19:51:34 +0000824 if (den == NULL) {
825 Py_DECREF(num);
826 return NULL;
827 }
828
Neal Norwitzbcc0db82006-03-24 08:14:36 +0000829 ans = PyNumber_TrueDivide(num, den);
Raymond Hettinger866964c2002-12-14 19:51:34 +0000830 Py_DECREF(num);
831 Py_DECREF(den);
832 return ans;
Tim Peters78526162001-09-05 00:53:45 +0000833}
834
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000835PyDoc_STRVAR(math_log_doc,
Raymond Hettinger866964c2002-12-14 19:51:34 +0000836"log(x[, base]) -> the logarithm of x to the given base.\n\
837If the base not specified, returns the natural logarithm (base e) of x.");
Tim Peters78526162001-09-05 00:53:45 +0000838
839static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +0000840math_log10(PyObject *self, PyObject *arg)
Tim Peters78526162001-09-05 00:53:45 +0000841{
Thomas Wouters89f507f2006-12-13 04:49:30 +0000842 return loghelper(arg, log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +0000843}
844
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000845PyDoc_STRVAR(math_log10_doc,
846"log10(x) -> the base 10 logarithm of x.");
Tim Peters78526162001-09-05 00:53:45 +0000847
Christian Heimes53876d92008-04-19 00:31:39 +0000848static PyObject *
849math_fmod(PyObject *self, PyObject *args)
850{
851 PyObject *ox, *oy;
852 double r, x, y;
853 if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy))
854 return NULL;
855 x = PyFloat_AsDouble(ox);
856 y = PyFloat_AsDouble(oy);
857 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
858 return NULL;
859 /* fmod(x, +/-Inf) returns x for finite x. */
860 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
861 return PyFloat_FromDouble(x);
862 errno = 0;
863 PyFPE_START_PROTECT("in math_fmod", return 0);
864 r = fmod(x, y);
865 PyFPE_END_PROTECT(r);
866 if (Py_IS_NAN(r)) {
867 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
868 errno = EDOM;
869 else
870 errno = 0;
871 }
872 if (errno && is_error(r))
873 return NULL;
874 else
875 return PyFloat_FromDouble(r);
876}
877
878PyDoc_STRVAR(math_fmod_doc,
879"fmod(x,y)\n\nReturn fmod(x, y), according to platform C."
880" x % y may differ.");
881
882static PyObject *
883math_hypot(PyObject *self, PyObject *args)
884{
885 PyObject *ox, *oy;
886 double r, x, y;
887 if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy))
888 return NULL;
889 x = PyFloat_AsDouble(ox);
890 y = PyFloat_AsDouble(oy);
891 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
892 return NULL;
893 /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */
894 if (Py_IS_INFINITY(x))
895 return PyFloat_FromDouble(fabs(x));
896 if (Py_IS_INFINITY(y))
897 return PyFloat_FromDouble(fabs(y));
898 errno = 0;
899 PyFPE_START_PROTECT("in math_hypot", return 0);
900 r = hypot(x, y);
901 PyFPE_END_PROTECT(r);
902 if (Py_IS_NAN(r)) {
903 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
904 errno = EDOM;
905 else
906 errno = 0;
907 }
908 else if (Py_IS_INFINITY(r)) {
909 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
910 errno = ERANGE;
911 else
912 errno = 0;
913 }
914 if (errno && is_error(r))
915 return NULL;
916 else
917 return PyFloat_FromDouble(r);
918}
919
920PyDoc_STRVAR(math_hypot_doc,
921"hypot(x,y)\n\nReturn the Euclidean distance, sqrt(x*x + y*y).");
922
923/* pow can't use math_2, but needs its own wrapper: the problem is
924 that an infinite result can arise either as a result of overflow
925 (in which case OverflowError should be raised) or as a result of
926 e.g. 0.**-5. (for which ValueError needs to be raised.)
927*/
928
929static PyObject *
930math_pow(PyObject *self, PyObject *args)
931{
932 PyObject *ox, *oy;
933 double r, x, y;
Christian Heimesa342c012008-04-20 21:01:16 +0000934 int odd_y;
Christian Heimes53876d92008-04-19 00:31:39 +0000935
936 if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy))
937 return NULL;
938 x = PyFloat_AsDouble(ox);
939 y = PyFloat_AsDouble(oy);
940 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
941 return NULL;
Christian Heimesa342c012008-04-20 21:01:16 +0000942
943 /* deal directly with IEEE specials, to cope with problems on various
944 platforms whose semantics don't exactly match C99 */
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000945 r = 0.; /* silence compiler warning */
Christian Heimesa342c012008-04-20 21:01:16 +0000946 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
947 errno = 0;
948 if (Py_IS_NAN(x))
949 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
950 else if (Py_IS_NAN(y))
951 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
952 else if (Py_IS_INFINITY(x)) {
953 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
954 if (y > 0.)
955 r = odd_y ? x : fabs(x);
956 else if (y == 0.)
957 r = 1.;
958 else /* y < 0. */
959 r = odd_y ? copysign(0., x) : 0.;
960 }
961 else if (Py_IS_INFINITY(y)) {
962 if (fabs(x) == 1.0)
963 r = 1.;
964 else if (y > 0. && fabs(x) > 1.0)
965 r = y;
966 else if (y < 0. && fabs(x) < 1.0) {
967 r = -y; /* result is +inf */
968 if (x == 0.) /* 0**-inf: divide-by-zero */
969 errno = EDOM;
970 }
971 else
972 r = 0.;
973 }
Christian Heimes53876d92008-04-19 00:31:39 +0000974 }
Christian Heimesa342c012008-04-20 21:01:16 +0000975 else {
976 /* let libm handle finite**finite */
977 errno = 0;
978 PyFPE_START_PROTECT("in math_pow", return 0);
979 r = pow(x, y);
980 PyFPE_END_PROTECT(r);
981 /* a NaN result should arise only from (-ve)**(finite
982 non-integer); in this case we want to raise ValueError. */
983 if (!Py_IS_FINITE(r)) {
984 if (Py_IS_NAN(r)) {
985 errno = EDOM;
986 }
987 /*
988 an infinite result here arises either from:
989 (A) (+/-0.)**negative (-> divide-by-zero)
990 (B) overflow of x**y with x and y finite
991 */
992 else if (Py_IS_INFINITY(r)) {
993 if (x == 0.)
994 errno = EDOM;
995 else
996 errno = ERANGE;
997 }
998 }
Christian Heimes53876d92008-04-19 00:31:39 +0000999 }
1000
1001 if (errno && is_error(r))
1002 return NULL;
1003 else
1004 return PyFloat_FromDouble(r);
1005}
1006
1007PyDoc_STRVAR(math_pow_doc,
1008"pow(x,y)\n\nReturn x**y (x to the power of y).");
1009
Christian Heimes072c0f12008-01-03 23:01:04 +00001010static const double degToRad = Py_MATH_PI / 180.0;
1011static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001012
1013static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001014math_degrees(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001015{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001016 double x = PyFloat_AsDouble(arg);
1017 if (x == -1.0 && PyErr_Occurred())
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001018 return NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +00001019 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001020}
1021
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001022PyDoc_STRVAR(math_degrees_doc,
1023"degrees(x) -> converts angle x from radians to degrees");
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001024
1025static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001026math_radians(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001027{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001028 double x = PyFloat_AsDouble(arg);
1029 if (x == -1.0 && PyErr_Occurred())
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001030 return NULL;
1031 return PyFloat_FromDouble(x * degToRad);
1032}
1033
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001034PyDoc_STRVAR(math_radians_doc,
1035"radians(x) -> converts angle x from degrees to radians");
Tim Peters78526162001-09-05 00:53:45 +00001036
Christian Heimes072c0f12008-01-03 23:01:04 +00001037static PyObject *
1038math_isnan(PyObject *self, PyObject *arg)
1039{
1040 double x = PyFloat_AsDouble(arg);
1041 if (x == -1.0 && PyErr_Occurred())
1042 return NULL;
1043 return PyBool_FromLong((long)Py_IS_NAN(x));
1044}
1045
1046PyDoc_STRVAR(math_isnan_doc,
1047"isnan(x) -> bool\n\
1048Checks if float x is not a number (NaN)");
1049
1050static PyObject *
1051math_isinf(PyObject *self, PyObject *arg)
1052{
1053 double x = PyFloat_AsDouble(arg);
1054 if (x == -1.0 && PyErr_Occurred())
1055 return NULL;
1056 return PyBool_FromLong((long)Py_IS_INFINITY(x));
1057}
1058
1059PyDoc_STRVAR(math_isinf_doc,
1060"isinf(x) -> bool\n\
1061Checks if float x is infinite (positive or negative)");
1062
Barry Warsaw8b43b191996-12-09 22:32:36 +00001063static PyMethodDef math_methods[] = {
Thomas Wouters89f507f2006-12-13 04:49:30 +00001064 {"acos", math_acos, METH_O, math_acos_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001065 {"acosh", math_acosh, METH_O, math_acosh_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001066 {"asin", math_asin, METH_O, math_asin_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001067 {"asinh", math_asinh, METH_O, math_asinh_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001068 {"atan", math_atan, METH_O, math_atan_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001069 {"atan2", math_atan2, METH_VARARGS, math_atan2_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001070 {"atanh", math_atanh, METH_O, math_atanh_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001071 {"ceil", math_ceil, METH_O, math_ceil_doc},
Christian Heimes072c0f12008-01-03 23:01:04 +00001072 {"copysign", math_copysign, METH_VARARGS, math_copysign_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001073 {"cos", math_cos, METH_O, math_cos_doc},
1074 {"cosh", math_cosh, METH_O, math_cosh_doc},
1075 {"degrees", math_degrees, METH_O, math_degrees_doc},
1076 {"exp", math_exp, METH_O, math_exp_doc},
1077 {"fabs", math_fabs, METH_O, math_fabs_doc},
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001078 {"factorial", math_factorial, METH_O, math_factorial_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001079 {"floor", math_floor, METH_O, math_floor_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001080 {"fmod", math_fmod, METH_VARARGS, math_fmod_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001081 {"frexp", math_frexp, METH_O, math_frexp_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001082 {"hypot", math_hypot, METH_VARARGS, math_hypot_doc},
Christian Heimes072c0f12008-01-03 23:01:04 +00001083 {"isinf", math_isinf, METH_O, math_isinf_doc},
1084 {"isnan", math_isnan, METH_O, math_isnan_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001085 {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc},
1086 {"log", math_log, METH_VARARGS, math_log_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001087 {"log1p", math_log1p, METH_O, math_log1p_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001088 {"log10", math_log10, METH_O, math_log10_doc},
1089 {"modf", math_modf, METH_O, math_modf_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001090 {"pow", math_pow, METH_VARARGS, math_pow_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001091 {"radians", math_radians, METH_O, math_radians_doc},
1092 {"sin", math_sin, METH_O, math_sin_doc},
1093 {"sinh", math_sinh, METH_O, math_sinh_doc},
1094 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001095 {"sum", math_sum, METH_O, math_sum_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001096 {"tan", math_tan, METH_O, math_tan_doc},
1097 {"tanh", math_tanh, METH_O, math_tanh_doc},
Christian Heimes400adb02008-02-01 08:12:03 +00001098 {"trunc", math_trunc, METH_O, math_trunc_doc},
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001099 {NULL, NULL} /* sentinel */
1100};
1101
Guido van Rossumc6e22901998-12-04 19:26:43 +00001102
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001103PyDoc_STRVAR(module_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001104"This module is always available. It provides access to the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001105"mathematical functions defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001106
Martin v. Löwis1a214512008-06-11 05:26:20 +00001107
1108static struct PyModuleDef mathmodule = {
1109 PyModuleDef_HEAD_INIT,
1110 "math",
1111 module_doc,
1112 -1,
1113 math_methods,
1114 NULL,
1115 NULL,
1116 NULL,
1117 NULL
1118};
1119
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001120PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001121PyInit_math(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001122{
Christian Heimes53876d92008-04-19 00:31:39 +00001123 PyObject *m;
Tim Petersfe71f812001-08-07 22:10:00 +00001124
Martin v. Löwis1a214512008-06-11 05:26:20 +00001125 m = PyModule_Create(&mathmodule);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00001126 if (m == NULL)
1127 goto finally;
Barry Warsawfc93f751996-12-17 00:47:03 +00001128
Christian Heimes53876d92008-04-19 00:31:39 +00001129 PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
1130 PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
Barry Warsawfc93f751996-12-17 00:47:03 +00001131
Christian Heimes53876d92008-04-19 00:31:39 +00001132 finally:
Martin v. Löwis1a214512008-06-11 05:26:20 +00001133 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001134}