blob: 05bad5de6e4dd58597031f466b0c96507694e0cb [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{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000070 int result = 1; /* presumption of guilt */
71 assert(errno); /* non-zero errno is a precondition for calling */
72 if (errno == EDOM)
73 PyErr_SetString(PyExc_ValueError, "math domain error");
Tim Petersa40c7932001-09-05 22:36:56 +000074
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +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
79 * 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).
85 *
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.
90 */
91 if (fabs(x) < 1.0)
92 result = 0;
93 else
94 PyErr_SetString(PyExc_OverflowError,
95 "math range error");
96 }
97 else
98 /* Unexpected math error */
99 PyErr_SetFromErrno(PyExc_ValueError);
100 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{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000114 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);
Christian Heimese57950f2008-04-21 13:08:03 +0000137}
138
139/*
Mark Dickinsone675f082008-12-11 21:56:00 +0000140 Various platforms (Solaris, OpenBSD) do nonstandard things for log(0),
141 log(-ve), log(NaN). Here are wrappers for log and log10 that deal with
142 special values directly, passing positive non-special values through to
143 the system log/log10.
144 */
145
146static double
147m_log(double x)
148{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000149 if (Py_IS_FINITE(x)) {
150 if (x > 0.0)
151 return log(x);
152 errno = EDOM;
153 if (x == 0.0)
154 return -Py_HUGE_VAL; /* log(0) = -inf */
155 else
156 return Py_NAN; /* log(-ve) = nan */
157 }
158 else if (Py_IS_NAN(x))
159 return x; /* log(nan) = nan */
160 else if (x > 0.0)
161 return x; /* log(inf) = inf */
162 else {
163 errno = EDOM;
164 return Py_NAN; /* log(-inf) = nan */
165 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000166}
167
168static double
169m_log10(double x)
170{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000171 if (Py_IS_FINITE(x)) {
172 if (x > 0.0)
173 return log10(x);
174 errno = EDOM;
175 if (x == 0.0)
176 return -Py_HUGE_VAL; /* log10(0) = -inf */
177 else
178 return Py_NAN; /* log10(-ve) = nan */
179 }
180 else if (Py_IS_NAN(x))
181 return x; /* log10(nan) = nan */
182 else if (x > 0.0)
183 return x; /* log10(inf) = inf */
184 else {
185 errno = EDOM;
186 return Py_NAN; /* log10(-inf) = nan */
187 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000188}
189
190
191/*
Christian Heimes53876d92008-04-19 00:31:39 +0000192 math_1 is used to wrap a libm function f that takes a double
193 arguments and returns a double.
194
195 The error reporting follows these rules, which are designed to do
196 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
197 platforms.
198
199 - a NaN result from non-NaN inputs causes ValueError to be raised
200 - an infinite result from finite inputs causes OverflowError to be
201 raised if can_overflow is 1, or raises ValueError if can_overflow
202 is 0.
203 - if the result is finite and errno == EDOM then ValueError is
204 raised
205 - if the result is finite and nonzero and errno == ERANGE then
206 OverflowError is raised
207
208 The last rule is used to catch overflow on platforms which follow
209 C89 but for which HUGE_VAL is not an infinity.
210
211 For the majority of one-argument functions these rules are enough
212 to ensure that Python's functions behave as specified in 'Annex F'
213 of the C99 standard, with the 'invalid' and 'divide-by-zero'
214 floating-point exceptions mapping to Python's ValueError and the
215 'overflow' floating-point exception mapping to OverflowError.
216 math_1 only works for functions that don't have singularities *and*
217 the possibility of overflow; fortunately, that covers everything we
218 care about right now.
219*/
220
Barry Warsaw8b43b191996-12-09 22:32:36 +0000221static PyObject *
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000222math_1_to_whatever(PyObject *arg, double (*func) (double),
Christian Heimes53876d92008-04-19 00:31:39 +0000223 PyObject *(*from_double_func) (double),
224 int can_overflow)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000225{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000226 double x, r;
227 x = PyFloat_AsDouble(arg);
228 if (x == -1.0 && PyErr_Occurred())
229 return NULL;
230 errno = 0;
231 PyFPE_START_PROTECT("in math_1", return 0);
232 r = (*func)(x);
233 PyFPE_END_PROTECT(r);
234 if (Py_IS_NAN(r) && !Py_IS_NAN(x)) {
235 PyErr_SetString(PyExc_ValueError,
236 "math domain error"); /* invalid arg */
237 return NULL;
238 }
239 if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) {
240 if (can_overflow)
241 PyErr_SetString(PyExc_OverflowError,
242 "math range error"); /* overflow */
243 else
244 PyErr_SetString(PyExc_ValueError,
245 "math domain error"); /* singularity */
246 return NULL;
247 }
248 if (Py_IS_FINITE(r) && errno && is_error(r))
249 /* this branch unnecessary on most platforms */
250 return NULL;
Mark Dickinsonde429622008-05-01 00:19:23 +0000251
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000252 return (*from_double_func)(r);
Christian Heimes53876d92008-04-19 00:31:39 +0000253}
254
255/*
256 math_2 is used to wrap a libm function f that takes two double
257 arguments and returns a double.
258
259 The error reporting follows these rules, which are designed to do
260 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
261 platforms.
262
263 - a NaN result from non-NaN inputs causes ValueError to be raised
264 - an infinite result from finite inputs causes OverflowError to be
265 raised.
266 - if the result is finite and errno == EDOM then ValueError is
267 raised
268 - if the result is finite and nonzero and errno == ERANGE then
269 OverflowError is raised
270
271 The last rule is used to catch overflow on platforms which follow
272 C89 but for which HUGE_VAL is not an infinity.
273
274 For most two-argument functions (copysign, fmod, hypot, atan2)
275 these rules are enough to ensure that Python's functions behave as
276 specified in 'Annex F' of the C99 standard, with the 'invalid' and
277 'divide-by-zero' floating-point exceptions mapping to Python's
278 ValueError and the 'overflow' floating-point exception mapping to
279 OverflowError.
280*/
281
282static PyObject *
283math_1(PyObject *arg, double (*func) (double), int can_overflow)
284{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000285 return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow);
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000286}
287
288static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000289math_1_to_int(PyObject *arg, double (*func) (double), int can_overflow)
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000290{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000291 return math_1_to_whatever(arg, func, PyLong_FromDouble, can_overflow);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000292}
293
Barry Warsaw8b43b191996-12-09 22:32:36 +0000294static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +0000295math_2(PyObject *args, double (*func) (double, double), char *funcname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000296{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000297 PyObject *ox, *oy;
298 double x, y, r;
299 if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy))
300 return NULL;
301 x = PyFloat_AsDouble(ox);
302 y = PyFloat_AsDouble(oy);
303 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
304 return NULL;
305 errno = 0;
306 PyFPE_START_PROTECT("in math_2", return 0);
307 r = (*func)(x, y);
308 PyFPE_END_PROTECT(r);
309 if (Py_IS_NAN(r)) {
310 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
311 errno = EDOM;
312 else
313 errno = 0;
314 }
315 else if (Py_IS_INFINITY(r)) {
316 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
317 errno = ERANGE;
318 else
319 errno = 0;
320 }
321 if (errno && is_error(r))
322 return NULL;
323 else
324 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000325}
326
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000327#define FUNC1(funcname, func, can_overflow, docstring) \
328 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
329 return math_1(args, func, can_overflow); \
330 }\
331 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000332
Fred Drake40c48682000-07-03 18:11:56 +0000333#define FUNC2(funcname, func, docstring) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000334 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
335 return math_2(args, func, #funcname); \
336 }\
337 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000338
Christian Heimes53876d92008-04-19 00:31:39 +0000339FUNC1(acos, acos, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000340 "acos(x)\n\nReturn the arc cosine (measured in radians) of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000341FUNC1(acosh, acosh, 0,
342 "acosh(x)\n\nReturn the hyperbolic arc cosine (measured in radians) of x.")
343FUNC1(asin, asin, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000344 "asin(x)\n\nReturn the arc sine (measured in radians) of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000345FUNC1(asinh, asinh, 0,
346 "asinh(x)\n\nReturn the hyperbolic arc sine (measured in radians) of x.")
347FUNC1(atan, atan, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000348 "atan(x)\n\nReturn the arc tangent (measured in radians) of x.")
Christian Heimese57950f2008-04-21 13:08:03 +0000349FUNC2(atan2, m_atan2,
Tim Petersfe71f812001-08-07 22:10:00 +0000350 "atan2(y, x)\n\nReturn the arc tangent (measured in radians) of y/x.\n"
351 "Unlike atan(y/x), the signs of both x and y are considered.")
Christian Heimes53876d92008-04-19 00:31:39 +0000352FUNC1(atanh, atanh, 0,
353 "atanh(x)\n\nReturn the hyperbolic arc tangent (measured in radians) of x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +0000354
355static PyObject * math_ceil(PyObject *self, PyObject *number) {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000356 static PyObject *ceil_str = NULL;
357 PyObject *method;
Guido van Rossum13e05de2007-08-23 22:56:55 +0000358
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000359 if (ceil_str == NULL) {
360 ceil_str = PyUnicode_InternFromString("__ceil__");
361 if (ceil_str == NULL)
362 return NULL;
363 }
Guido van Rossum13e05de2007-08-23 22:56:55 +0000364
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000365 method = _PyType_Lookup(Py_TYPE(number), ceil_str);
366 if (method == NULL)
367 return math_1_to_int(number, ceil, 0);
368 else
369 return PyObject_CallFunction(method, "O", number);
Guido van Rossum13e05de2007-08-23 22:56:55 +0000370}
371
372PyDoc_STRVAR(math_ceil_doc,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000373 "ceil(x)\n\nReturn the ceiling of x as an int.\n"
374 "This is the smallest integral value >= x.");
Guido van Rossum13e05de2007-08-23 22:56:55 +0000375
Christian Heimes072c0f12008-01-03 23:01:04 +0000376FUNC2(copysign, copysign,
Benjamin Peterson8f6713f2009-11-13 02:29:35 +0000377 "copysign(x, y)\n\nReturn x with the sign of y.")
Christian Heimes53876d92008-04-19 00:31:39 +0000378FUNC1(cos, cos, 0,
379 "cos(x)\n\nReturn the cosine of x (measured in radians).")
380FUNC1(cosh, cosh, 1,
381 "cosh(x)\n\nReturn the hyperbolic cosine of x.")
382FUNC1(exp, exp, 1,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000383 "exp(x)\n\nReturn e raised to the power of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000384FUNC1(fabs, fabs, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000385 "fabs(x)\n\nReturn the absolute value of the float x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +0000386
387static PyObject * math_floor(PyObject *self, PyObject *number) {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000388 static PyObject *floor_str = NULL;
389 PyObject *method;
Guido van Rossum13e05de2007-08-23 22:56:55 +0000390
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000391 if (floor_str == NULL) {
392 floor_str = PyUnicode_InternFromString("__floor__");
393 if (floor_str == NULL)
394 return NULL;
395 }
Guido van Rossum13e05de2007-08-23 22:56:55 +0000396
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000397 method = _PyType_Lookup(Py_TYPE(number), floor_str);
398 if (method == NULL)
399 return math_1_to_int(number, floor, 0);
400 else
401 return PyObject_CallFunction(method, "O", number);
Guido van Rossum13e05de2007-08-23 22:56:55 +0000402}
403
404PyDoc_STRVAR(math_floor_doc,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000405 "floor(x)\n\nReturn the floor of x as an int.\n"
406 "This is the largest integral value <= x.");
Guido van Rossum13e05de2007-08-23 22:56:55 +0000407
Christian Heimes53876d92008-04-19 00:31:39 +0000408FUNC1(log1p, log1p, 1,
Benjamin Peterson8f6713f2009-11-13 02:29:35 +0000409 "log1p(x)\n\nReturn the natural logarithm of 1+x (base e).\n"
410 "The result is computed in a way which is accurate for x near zero.")
Christian Heimes53876d92008-04-19 00:31:39 +0000411FUNC1(sin, sin, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000412 "sin(x)\n\nReturn the sine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +0000413FUNC1(sinh, sinh, 1,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000414 "sinh(x)\n\nReturn the hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000415FUNC1(sqrt, sqrt, 0,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000416 "sqrt(x)\n\nReturn the square root of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000417FUNC1(tan, tan, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000418 "tan(x)\n\nReturn the tangent of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +0000419FUNC1(tanh, tanh, 0,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000420 "tanh(x)\n\nReturn the hyperbolic tangent of x.")
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000421
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000422/* Precision summation function as msum() by Raymond Hettinger in
423 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
424 enhanced with the exact partials sum and roundoff from Mark
425 Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
426 See those links for more details, proofs and other references.
427
428 Note 1: IEEE 754R floating point semantics are assumed,
429 but the current implementation does not re-establish special
430 value semantics across iterations (i.e. handling -Inf + Inf).
431
432 Note 2: No provision is made for intermediate overflow handling;
Georg Brandlf78e02b2008-06-10 17:40:04 +0000433 therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000434 sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
435 overflow of the first partial sum.
436
Benjamin Petersonfea6a942008-07-02 16:11:42 +0000437 Note 3: The intermediate values lo, yr, and hi are declared volatile so
438 aggressive compilers won't algebraically reduce lo to always be exactly 0.0.
Georg Brandlf78e02b2008-06-10 17:40:04 +0000439 Also, the volatile declaration forces the values to be stored in memory as
440 regular doubles instead of extended long precision (80-bit) values. This
Benjamin Petersonfea6a942008-07-02 16:11:42 +0000441 prevents double rounding because any addition or subtraction of two doubles
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000442 can be resolved exactly into double-sized hi and lo values. As long as the
Georg Brandlf78e02b2008-06-10 17:40:04 +0000443 hi value gets forced into a double before yr and lo are computed, the extra
444 bits in downstream extended precision operations (x87 for example) will be
445 exactly zero and therefore can be losslessly stored back into a double,
446 thereby preventing double rounding.
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000447
448 Note 4: A similar implementation is in Modules/cmathmodule.c.
449 Be sure to update both when making changes.
450
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000451 Note 5: The signature of math.fsum() differs from __builtin__.sum()
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000452 because the start argument doesn't make sense in the context of
453 accurate summation. Since the partials table is collapsed before
454 returning a result, sum(seq2, start=sum(seq1)) may not equal the
455 accurate result returned by sum(itertools.chain(seq1, seq2)).
456*/
457
458#define NUM_PARTIALS 32 /* initial partials array size, on stack */
459
460/* Extend the partials array p[] by doubling its size. */
461static int /* non-zero on error */
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000462_fsum_realloc(double **p_ptr, Py_ssize_t n,
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000463 double *ps, Py_ssize_t *m_ptr)
464{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000465 void *v = NULL;
466 Py_ssize_t m = *m_ptr;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000467
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000468 m += m; /* double */
469 if (n < m && m < (PY_SSIZE_T_MAX / sizeof(double))) {
470 double *p = *p_ptr;
471 if (p == ps) {
472 v = PyMem_Malloc(sizeof(double) * m);
473 if (v != NULL)
474 memcpy(v, ps, sizeof(double) * n);
475 }
476 else
477 v = PyMem_Realloc(p, sizeof(double) * m);
478 }
479 if (v == NULL) { /* size overflow or no memory */
480 PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
481 return 1;
482 }
483 *p_ptr = (double*) v;
484 *m_ptr = m;
485 return 0;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000486}
487
488/* Full precision summation of a sequence of floats.
489
490 def msum(iterable):
491 partials = [] # sorted, non-overlapping partial sums
492 for x in iterable:
Mark Dickinsonb7620712010-06-25 20:23:41 +0000493 i = 0
494 for y in partials:
495 if abs(x) < abs(y):
496 x, y = y, x
497 hi = x + y
498 lo = y - (hi - x)
499 if lo:
500 partials[i] = lo
501 i += 1
502 x = hi
503 partials[i:] = [x]
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000504 return sum_exact(partials)
505
506 Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
507 are exactly equal to x+y. The inner loop applies hi/lo summation to each
508 partial so that the list of partial sums remains exact.
509
510 Sum_exact() adds the partial sums exactly and correctly rounds the final
511 result (using the round-half-to-even rule). The items in partials remain
512 non-zero, non-special, non-overlapping and strictly increasing in
513 magnitude, but possibly not all having the same sign.
514
515 Depends on IEEE 754 arithmetic guarantees and half-even rounding.
516*/
517
518static PyObject*
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000519math_fsum(PyObject *self, PyObject *seq)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000520{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000521 PyObject *item, *iter, *sum = NULL;
522 Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
523 double x, y, t, ps[NUM_PARTIALS], *p = ps;
524 double xsave, special_sum = 0.0, inf_sum = 0.0;
525 volatile double hi, yr, lo;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000526
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000527 iter = PyObject_GetIter(seq);
528 if (iter == NULL)
529 return NULL;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000530
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000531 PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000532
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000533 for(;;) { /* for x in iterable */
534 assert(0 <= n && n <= m);
535 assert((m == NUM_PARTIALS && p == ps) ||
536 (m > NUM_PARTIALS && p != NULL));
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000537
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000538 item = PyIter_Next(iter);
539 if (item == NULL) {
540 if (PyErr_Occurred())
541 goto _fsum_error;
542 break;
543 }
544 x = PyFloat_AsDouble(item);
545 Py_DECREF(item);
546 if (PyErr_Occurred())
547 goto _fsum_error;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000548
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000549 xsave = x;
550 for (i = j = 0; j < n; j++) { /* for y in partials */
551 y = p[j];
552 if (fabs(x) < fabs(y)) {
553 t = x; x = y; y = t;
554 }
555 hi = x + y;
556 yr = hi - x;
557 lo = y - yr;
558 if (lo != 0.0)
559 p[i++] = lo;
560 x = hi;
561 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000562
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000563 n = i; /* ps[i:] = [x] */
564 if (x != 0.0) {
565 if (! Py_IS_FINITE(x)) {
566 /* a nonfinite x could arise either as
567 a result of intermediate overflow, or
568 as a result of a nan or inf in the
569 summands */
570 if (Py_IS_FINITE(xsave)) {
571 PyErr_SetString(PyExc_OverflowError,
572 "intermediate overflow in fsum");
573 goto _fsum_error;
574 }
575 if (Py_IS_INFINITY(xsave))
576 inf_sum += xsave;
577 special_sum += xsave;
578 /* reset partials */
579 n = 0;
580 }
581 else if (n >= m && _fsum_realloc(&p, n, ps, &m))
582 goto _fsum_error;
583 else
584 p[n++] = x;
585 }
586 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000587
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000588 if (special_sum != 0.0) {
589 if (Py_IS_NAN(inf_sum))
590 PyErr_SetString(PyExc_ValueError,
591 "-inf + inf in fsum");
592 else
593 sum = PyFloat_FromDouble(special_sum);
594 goto _fsum_error;
595 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000596
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000597 hi = 0.0;
598 if (n > 0) {
599 hi = p[--n];
600 /* sum_exact(ps, hi) from the top, stop when the sum becomes
601 inexact. */
602 while (n > 0) {
603 x = hi;
604 y = p[--n];
605 assert(fabs(y) < fabs(x));
606 hi = x + y;
607 yr = hi - x;
608 lo = y - yr;
609 if (lo != 0.0)
610 break;
611 }
612 /* Make half-even rounding work across multiple partials.
613 Needed so that sum([1e-16, 1, 1e16]) will round-up the last
614 digit to two instead of down to zero (the 1e-16 makes the 1
615 slightly closer to two). With a potential 1 ULP rounding
616 error fixed-up, math.fsum() can guarantee commutativity. */
617 if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
618 (lo > 0.0 && p[n-1] > 0.0))) {
619 y = lo * 2.0;
620 x = hi + y;
621 yr = x - hi;
622 if (y == yr)
623 hi = x;
624 }
625 }
626 sum = PyFloat_FromDouble(hi);
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000627
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000628_fsum_error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000629 PyFPE_END_PROTECT(hi)
630 Py_DECREF(iter);
631 if (p != ps)
632 PyMem_Free(p);
633 return sum;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000634}
635
636#undef NUM_PARTIALS
637
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000638PyDoc_STRVAR(math_fsum_doc,
Benjamin Peterson8f6713f2009-11-13 02:29:35 +0000639"fsum(iterable)\n\n\
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000640Return an accurate floating point sum of values in the iterable.\n\
641Assumes IEEE-754 floating point arithmetic.");
642
Barry Warsaw8b43b191996-12-09 22:32:36 +0000643static PyObject *
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000644math_factorial(PyObject *self, PyObject *arg)
645{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000646 long i, x;
647 PyObject *result, *iobj, *newresult;
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000648
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000649 if (PyFloat_Check(arg)) {
650 double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
651 if (dx != floor(dx)) {
652 PyErr_SetString(PyExc_ValueError,
653 "factorial() only accepts integral values");
654 return NULL;
655 }
656 }
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000657
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000658 x = PyLong_AsLong(arg);
659 if (x == -1 && PyErr_Occurred())
660 return NULL;
661 if (x < 0) {
662 PyErr_SetString(PyExc_ValueError,
663 "factorial() not defined for negative values");
664 return NULL;
665 }
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000666
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000667 result = (PyObject *)PyLong_FromLong(1);
668 if (result == NULL)
669 return NULL;
670 for (i=1 ; i<=x ; i++) {
671 iobj = (PyObject *)PyLong_FromLong(i);
672 if (iobj == NULL)
673 goto error;
674 newresult = PyNumber_Multiply(result, iobj);
675 Py_DECREF(iobj);
676 if (newresult == NULL)
677 goto error;
678 Py_DECREF(result);
679 result = newresult;
680 }
681 return result;
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000682
683error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000684 Py_DECREF(result);
685 return NULL;
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000686}
687
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +0000688PyDoc_STRVAR(math_factorial_doc,
689"factorial(x) -> Integral\n"
690"\n"
691"Find x!. Raise a ValueError if x is negative or non-integral.");
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000692
693static PyObject *
Christian Heimes400adb02008-02-01 08:12:03 +0000694math_trunc(PyObject *self, PyObject *number)
695{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000696 static PyObject *trunc_str = NULL;
697 PyObject *trunc;
Christian Heimes400adb02008-02-01 08:12:03 +0000698
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000699 if (Py_TYPE(number)->tp_dict == NULL) {
700 if (PyType_Ready(Py_TYPE(number)) < 0)
701 return NULL;
702 }
Christian Heimes400adb02008-02-01 08:12:03 +0000703
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000704 if (trunc_str == NULL) {
705 trunc_str = PyUnicode_InternFromString("__trunc__");
706 if (trunc_str == NULL)
707 return NULL;
708 }
Christian Heimes400adb02008-02-01 08:12:03 +0000709
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000710 trunc = _PyType_Lookup(Py_TYPE(number), trunc_str);
711 if (trunc == NULL) {
712 PyErr_Format(PyExc_TypeError,
713 "type %.100s doesn't define __trunc__ method",
714 Py_TYPE(number)->tp_name);
715 return NULL;
716 }
717 return PyObject_CallFunctionObjArgs(trunc, number, NULL);
Christian Heimes400adb02008-02-01 08:12:03 +0000718}
719
720PyDoc_STRVAR(math_trunc_doc,
721"trunc(x:Real) -> Integral\n"
722"\n"
Christian Heimes292d3512008-02-03 16:51:08 +0000723"Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.");
Christian Heimes400adb02008-02-01 08:12:03 +0000724
725static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +0000726math_frexp(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +0000727{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000728 int i;
729 double x = PyFloat_AsDouble(arg);
730 if (x == -1.0 && PyErr_Occurred())
731 return NULL;
732 /* deal with special cases directly, to sidestep platform
733 differences */
734 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
735 i = 0;
736 }
737 else {
738 PyFPE_START_PROTECT("in math_frexp", return 0);
739 x = frexp(x, &i);
740 PyFPE_END_PROTECT(x);
741 }
742 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +0000743}
744
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000745PyDoc_STRVAR(math_frexp_doc,
Tim Peters63c94532001-09-04 23:17:42 +0000746"frexp(x)\n"
747"\n"
748"Return the mantissa and exponent of x, as pair (m, e).\n"
749"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 +0000750"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 +0000751
Barry Warsaw8b43b191996-12-09 22:32:36 +0000752static PyObject *
Fred Drake40c48682000-07-03 18:11:56 +0000753math_ldexp(PyObject *self, PyObject *args)
Guido van Rossumd18ad581991-10-24 14:57:21 +0000754{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000755 double x, r;
756 PyObject *oexp;
757 long exp;
758 if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp))
759 return NULL;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000760
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000761 if (PyLong_Check(oexp)) {
762 /* on overflow, replace exponent with either LONG_MAX
763 or LONG_MIN, depending on the sign. */
764 exp = PyLong_AsLong(oexp);
765 if (exp == -1 && PyErr_Occurred()) {
766 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
767 if (Py_SIZE(oexp) < 0) {
768 exp = LONG_MIN;
769 }
770 else {
771 exp = LONG_MAX;
772 }
773 PyErr_Clear();
774 }
775 else {
776 /* propagate any unexpected exception */
777 return NULL;
778 }
779 }
780 }
781 else {
782 PyErr_SetString(PyExc_TypeError,
783 "Expected an int or long as second argument "
784 "to ldexp.");
785 return NULL;
786 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000787
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000788 if (x == 0. || !Py_IS_FINITE(x)) {
789 /* NaNs, zeros and infinities are returned unchanged */
790 r = x;
791 errno = 0;
792 } else if (exp > INT_MAX) {
793 /* overflow */
794 r = copysign(Py_HUGE_VAL, x);
795 errno = ERANGE;
796 } else if (exp < INT_MIN) {
797 /* underflow to +-0 */
798 r = copysign(0., x);
799 errno = 0;
800 } else {
801 errno = 0;
802 PyFPE_START_PROTECT("in math_ldexp", return 0);
803 r = ldexp(x, (int)exp);
804 PyFPE_END_PROTECT(r);
805 if (Py_IS_INFINITY(r))
806 errno = ERANGE;
807 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000808
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000809 if (errno && is_error(r))
810 return NULL;
811 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +0000812}
813
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000814PyDoc_STRVAR(math_ldexp_doc,
Benjamin Peterson8f6713f2009-11-13 02:29:35 +0000815"ldexp(x, i)\n\n\
816Return x * (2**i).");
Guido van Rossumc6e22901998-12-04 19:26:43 +0000817
Barry Warsaw8b43b191996-12-09 22:32:36 +0000818static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +0000819math_modf(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +0000820{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000821 double y, x = PyFloat_AsDouble(arg);
822 if (x == -1.0 && PyErr_Occurred())
823 return NULL;
824 /* some platforms don't do the right thing for NaNs and
825 infinities, so we take care of special cases directly. */
826 if (!Py_IS_FINITE(x)) {
827 if (Py_IS_INFINITY(x))
828 return Py_BuildValue("(dd)", copysign(0., x), x);
829 else if (Py_IS_NAN(x))
830 return Py_BuildValue("(dd)", x, x);
831 }
Christian Heimesa342c012008-04-20 21:01:16 +0000832
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000833 errno = 0;
834 PyFPE_START_PROTECT("in math_modf", return 0);
835 x = modf(x, &y);
836 PyFPE_END_PROTECT(x);
837 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +0000838}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000839
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000840PyDoc_STRVAR(math_modf_doc,
Tim Peters63c94532001-09-04 23:17:42 +0000841"modf(x)\n"
842"\n"
843"Return the fractional and integer parts of x. Both results carry the sign\n"
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +0000844"of x and are floats.");
Guido van Rossumc6e22901998-12-04 19:26:43 +0000845
Tim Peters78526162001-09-05 00:53:45 +0000846/* A decent logarithm is easy to compute even for huge longs, but libm can't
847 do that by itself -- loghelper can. func is log or log10, and name is
848 "log" or "log10". Note that overflow isn't possible: a long can contain
849 no more than INT_MAX * SHIFT bits, so has value certainly less than
850 2**(2**64 * 2**16) == 2**2**80, and log2 of that is 2**80, which is
851 small enough to fit in an IEEE single. log and log10 are even smaller.
852*/
853
854static PyObject*
Thomas Wouters89f507f2006-12-13 04:49:30 +0000855loghelper(PyObject* arg, double (*func)(double), char *funcname)
Tim Peters78526162001-09-05 00:53:45 +0000856{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000857 /* If it is long, do it ourselves. */
858 if (PyLong_Check(arg)) {
859 double x;
860 int e;
861 x = _PyLong_AsScaledDouble(arg, &e);
862 if (x <= 0.0) {
863 PyErr_SetString(PyExc_ValueError,
864 "math domain error");
865 return NULL;
866 }
867 /* Value is ~= x * 2**(e*PyLong_SHIFT), so the log ~=
868 log(x) + log(2) * e * PyLong_SHIFT.
869 CAUTION: e*PyLong_SHIFT may overflow using int arithmetic,
870 so force use of double. */
871 x = func(x) + (e * (double)PyLong_SHIFT) * func(2.0);
872 return PyFloat_FromDouble(x);
873 }
Tim Peters78526162001-09-05 00:53:45 +0000874
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000875 /* Else let libm handle it by itself. */
876 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +0000877}
878
879static PyObject *
880math_log(PyObject *self, PyObject *args)
881{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000882 PyObject *arg;
883 PyObject *base = NULL;
884 PyObject *num, *den;
885 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +0000886
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000887 if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base))
888 return NULL;
Raymond Hettinger866964c2002-12-14 19:51:34 +0000889
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000890 num = loghelper(arg, m_log, "log");
891 if (num == NULL || base == NULL)
892 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +0000893
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000894 den = loghelper(base, m_log, "log");
895 if (den == NULL) {
896 Py_DECREF(num);
897 return NULL;
898 }
Raymond Hettinger866964c2002-12-14 19:51:34 +0000899
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000900 ans = PyNumber_TrueDivide(num, den);
901 Py_DECREF(num);
902 Py_DECREF(den);
903 return ans;
Tim Peters78526162001-09-05 00:53:45 +0000904}
905
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000906PyDoc_STRVAR(math_log_doc,
Benjamin Peterson8f6713f2009-11-13 02:29:35 +0000907"log(x[, base])\n\n\
908Return the logarithm of x to the given base.\n\
Raymond Hettinger866964c2002-12-14 19:51:34 +0000909If the base not specified, returns the natural logarithm (base e) of x.");
Tim Peters78526162001-09-05 00:53:45 +0000910
911static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +0000912math_log10(PyObject *self, PyObject *arg)
Tim Peters78526162001-09-05 00:53:45 +0000913{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000914 return loghelper(arg, m_log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +0000915}
916
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000917PyDoc_STRVAR(math_log10_doc,
Benjamin Peterson8f6713f2009-11-13 02:29:35 +0000918"log10(x)\n\nReturn the base 10 logarithm of x.");
Tim Peters78526162001-09-05 00:53:45 +0000919
Christian Heimes53876d92008-04-19 00:31:39 +0000920static PyObject *
921math_fmod(PyObject *self, PyObject *args)
922{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000923 PyObject *ox, *oy;
924 double r, x, y;
925 if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy))
926 return NULL;
927 x = PyFloat_AsDouble(ox);
928 y = PyFloat_AsDouble(oy);
929 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
930 return NULL;
931 /* fmod(x, +/-Inf) returns x for finite x. */
932 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
933 return PyFloat_FromDouble(x);
934 errno = 0;
935 PyFPE_START_PROTECT("in math_fmod", return 0);
936 r = fmod(x, y);
937 PyFPE_END_PROTECT(r);
938 if (Py_IS_NAN(r)) {
939 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
940 errno = EDOM;
941 else
942 errno = 0;
943 }
944 if (errno && is_error(r))
945 return NULL;
946 else
947 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +0000948}
949
950PyDoc_STRVAR(math_fmod_doc,
Benjamin Peterson8f6713f2009-11-13 02:29:35 +0000951"fmod(x, y)\n\nReturn fmod(x, y), according to platform C."
Christian Heimes53876d92008-04-19 00:31:39 +0000952" x % y may differ.");
953
954static PyObject *
955math_hypot(PyObject *self, PyObject *args)
956{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000957 PyObject *ox, *oy;
958 double r, x, y;
959 if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy))
960 return NULL;
961 x = PyFloat_AsDouble(ox);
962 y = PyFloat_AsDouble(oy);
963 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
964 return NULL;
965 /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */
966 if (Py_IS_INFINITY(x))
967 return PyFloat_FromDouble(fabs(x));
968 if (Py_IS_INFINITY(y))
969 return PyFloat_FromDouble(fabs(y));
970 errno = 0;
971 PyFPE_START_PROTECT("in math_hypot", return 0);
972 r = hypot(x, y);
973 PyFPE_END_PROTECT(r);
974 if (Py_IS_NAN(r)) {
975 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
976 errno = EDOM;
977 else
978 errno = 0;
979 }
980 else if (Py_IS_INFINITY(r)) {
981 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
982 errno = ERANGE;
983 else
984 errno = 0;
985 }
986 if (errno && is_error(r))
987 return NULL;
988 else
989 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +0000990}
991
992PyDoc_STRVAR(math_hypot_doc,
Benjamin Peterson8f6713f2009-11-13 02:29:35 +0000993"hypot(x, y)\n\nReturn the Euclidean distance, sqrt(x*x + y*y).");
Christian Heimes53876d92008-04-19 00:31:39 +0000994
995/* pow can't use math_2, but needs its own wrapper: the problem is
996 that an infinite result can arise either as a result of overflow
997 (in which case OverflowError should be raised) or as a result of
998 e.g. 0.**-5. (for which ValueError needs to be raised.)
999*/
1000
1001static PyObject *
1002math_pow(PyObject *self, PyObject *args)
1003{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001004 PyObject *ox, *oy;
1005 double r, x, y;
1006 int odd_y;
Christian Heimes53876d92008-04-19 00:31:39 +00001007
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001008 if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy))
1009 return NULL;
1010 x = PyFloat_AsDouble(ox);
1011 y = PyFloat_AsDouble(oy);
1012 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1013 return NULL;
Christian Heimesa342c012008-04-20 21:01:16 +00001014
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001015 /* deal directly with IEEE specials, to cope with problems on various
1016 platforms whose semantics don't exactly match C99 */
1017 r = 0.; /* silence compiler warning */
1018 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
1019 errno = 0;
1020 if (Py_IS_NAN(x))
1021 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
1022 else if (Py_IS_NAN(y))
1023 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
1024 else if (Py_IS_INFINITY(x)) {
1025 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
1026 if (y > 0.)
1027 r = odd_y ? x : fabs(x);
1028 else if (y == 0.)
1029 r = 1.;
1030 else /* y < 0. */
1031 r = odd_y ? copysign(0., x) : 0.;
1032 }
1033 else if (Py_IS_INFINITY(y)) {
1034 if (fabs(x) == 1.0)
1035 r = 1.;
1036 else if (y > 0. && fabs(x) > 1.0)
1037 r = y;
1038 else if (y < 0. && fabs(x) < 1.0) {
1039 r = -y; /* result is +inf */
1040 if (x == 0.) /* 0**-inf: divide-by-zero */
1041 errno = EDOM;
1042 }
1043 else
1044 r = 0.;
1045 }
1046 }
1047 else {
1048 /* let libm handle finite**finite */
1049 errno = 0;
1050 PyFPE_START_PROTECT("in math_pow", return 0);
1051 r = pow(x, y);
1052 PyFPE_END_PROTECT(r);
1053 /* a NaN result should arise only from (-ve)**(finite
1054 non-integer); in this case we want to raise ValueError. */
1055 if (!Py_IS_FINITE(r)) {
1056 if (Py_IS_NAN(r)) {
1057 errno = EDOM;
1058 }
1059 /*
1060 an infinite result here arises either from:
1061 (A) (+/-0.)**negative (-> divide-by-zero)
1062 (B) overflow of x**y with x and y finite
1063 */
1064 else if (Py_IS_INFINITY(r)) {
1065 if (x == 0.)
1066 errno = EDOM;
1067 else
1068 errno = ERANGE;
1069 }
1070 }
1071 }
Christian Heimes53876d92008-04-19 00:31:39 +00001072
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001073 if (errno && is_error(r))
1074 return NULL;
1075 else
1076 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00001077}
1078
1079PyDoc_STRVAR(math_pow_doc,
Benjamin Peterson8f6713f2009-11-13 02:29:35 +00001080"pow(x, y)\n\nReturn x**y (x to the power of y).");
Christian Heimes53876d92008-04-19 00:31:39 +00001081
Christian Heimes072c0f12008-01-03 23:01:04 +00001082static const double degToRad = Py_MATH_PI / 180.0;
1083static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001084
1085static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001086math_degrees(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001087{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001088 double x = PyFloat_AsDouble(arg);
1089 if (x == -1.0 && PyErr_Occurred())
1090 return NULL;
1091 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001092}
1093
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001094PyDoc_STRVAR(math_degrees_doc,
Benjamin Peterson8f6713f2009-11-13 02:29:35 +00001095"degrees(x)\n\n\
1096Convert angle x from radians to degrees.");
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001097
1098static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001099math_radians(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001100{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001101 double x = PyFloat_AsDouble(arg);
1102 if (x == -1.0 && PyErr_Occurred())
1103 return NULL;
1104 return PyFloat_FromDouble(x * degToRad);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001105}
1106
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001107PyDoc_STRVAR(math_radians_doc,
Benjamin Peterson8f6713f2009-11-13 02:29:35 +00001108"radians(x)\n\n\
1109Convert angle x from degrees to radians.");
Tim Peters78526162001-09-05 00:53:45 +00001110
Christian Heimes072c0f12008-01-03 23:01:04 +00001111static PyObject *
1112math_isnan(PyObject *self, PyObject *arg)
1113{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001114 double x = PyFloat_AsDouble(arg);
1115 if (x == -1.0 && PyErr_Occurred())
1116 return NULL;
1117 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00001118}
1119
1120PyDoc_STRVAR(math_isnan_doc,
Benjamin Peterson8f6713f2009-11-13 02:29:35 +00001121"isnan(x) -> bool\n\n\
1122Check if float x is not a number (NaN).");
Christian Heimes072c0f12008-01-03 23:01:04 +00001123
1124static PyObject *
1125math_isinf(PyObject *self, PyObject *arg)
1126{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001127 double x = PyFloat_AsDouble(arg);
1128 if (x == -1.0 && PyErr_Occurred())
1129 return NULL;
1130 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00001131}
1132
1133PyDoc_STRVAR(math_isinf_doc,
Benjamin Peterson8f6713f2009-11-13 02:29:35 +00001134"isinf(x) -> bool\n\n\
1135Check if float x is infinite (positive or negative).");
Christian Heimes072c0f12008-01-03 23:01:04 +00001136
Barry Warsaw8b43b191996-12-09 22:32:36 +00001137static PyMethodDef math_methods[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001138 {"acos", math_acos, METH_O, math_acos_doc},
1139 {"acosh", math_acosh, METH_O, math_acosh_doc},
1140 {"asin", math_asin, METH_O, math_asin_doc},
1141 {"asinh", math_asinh, METH_O, math_asinh_doc},
1142 {"atan", math_atan, METH_O, math_atan_doc},
1143 {"atan2", math_atan2, METH_VARARGS, math_atan2_doc},
1144 {"atanh", math_atanh, METH_O, math_atanh_doc},
1145 {"ceil", math_ceil, METH_O, math_ceil_doc},
1146 {"copysign", math_copysign, METH_VARARGS, math_copysign_doc},
1147 {"cos", math_cos, METH_O, math_cos_doc},
1148 {"cosh", math_cosh, METH_O, math_cosh_doc},
1149 {"degrees", math_degrees, METH_O, math_degrees_doc},
1150 {"exp", math_exp, METH_O, math_exp_doc},
1151 {"fabs", math_fabs, METH_O, math_fabs_doc},
1152 {"factorial", math_factorial, METH_O, math_factorial_doc},
1153 {"floor", math_floor, METH_O, math_floor_doc},
1154 {"fmod", math_fmod, METH_VARARGS, math_fmod_doc},
1155 {"frexp", math_frexp, METH_O, math_frexp_doc},
1156 {"fsum", math_fsum, METH_O, math_fsum_doc},
1157 {"hypot", math_hypot, METH_VARARGS, math_hypot_doc},
1158 {"isinf", math_isinf, METH_O, math_isinf_doc},
1159 {"isnan", math_isnan, METH_O, math_isnan_doc},
1160 {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc},
1161 {"log", math_log, METH_VARARGS, math_log_doc},
1162 {"log1p", math_log1p, METH_O, math_log1p_doc},
1163 {"log10", math_log10, METH_O, math_log10_doc},
1164 {"modf", math_modf, METH_O, math_modf_doc},
1165 {"pow", math_pow, METH_VARARGS, math_pow_doc},
1166 {"radians", math_radians, METH_O, math_radians_doc},
1167 {"sin", math_sin, METH_O, math_sin_doc},
1168 {"sinh", math_sinh, METH_O, math_sinh_doc},
1169 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
1170 {"tan", math_tan, METH_O, math_tan_doc},
1171 {"tanh", math_tanh, METH_O, math_tanh_doc},
1172 {"trunc", math_trunc, METH_O, math_trunc_doc},
1173 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001174};
1175
Guido van Rossumc6e22901998-12-04 19:26:43 +00001176
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001177PyDoc_STRVAR(module_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001178"This module is always available. It provides access to the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001179"mathematical functions defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001180
Martin v. Löwis1a214512008-06-11 05:26:20 +00001181
1182static struct PyModuleDef mathmodule = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001183 PyModuleDef_HEAD_INIT,
1184 "math",
1185 module_doc,
1186 -1,
1187 math_methods,
1188 NULL,
1189 NULL,
1190 NULL,
1191 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001192};
1193
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001194PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001195PyInit_math(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001196{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001197 PyObject *m;
Tim Petersfe71f812001-08-07 22:10:00 +00001198
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001199 m = PyModule_Create(&mathmodule);
1200 if (m == NULL)
1201 goto finally;
Barry Warsawfc93f751996-12-17 00:47:03 +00001202
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001203 PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
1204 PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
Barry Warsawfc93f751996-12-17 00:47:03 +00001205
Christian Heimes53876d92008-04-19 00:31:39 +00001206 finally:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001207 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001208}