blob: d23d2ffcb5df59ceb79f1ac3e180bbcb357f2cf2 [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
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000399 Note 5: The signature of math.fsum() differs from __builtin__.sum()
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000400 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 */
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000410_fsum_realloc(double **p_ptr, Py_ssize_t n,
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000411 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 */
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000428 PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000429 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*
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000467math_fsum(PyObject *self, PyObject *seq)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000468{
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;
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000472 double xsave, special_sum = 0.0, inf_sum = 0.0;
Georg Brandlf78e02b2008-06-10 17:40:04 +0000473 volatile double hi, yr, lo;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000474
475 iter = PyObject_GetIter(seq);
476 if (iter == NULL)
477 return NULL;
478
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000479 PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000480
481 for(;;) { /* for x in iterable */
482 assert(0 <= n && n <= m);
483 assert((m == NUM_PARTIALS && p == ps) ||
484 (m > NUM_PARTIALS && p != NULL));
485
486 item = PyIter_Next(iter);
487 if (item == NULL) {
488 if (PyErr_Occurred())
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000489 goto _fsum_error;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000490 break;
491 }
492 x = PyFloat_AsDouble(item);
493 Py_DECREF(item);
494 if (PyErr_Occurred())
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000495 goto _fsum_error;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000496
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000497 xsave = x;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000498 for (i = j = 0; j < n; j++) { /* for y in partials */
499 y = p[j];
Georg Brandlf78e02b2008-06-10 17:40:04 +0000500 if (fabs(x) < fabs(y)) {
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000501 t = x; x = y; y = t;
Georg Brandlf78e02b2008-06-10 17:40:04 +0000502 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000503 hi = x + y;
Georg Brandlf78e02b2008-06-10 17:40:04 +0000504 yr = hi - x;
505 lo = y - yr;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000506 if (lo != 0.0)
507 p[i++] = lo;
508 x = hi;
509 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000510
511 n = i; /* ps[i:] = [x] */
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000512 if (x != 0.0) {
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000513 if (! Py_IS_FINITE(x)) {
514 /* a nonfinite x could arise either as
515 a result of intermediate overflow, or
516 as a result of a nan or inf in the
517 summands */
518 if (Py_IS_FINITE(xsave)) {
519 PyErr_SetString(PyExc_OverflowError,
520 "intermediate overflow in fsum");
521 goto _fsum_error;
522 }
523 if (Py_IS_INFINITY(xsave))
524 inf_sum += xsave;
525 special_sum += xsave;
526 /* reset partials */
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000527 n = 0;
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000528 }
529 else if (n >= m && _fsum_realloc(&p, n, ps, &m))
530 goto _fsum_error;
531 else
532 p[n++] = x;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000533 }
534 }
535
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000536 if (special_sum != 0.0) {
537 if (Py_IS_NAN(inf_sum))
538 PyErr_SetString(PyExc_ValueError,
539 "-inf + inf in fsum");
540 else
541 sum = PyFloat_FromDouble(special_sum);
542 goto _fsum_error;
543 }
544
Georg Brandlf78e02b2008-06-10 17:40:04 +0000545 hi = 0.0;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000546 if (n > 0) {
547 hi = p[--n];
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000548 /* sum_exact(ps, hi) from the top, stop when the sum becomes
549 inexact. */
550 while (n > 0) {
551 x = hi;
552 y = p[--n];
553 assert(fabs(y) < fabs(x));
554 hi = x + y;
555 yr = hi - x;
556 lo = y - yr;
557 if (lo != 0.0)
558 break;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000559 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000560 /* Make half-even rounding work across multiple partials.
561 Needed so that sum([1e-16, 1, 1e16]) will round-up the last
562 digit to two instead of down to zero (the 1e-16 makes the 1
563 slightly closer to two). With a potential 1 ULP rounding
564 error fixed-up, math.fsum() can guarantee commutativity. */
565 if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
566 (lo > 0.0 && p[n-1] > 0.0))) {
567 y = lo * 2.0;
568 x = hi + y;
569 yr = x - hi;
570 if (y == yr)
571 hi = x;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000572 }
573 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000574 sum = PyFloat_FromDouble(hi);
575
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000576_fsum_error:
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000577 PyFPE_END_PROTECT(hi)
578 Py_DECREF(iter);
579 if (p != ps)
580 PyMem_Free(p);
581 return sum;
582}
583
584#undef NUM_PARTIALS
585
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000586PyDoc_STRVAR(math_fsum_doc,
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000587"sum(iterable)\n\n\
588Return an accurate floating point sum of values in the iterable.\n\
589Assumes IEEE-754 floating point arithmetic.");
590
Barry Warsaw8b43b191996-12-09 22:32:36 +0000591static PyObject *
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000592math_factorial(PyObject *self, PyObject *arg)
593{
594 long i, x;
595 PyObject *result, *iobj, *newresult;
596
597 if (PyFloat_Check(arg)) {
598 double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
599 if (dx != floor(dx)) {
600 PyErr_SetString(PyExc_ValueError,
601 "factorial() only accepts integral values");
602 return NULL;
603 }
604 }
605
606 x = PyLong_AsLong(arg);
607 if (x == -1 && PyErr_Occurred())
608 return NULL;
609 if (x < 0) {
610 PyErr_SetString(PyExc_ValueError,
611 "factorial() not defined for negative values");
612 return NULL;
613 }
614
615 result = (PyObject *)PyLong_FromLong(1);
616 if (result == NULL)
617 return NULL;
618 for (i=1 ; i<=x ; i++) {
619 iobj = (PyObject *)PyLong_FromLong(i);
620 if (iobj == NULL)
621 goto error;
622 newresult = PyNumber_Multiply(result, iobj);
623 Py_DECREF(iobj);
624 if (newresult == NULL)
625 goto error;
626 Py_DECREF(result);
627 result = newresult;
628 }
629 return result;
630
631error:
632 Py_DECREF(result);
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000633 return NULL;
634}
635
636PyDoc_STRVAR(math_factorial_doc, "Return n!");
637
638static PyObject *
Christian Heimes400adb02008-02-01 08:12:03 +0000639math_trunc(PyObject *self, PyObject *number)
640{
641 static PyObject *trunc_str = NULL;
642 PyObject *trunc;
643
644 if (Py_TYPE(number)->tp_dict == NULL) {
645 if (PyType_Ready(Py_TYPE(number)) < 0)
646 return NULL;
647 }
648
649 if (trunc_str == NULL) {
650 trunc_str = PyUnicode_InternFromString("__trunc__");
651 if (trunc_str == NULL)
652 return NULL;
653 }
654
655 trunc = _PyType_Lookup(Py_TYPE(number), trunc_str);
656 if (trunc == NULL) {
657 PyErr_Format(PyExc_TypeError,
658 "type %.100s doesn't define __trunc__ method",
659 Py_TYPE(number)->tp_name);
660 return NULL;
661 }
662 return PyObject_CallFunctionObjArgs(trunc, number, NULL);
663}
664
665PyDoc_STRVAR(math_trunc_doc,
666"trunc(x:Real) -> Integral\n"
667"\n"
Christian Heimes292d3512008-02-03 16:51:08 +0000668"Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.");
Christian Heimes400adb02008-02-01 08:12:03 +0000669
670static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +0000671math_frexp(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +0000672{
Guido van Rossumd18ad581991-10-24 14:57:21 +0000673 int i;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000674 double x = PyFloat_AsDouble(arg);
675 if (x == -1.0 && PyErr_Occurred())
Guido van Rossumd18ad581991-10-24 14:57:21 +0000676 return NULL;
Christian Heimes53876d92008-04-19 00:31:39 +0000677 /* deal with special cases directly, to sidestep platform
678 differences */
679 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
680 i = 0;
681 }
682 else {
683 PyFPE_START_PROTECT("in math_frexp", return 0);
684 x = frexp(x, &i);
685 PyFPE_END_PROTECT(x);
686 }
687 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +0000688}
689
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000690PyDoc_STRVAR(math_frexp_doc,
Tim Peters63c94532001-09-04 23:17:42 +0000691"frexp(x)\n"
692"\n"
693"Return the mantissa and exponent of x, as pair (m, e).\n"
694"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 +0000695"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 +0000696
Barry Warsaw8b43b191996-12-09 22:32:36 +0000697static PyObject *
Fred Drake40c48682000-07-03 18:11:56 +0000698math_ldexp(PyObject *self, PyObject *args)
Guido van Rossumd18ad581991-10-24 14:57:21 +0000699{
Christian Heimes53876d92008-04-19 00:31:39 +0000700 double x, r;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000701 PyObject *oexp;
702 long exp;
703 if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp))
Guido van Rossumd18ad581991-10-24 14:57:21 +0000704 return NULL;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000705
706 if (PyLong_Check(oexp)) {
707 /* on overflow, replace exponent with either LONG_MAX
708 or LONG_MIN, depending on the sign. */
709 exp = PyLong_AsLong(oexp);
710 if (exp == -1 && PyErr_Occurred()) {
711 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
712 if (Py_SIZE(oexp) < 0) {
713 exp = LONG_MIN;
714 }
715 else {
716 exp = LONG_MAX;
717 }
718 PyErr_Clear();
719 }
720 else {
721 /* propagate any unexpected exception */
722 return NULL;
723 }
724 }
725 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000726 else {
727 PyErr_SetString(PyExc_TypeError,
728 "Expected an int or long as second argument "
729 "to ldexp.");
730 return NULL;
731 }
732
733 if (x == 0. || !Py_IS_FINITE(x)) {
734 /* NaNs, zeros and infinities are returned unchanged */
735 r = x;
Christian Heimes53876d92008-04-19 00:31:39 +0000736 errno = 0;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000737 } else if (exp > INT_MAX) {
738 /* overflow */
739 r = copysign(Py_HUGE_VAL, x);
740 errno = ERANGE;
741 } else if (exp < INT_MIN) {
742 /* underflow to +-0 */
743 r = copysign(0., x);
744 errno = 0;
745 } else {
746 errno = 0;
747 PyFPE_START_PROTECT("in math_ldexp", return 0);
748 r = ldexp(x, (int)exp);
749 PyFPE_END_PROTECT(r);
750 if (Py_IS_INFINITY(r))
751 errno = ERANGE;
752 }
753
Christian Heimes53876d92008-04-19 00:31:39 +0000754 if (errno && is_error(r))
Tim Peters1d120612000-10-12 06:10:25 +0000755 return NULL;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000756 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +0000757}
758
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000759PyDoc_STRVAR(math_ldexp_doc,
760"ldexp(x, i) -> x * (2**i)");
Guido van Rossumc6e22901998-12-04 19:26:43 +0000761
Barry Warsaw8b43b191996-12-09 22:32:36 +0000762static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +0000763math_modf(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +0000764{
Thomas Wouters89f507f2006-12-13 04:49:30 +0000765 double y, x = PyFloat_AsDouble(arg);
766 if (x == -1.0 && PyErr_Occurred())
Guido van Rossumd18ad581991-10-24 14:57:21 +0000767 return NULL;
Christian Heimesa342c012008-04-20 21:01:16 +0000768 /* some platforms don't do the right thing for NaNs and
769 infinities, so we take care of special cases directly. */
770 if (!Py_IS_FINITE(x)) {
771 if (Py_IS_INFINITY(x))
772 return Py_BuildValue("(dd)", copysign(0., x), x);
773 else if (Py_IS_NAN(x))
774 return Py_BuildValue("(dd)", x, x);
775 }
776
Guido van Rossumd18ad581991-10-24 14:57:21 +0000777 errno = 0;
Christian Heimes53876d92008-04-19 00:31:39 +0000778 PyFPE_START_PROTECT("in math_modf", return 0);
Guido van Rossumd18ad581991-10-24 14:57:21 +0000779 x = modf(x, &y);
Christian Heimes53876d92008-04-19 00:31:39 +0000780 PyFPE_END_PROTECT(x);
781 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +0000782}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000783
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000784PyDoc_STRVAR(math_modf_doc,
Tim Peters63c94532001-09-04 23:17:42 +0000785"modf(x)\n"
786"\n"
787"Return the fractional and integer parts of x. Both results carry the sign\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000788"of x. The integer part is returned as a real.");
Guido van Rossumc6e22901998-12-04 19:26:43 +0000789
Tim Peters78526162001-09-05 00:53:45 +0000790/* A decent logarithm is easy to compute even for huge longs, but libm can't
791 do that by itself -- loghelper can. func is log or log10, and name is
792 "log" or "log10". Note that overflow isn't possible: a long can contain
793 no more than INT_MAX * SHIFT bits, so has value certainly less than
794 2**(2**64 * 2**16) == 2**2**80, and log2 of that is 2**80, which is
795 small enough to fit in an IEEE single. log and log10 are even smaller.
796*/
797
798static PyObject*
Thomas Wouters89f507f2006-12-13 04:49:30 +0000799loghelper(PyObject* arg, double (*func)(double), char *funcname)
Tim Peters78526162001-09-05 00:53:45 +0000800{
Tim Peters78526162001-09-05 00:53:45 +0000801 /* If it is long, do it ourselves. */
802 if (PyLong_Check(arg)) {
803 double x;
804 int e;
805 x = _PyLong_AsScaledDouble(arg, &e);
806 if (x <= 0.0) {
807 PyErr_SetString(PyExc_ValueError,
808 "math domain error");
809 return NULL;
810 }
Christian Heimesaf98da12008-01-27 15:18:18 +0000811 /* Value is ~= x * 2**(e*PyLong_SHIFT), so the log ~=
812 log(x) + log(2) * e * PyLong_SHIFT.
813 CAUTION: e*PyLong_SHIFT may overflow using int arithmetic,
Tim Peters78526162001-09-05 00:53:45 +0000814 so force use of double. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000815 x = func(x) + (e * (double)PyLong_SHIFT) * func(2.0);
Tim Peters78526162001-09-05 00:53:45 +0000816 return PyFloat_FromDouble(x);
817 }
818
819 /* Else let libm handle it by itself. */
Christian Heimes53876d92008-04-19 00:31:39 +0000820 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +0000821}
822
823static PyObject *
824math_log(PyObject *self, PyObject *args)
825{
Raymond Hettinger866964c2002-12-14 19:51:34 +0000826 PyObject *arg;
827 PyObject *base = NULL;
828 PyObject *num, *den;
829 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +0000830
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000831 if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base))
Raymond Hettinger866964c2002-12-14 19:51:34 +0000832 return NULL;
Raymond Hettinger866964c2002-12-14 19:51:34 +0000833
Thomas Wouters89f507f2006-12-13 04:49:30 +0000834 num = loghelper(arg, log, "log");
835 if (num == NULL || base == NULL)
836 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +0000837
Thomas Wouters89f507f2006-12-13 04:49:30 +0000838 den = loghelper(base, log, "log");
Raymond Hettinger866964c2002-12-14 19:51:34 +0000839 if (den == NULL) {
840 Py_DECREF(num);
841 return NULL;
842 }
843
Neal Norwitzbcc0db82006-03-24 08:14:36 +0000844 ans = PyNumber_TrueDivide(num, den);
Raymond Hettinger866964c2002-12-14 19:51:34 +0000845 Py_DECREF(num);
846 Py_DECREF(den);
847 return ans;
Tim Peters78526162001-09-05 00:53:45 +0000848}
849
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000850PyDoc_STRVAR(math_log_doc,
Raymond Hettinger866964c2002-12-14 19:51:34 +0000851"log(x[, base]) -> the logarithm of x to the given base.\n\
852If the base not specified, returns the natural logarithm (base e) of x.");
Tim Peters78526162001-09-05 00:53:45 +0000853
854static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +0000855math_log10(PyObject *self, PyObject *arg)
Tim Peters78526162001-09-05 00:53:45 +0000856{
Thomas Wouters89f507f2006-12-13 04:49:30 +0000857 return loghelper(arg, log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +0000858}
859
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000860PyDoc_STRVAR(math_log10_doc,
861"log10(x) -> the base 10 logarithm of x.");
Tim Peters78526162001-09-05 00:53:45 +0000862
Christian Heimes53876d92008-04-19 00:31:39 +0000863static PyObject *
864math_fmod(PyObject *self, PyObject *args)
865{
866 PyObject *ox, *oy;
867 double r, x, y;
868 if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy))
869 return NULL;
870 x = PyFloat_AsDouble(ox);
871 y = PyFloat_AsDouble(oy);
872 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
873 return NULL;
874 /* fmod(x, +/-Inf) returns x for finite x. */
875 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
876 return PyFloat_FromDouble(x);
877 errno = 0;
878 PyFPE_START_PROTECT("in math_fmod", return 0);
879 r = fmod(x, y);
880 PyFPE_END_PROTECT(r);
881 if (Py_IS_NAN(r)) {
882 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
883 errno = EDOM;
884 else
885 errno = 0;
886 }
887 if (errno && is_error(r))
888 return NULL;
889 else
890 return PyFloat_FromDouble(r);
891}
892
893PyDoc_STRVAR(math_fmod_doc,
894"fmod(x,y)\n\nReturn fmod(x, y), according to platform C."
895" x % y may differ.");
896
897static PyObject *
898math_hypot(PyObject *self, PyObject *args)
899{
900 PyObject *ox, *oy;
901 double r, x, y;
902 if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy))
903 return NULL;
904 x = PyFloat_AsDouble(ox);
905 y = PyFloat_AsDouble(oy);
906 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
907 return NULL;
908 /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */
909 if (Py_IS_INFINITY(x))
910 return PyFloat_FromDouble(fabs(x));
911 if (Py_IS_INFINITY(y))
912 return PyFloat_FromDouble(fabs(y));
913 errno = 0;
914 PyFPE_START_PROTECT("in math_hypot", return 0);
915 r = hypot(x, y);
916 PyFPE_END_PROTECT(r);
917 if (Py_IS_NAN(r)) {
918 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
919 errno = EDOM;
920 else
921 errno = 0;
922 }
923 else if (Py_IS_INFINITY(r)) {
924 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
925 errno = ERANGE;
926 else
927 errno = 0;
928 }
929 if (errno && is_error(r))
930 return NULL;
931 else
932 return PyFloat_FromDouble(r);
933}
934
935PyDoc_STRVAR(math_hypot_doc,
936"hypot(x,y)\n\nReturn the Euclidean distance, sqrt(x*x + y*y).");
937
938/* pow can't use math_2, but needs its own wrapper: the problem is
939 that an infinite result can arise either as a result of overflow
940 (in which case OverflowError should be raised) or as a result of
941 e.g. 0.**-5. (for which ValueError needs to be raised.)
942*/
943
944static PyObject *
945math_pow(PyObject *self, PyObject *args)
946{
947 PyObject *ox, *oy;
948 double r, x, y;
Christian Heimesa342c012008-04-20 21:01:16 +0000949 int odd_y;
Christian Heimes53876d92008-04-19 00:31:39 +0000950
951 if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy))
952 return NULL;
953 x = PyFloat_AsDouble(ox);
954 y = PyFloat_AsDouble(oy);
955 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
956 return NULL;
Christian Heimesa342c012008-04-20 21:01:16 +0000957
958 /* deal directly with IEEE specials, to cope with problems on various
959 platforms whose semantics don't exactly match C99 */
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000960 r = 0.; /* silence compiler warning */
Christian Heimesa342c012008-04-20 21:01:16 +0000961 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
962 errno = 0;
963 if (Py_IS_NAN(x))
964 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
965 else if (Py_IS_NAN(y))
966 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
967 else if (Py_IS_INFINITY(x)) {
968 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
969 if (y > 0.)
970 r = odd_y ? x : fabs(x);
971 else if (y == 0.)
972 r = 1.;
973 else /* y < 0. */
974 r = odd_y ? copysign(0., x) : 0.;
975 }
976 else if (Py_IS_INFINITY(y)) {
977 if (fabs(x) == 1.0)
978 r = 1.;
979 else if (y > 0. && fabs(x) > 1.0)
980 r = y;
981 else if (y < 0. && fabs(x) < 1.0) {
982 r = -y; /* result is +inf */
983 if (x == 0.) /* 0**-inf: divide-by-zero */
984 errno = EDOM;
985 }
986 else
987 r = 0.;
988 }
Christian Heimes53876d92008-04-19 00:31:39 +0000989 }
Christian Heimesa342c012008-04-20 21:01:16 +0000990 else {
991 /* let libm handle finite**finite */
992 errno = 0;
993 PyFPE_START_PROTECT("in math_pow", return 0);
994 r = pow(x, y);
995 PyFPE_END_PROTECT(r);
996 /* a NaN result should arise only from (-ve)**(finite
997 non-integer); in this case we want to raise ValueError. */
998 if (!Py_IS_FINITE(r)) {
999 if (Py_IS_NAN(r)) {
1000 errno = EDOM;
1001 }
1002 /*
1003 an infinite result here arises either from:
1004 (A) (+/-0.)**negative (-> divide-by-zero)
1005 (B) overflow of x**y with x and y finite
1006 */
1007 else if (Py_IS_INFINITY(r)) {
1008 if (x == 0.)
1009 errno = EDOM;
1010 else
1011 errno = ERANGE;
1012 }
1013 }
Christian Heimes53876d92008-04-19 00:31:39 +00001014 }
1015
1016 if (errno && is_error(r))
1017 return NULL;
1018 else
1019 return PyFloat_FromDouble(r);
1020}
1021
1022PyDoc_STRVAR(math_pow_doc,
1023"pow(x,y)\n\nReturn x**y (x to the power of y).");
1024
Christian Heimes072c0f12008-01-03 23:01:04 +00001025static const double degToRad = Py_MATH_PI / 180.0;
1026static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001027
1028static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001029math_degrees(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001030{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001031 double x = PyFloat_AsDouble(arg);
1032 if (x == -1.0 && PyErr_Occurred())
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001033 return NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +00001034 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001035}
1036
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001037PyDoc_STRVAR(math_degrees_doc,
1038"degrees(x) -> converts angle x from radians to degrees");
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001039
1040static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001041math_radians(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001042{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001043 double x = PyFloat_AsDouble(arg);
1044 if (x == -1.0 && PyErr_Occurred())
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001045 return NULL;
1046 return PyFloat_FromDouble(x * degToRad);
1047}
1048
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001049PyDoc_STRVAR(math_radians_doc,
1050"radians(x) -> converts angle x from degrees to radians");
Tim Peters78526162001-09-05 00:53:45 +00001051
Christian Heimes072c0f12008-01-03 23:01:04 +00001052static PyObject *
1053math_isnan(PyObject *self, PyObject *arg)
1054{
1055 double x = PyFloat_AsDouble(arg);
1056 if (x == -1.0 && PyErr_Occurred())
1057 return NULL;
1058 return PyBool_FromLong((long)Py_IS_NAN(x));
1059}
1060
1061PyDoc_STRVAR(math_isnan_doc,
1062"isnan(x) -> bool\n\
1063Checks if float x is not a number (NaN)");
1064
1065static PyObject *
1066math_isinf(PyObject *self, PyObject *arg)
1067{
1068 double x = PyFloat_AsDouble(arg);
1069 if (x == -1.0 && PyErr_Occurred())
1070 return NULL;
1071 return PyBool_FromLong((long)Py_IS_INFINITY(x));
1072}
1073
1074PyDoc_STRVAR(math_isinf_doc,
1075"isinf(x) -> bool\n\
1076Checks if float x is infinite (positive or negative)");
1077
Barry Warsaw8b43b191996-12-09 22:32:36 +00001078static PyMethodDef math_methods[] = {
Thomas Wouters89f507f2006-12-13 04:49:30 +00001079 {"acos", math_acos, METH_O, math_acos_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001080 {"acosh", math_acosh, METH_O, math_acosh_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001081 {"asin", math_asin, METH_O, math_asin_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001082 {"asinh", math_asinh, METH_O, math_asinh_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001083 {"atan", math_atan, METH_O, math_atan_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001084 {"atan2", math_atan2, METH_VARARGS, math_atan2_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001085 {"atanh", math_atanh, METH_O, math_atanh_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001086 {"ceil", math_ceil, METH_O, math_ceil_doc},
Christian Heimes072c0f12008-01-03 23:01:04 +00001087 {"copysign", math_copysign, METH_VARARGS, math_copysign_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001088 {"cos", math_cos, METH_O, math_cos_doc},
1089 {"cosh", math_cosh, METH_O, math_cosh_doc},
1090 {"degrees", math_degrees, METH_O, math_degrees_doc},
1091 {"exp", math_exp, METH_O, math_exp_doc},
1092 {"fabs", math_fabs, METH_O, math_fabs_doc},
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001093 {"factorial", math_factorial, METH_O, math_factorial_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001094 {"floor", math_floor, METH_O, math_floor_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001095 {"fmod", math_fmod, METH_VARARGS, math_fmod_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001096 {"frexp", math_frexp, METH_O, math_frexp_doc},
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001097 {"fsum", math_fsum, METH_O, math_fsum_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001098 {"hypot", math_hypot, METH_VARARGS, math_hypot_doc},
Christian Heimes072c0f12008-01-03 23:01:04 +00001099 {"isinf", math_isinf, METH_O, math_isinf_doc},
1100 {"isnan", math_isnan, METH_O, math_isnan_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001101 {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc},
1102 {"log", math_log, METH_VARARGS, math_log_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001103 {"log1p", math_log1p, METH_O, math_log1p_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001104 {"log10", math_log10, METH_O, math_log10_doc},
1105 {"modf", math_modf, METH_O, math_modf_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001106 {"pow", math_pow, METH_VARARGS, math_pow_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001107 {"radians", math_radians, METH_O, math_radians_doc},
1108 {"sin", math_sin, METH_O, math_sin_doc},
1109 {"sinh", math_sinh, METH_O, math_sinh_doc},
1110 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
1111 {"tan", math_tan, METH_O, math_tan_doc},
1112 {"tanh", math_tanh, METH_O, math_tanh_doc},
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001113 {"trunc", math_trunc, METH_O, math_trunc_doc},
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001114 {NULL, NULL} /* sentinel */
1115};
1116
Guido van Rossumc6e22901998-12-04 19:26:43 +00001117
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001118PyDoc_STRVAR(module_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001119"This module is always available. It provides access to the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001120"mathematical functions defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001121
Martin v. Löwis1a214512008-06-11 05:26:20 +00001122
1123static struct PyModuleDef mathmodule = {
1124 PyModuleDef_HEAD_INIT,
1125 "math",
1126 module_doc,
1127 -1,
1128 math_methods,
1129 NULL,
1130 NULL,
1131 NULL,
1132 NULL
1133};
1134
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001135PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001136PyInit_math(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001137{
Christian Heimes53876d92008-04-19 00:31:39 +00001138 PyObject *m;
Tim Petersfe71f812001-08-07 22:10:00 +00001139
Martin v. Löwis1a214512008-06-11 05:26:20 +00001140 m = PyModule_Create(&mathmodule);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00001141 if (m == NULL)
1142 goto finally;
Barry Warsawfc93f751996-12-17 00:47:03 +00001143
Christian Heimes53876d92008-04-19 00:31:39 +00001144 PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
1145 PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
Barry Warsawfc93f751996-12-17 00:47:03 +00001146
Christian Heimes53876d92008-04-19 00:31:39 +00001147 finally:
Martin v. Löwis1a214512008-06-11 05:26:20 +00001148 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001149}