blob: 1eb0c2be72073ae8754c715a8319f3aeb83ae114 [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/*
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{
149 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 }
166}
167
168static double
169m_log10(double x)
170{
171 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 }
188}
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{
Christian Heimes53876d92008-04-19 00:31:39 +0000226 double x, r;
227 x = PyFloat_AsDouble(arg);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000228 if (x == -1.0 && PyErr_Occurred())
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000229 return NULL;
230 errno = 0;
Christian Heimes53876d92008-04-19 00:31:39 +0000231 PyFPE_START_PROTECT("in math_1", return 0);
232 r = (*func)(x);
233 PyFPE_END_PROTECT(r);
Mark Dickinsona0de26c2008-04-30 23:30:57 +0000234 if (Py_IS_NAN(r) && !Py_IS_NAN(x)) {
235 PyErr_SetString(PyExc_ValueError,
Mark Dickinson66bada52008-06-18 10:04:31 +0000236 "math domain error"); /* invalid arg */
Mark Dickinsona0de26c2008-04-30 23:30:57 +0000237 return NULL;
Christian Heimes53876d92008-04-19 00:31:39 +0000238 }
Mark Dickinsona0de26c2008-04-30 23:30:57 +0000239 if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) {
240 if (can_overflow)
241 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson66bada52008-06-18 10:04:31 +0000242 "math range error"); /* overflow */
Mark Dickinsonb63aff12008-05-09 14:10:27 +0000243 else
244 PyErr_SetString(PyExc_ValueError,
Mark Dickinson66bada52008-06-18 10:04:31 +0000245 "math domain error"); /* singularity */
Mark Dickinsona0de26c2008-04-30 23:30:57 +0000246 return NULL;
Christian Heimes53876d92008-04-19 00:31:39 +0000247 }
Mark Dickinsonde429622008-05-01 00:19:23 +0000248 if (Py_IS_FINITE(r) && errno && is_error(r))
249 /* this branch unnecessary on most platforms */
Tim Peters1d120612000-10-12 06:10:25 +0000250 return NULL;
Mark Dickinsonde429622008-05-01 00:19:23 +0000251
252 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{
285 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{
Christian Heimes53876d92008-04-19 00:31:39 +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{
Thomas Wouters89f507f2006-12-13 04:49:30 +0000297 PyObject *ox, *oy;
Christian Heimes53876d92008-04-19 00:31:39 +0000298 double x, y, r;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000299 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())
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000304 return NULL;
305 errno = 0;
Christian Heimes53876d92008-04-19 00:31:39 +0000306 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))
Tim Peters1d120612000-10-12 06:10:25 +0000322 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000323 else
Christian Heimes53876d92008-04-19 00:31:39 +0000324 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000325}
326
Christian Heimes53876d92008-04-19 00:31:39 +0000327#define FUNC1(funcname, func, can_overflow, docstring) \
Fred Drake40c48682000-07-03 18:11:56 +0000328 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
Christian Heimes53876d92008-04-19 00:31:39 +0000329 return math_1(args, func, can_overflow); \
Guido van Rossumc6e22901998-12-04 19:26:43 +0000330 }\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000331 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) \
334 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
Thomas Wouters89f507f2006-12-13 04:49:30 +0000335 return math_2(args, func, #funcname); \
Guido van Rossumc6e22901998-12-04 19:26:43 +0000336 }\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000337 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) {
356 static PyObject *ceil_str = NULL;
357 PyObject *method;
358
359 if (ceil_str == NULL) {
Christian Heimesfe82e772008-01-28 02:38:20 +0000360 ceil_str = PyUnicode_InternFromString("__ceil__");
Guido van Rossum13e05de2007-08-23 22:56:55 +0000361 if (ceil_str == NULL)
362 return NULL;
363 }
364
Christian Heimes90aa7642007-12-19 02:45:37 +0000365 method = _PyType_Lookup(Py_TYPE(number), ceil_str);
Guido van Rossum13e05de2007-08-23 22:56:55 +0000366 if (method == NULL)
Christian Heimes53876d92008-04-19 00:31:39 +0000367 return math_1_to_int(number, ceil, 0);
Guido van Rossum13e05de2007-08-23 22:56:55 +0000368 else
369 return PyObject_CallFunction(method, "O", number);
370}
371
372PyDoc_STRVAR(math_ceil_doc,
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000373 "ceil(x)\n\nReturn the ceiling of x as an int.\n"
Guido van Rossum13e05de2007-08-23 22:56:55 +0000374 "This is the smallest integral value >= x.");
375
Christian Heimes072c0f12008-01-03 23:01:04 +0000376FUNC2(copysign, copysign,
Christian Heimes53876d92008-04-19 00:31:39 +0000377 "copysign(x,y)\n\nReturn x with the sign of y.")
378FUNC1(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) {
388 static PyObject *floor_str = NULL;
389 PyObject *method;
390
391 if (floor_str == NULL) {
Christian Heimesfe82e772008-01-28 02:38:20 +0000392 floor_str = PyUnicode_InternFromString("__floor__");
Guido van Rossum13e05de2007-08-23 22:56:55 +0000393 if (floor_str == NULL)
394 return NULL;
395 }
396
Christian Heimes90aa7642007-12-19 02:45:37 +0000397 method = _PyType_Lookup(Py_TYPE(number), floor_str);
Guido van Rossum13e05de2007-08-23 22:56:55 +0000398 if (method == NULL)
Christian Heimes53876d92008-04-19 00:31:39 +0000399 return math_1_to_int(number, floor, 0);
Guido van Rossum13e05de2007-08-23 22:56:55 +0000400 else
401 return PyObject_CallFunction(method, "O", number);
402}
403
404PyDoc_STRVAR(math_floor_doc,
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000405 "floor(x)\n\nReturn the floor of x as an int.\n"
Guido van Rossum13e05de2007-08-23 22:56:55 +0000406 "This is the largest integral value <= x.");
407
Christian Heimes53876d92008-04-19 00:31:39 +0000408FUNC1(log1p, log1p, 1,
409 "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.")
411FUNC1(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
Georg Brandlf78e02b2008-06-10 17:40:04 +0000442 can be resolved exactly into double-sized hi and lo values. As long as the
443 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{
465 void *v = NULL;
466 Py_ssize_t m = *m_ptr;
467
468 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 */
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000480 PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000481 return 1;
482 }
483 *p_ptr = (double*) v;
484 *m_ptr = m;
485 return 0;
486}
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:
493 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]
504 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{
521 PyObject *item, *iter, *sum = NULL;
522 Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
Georg Brandlf78e02b2008-06-10 17:40:04 +0000523 double x, y, t, ps[NUM_PARTIALS], *p = ps;
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000524 double xsave, special_sum = 0.0, inf_sum = 0.0;
Georg Brandlf78e02b2008-06-10 17:40:04 +0000525 volatile double hi, yr, lo;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000526
527 iter = PyObject_GetIter(seq);
528 if (iter == NULL)
529 return NULL;
530
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000531 PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000532
533 for(;;) { /* for x in iterable */
534 assert(0 <= n && n <= m);
535 assert((m == NUM_PARTIALS && p == ps) ||
536 (m > NUM_PARTIALS && p != NULL));
537
538 item = PyIter_Next(iter);
539 if (item == NULL) {
540 if (PyErr_Occurred())
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000541 goto _fsum_error;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000542 break;
543 }
544 x = PyFloat_AsDouble(item);
545 Py_DECREF(item);
546 if (PyErr_Occurred())
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000547 goto _fsum_error;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000548
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000549 xsave = x;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000550 for (i = j = 0; j < n; j++) { /* for y in partials */
551 y = p[j];
Georg Brandlf78e02b2008-06-10 17:40:04 +0000552 if (fabs(x) < fabs(y)) {
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000553 t = x; x = y; y = t;
Georg Brandlf78e02b2008-06-10 17:40:04 +0000554 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000555 hi = x + y;
Georg Brandlf78e02b2008-06-10 17:40:04 +0000556 yr = hi - x;
557 lo = y - yr;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000558 if (lo != 0.0)
559 p[i++] = lo;
560 x = hi;
561 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000562
563 n = i; /* ps[i:] = [x] */
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000564 if (x != 0.0) {
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000565 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 */
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000579 n = 0;
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000580 }
581 else if (n >= m && _fsum_realloc(&p, n, ps, &m))
582 goto _fsum_error;
583 else
584 p[n++] = x;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000585 }
586 }
587
Mark Dickinsonaa7633a2008-08-01 08:16:13 +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 }
596
Georg Brandlf78e02b2008-06-10 17:40:04 +0000597 hi = 0.0;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000598 if (n > 0) {
599 hi = p[--n];
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000600 /* 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;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000611 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000612 /* 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;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000624 }
625 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000626 sum = PyFloat_FromDouble(hi);
627
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000628_fsum_error:
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000629 PyFPE_END_PROTECT(hi)
630 Py_DECREF(iter);
631 if (p != ps)
632 PyMem_Free(p);
633 return sum;
634}
635
636#undef NUM_PARTIALS
637
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000638PyDoc_STRVAR(math_fsum_doc,
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000639"sum(iterable)\n\n\
640Return 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{
646 long i, x;
647 PyObject *result, *iobj, *newresult;
648
649 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 }
657
658 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 }
666
667 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;
682
683error:
684 Py_DECREF(result);
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000685 return NULL;
686}
687
688PyDoc_STRVAR(math_factorial_doc, "Return n!");
689
690static PyObject *
Christian Heimes400adb02008-02-01 08:12:03 +0000691math_trunc(PyObject *self, PyObject *number)
692{
693 static PyObject *trunc_str = NULL;
694 PyObject *trunc;
695
696 if (Py_TYPE(number)->tp_dict == NULL) {
697 if (PyType_Ready(Py_TYPE(number)) < 0)
698 return NULL;
699 }
700
701 if (trunc_str == NULL) {
702 trunc_str = PyUnicode_InternFromString("__trunc__");
703 if (trunc_str == NULL)
704 return NULL;
705 }
706
707 trunc = _PyType_Lookup(Py_TYPE(number), trunc_str);
708 if (trunc == NULL) {
709 PyErr_Format(PyExc_TypeError,
710 "type %.100s doesn't define __trunc__ method",
711 Py_TYPE(number)->tp_name);
712 return NULL;
713 }
714 return PyObject_CallFunctionObjArgs(trunc, number, NULL);
715}
716
717PyDoc_STRVAR(math_trunc_doc,
718"trunc(x:Real) -> Integral\n"
719"\n"
Christian Heimes292d3512008-02-03 16:51:08 +0000720"Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.");
Christian Heimes400adb02008-02-01 08:12:03 +0000721
722static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +0000723math_frexp(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +0000724{
Guido van Rossumd18ad581991-10-24 14:57:21 +0000725 int i;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000726 double x = PyFloat_AsDouble(arg);
727 if (x == -1.0 && PyErr_Occurred())
Guido van Rossumd18ad581991-10-24 14:57:21 +0000728 return NULL;
Christian Heimes53876d92008-04-19 00:31:39 +0000729 /* deal with special cases directly, to sidestep platform
730 differences */
731 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
732 i = 0;
733 }
734 else {
735 PyFPE_START_PROTECT("in math_frexp", return 0);
736 x = frexp(x, &i);
737 PyFPE_END_PROTECT(x);
738 }
739 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +0000740}
741
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000742PyDoc_STRVAR(math_frexp_doc,
Tim Peters63c94532001-09-04 23:17:42 +0000743"frexp(x)\n"
744"\n"
745"Return the mantissa and exponent of x, as pair (m, e).\n"
746"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 +0000747"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 +0000748
Barry Warsaw8b43b191996-12-09 22:32:36 +0000749static PyObject *
Fred Drake40c48682000-07-03 18:11:56 +0000750math_ldexp(PyObject *self, PyObject *args)
Guido van Rossumd18ad581991-10-24 14:57:21 +0000751{
Christian Heimes53876d92008-04-19 00:31:39 +0000752 double x, r;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000753 PyObject *oexp;
754 long exp;
755 if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp))
Guido van Rossumd18ad581991-10-24 14:57:21 +0000756 return NULL;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000757
758 if (PyLong_Check(oexp)) {
759 /* on overflow, replace exponent with either LONG_MAX
760 or LONG_MIN, depending on the sign. */
761 exp = PyLong_AsLong(oexp);
762 if (exp == -1 && PyErr_Occurred()) {
763 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
764 if (Py_SIZE(oexp) < 0) {
765 exp = LONG_MIN;
766 }
767 else {
768 exp = LONG_MAX;
769 }
770 PyErr_Clear();
771 }
772 else {
773 /* propagate any unexpected exception */
774 return NULL;
775 }
776 }
777 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000778 else {
779 PyErr_SetString(PyExc_TypeError,
780 "Expected an int or long as second argument "
781 "to ldexp.");
782 return NULL;
783 }
784
785 if (x == 0. || !Py_IS_FINITE(x)) {
786 /* NaNs, zeros and infinities are returned unchanged */
787 r = x;
Christian Heimes53876d92008-04-19 00:31:39 +0000788 errno = 0;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000789 } else if (exp > INT_MAX) {
790 /* overflow */
791 r = copysign(Py_HUGE_VAL, x);
792 errno = ERANGE;
793 } else if (exp < INT_MIN) {
794 /* underflow to +-0 */
795 r = copysign(0., x);
796 errno = 0;
797 } else {
798 errno = 0;
799 PyFPE_START_PROTECT("in math_ldexp", return 0);
800 r = ldexp(x, (int)exp);
801 PyFPE_END_PROTECT(r);
802 if (Py_IS_INFINITY(r))
803 errno = ERANGE;
804 }
805
Christian Heimes53876d92008-04-19 00:31:39 +0000806 if (errno && is_error(r))
Tim Peters1d120612000-10-12 06:10:25 +0000807 return NULL;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000808 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +0000809}
810
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000811PyDoc_STRVAR(math_ldexp_doc,
812"ldexp(x, i) -> x * (2**i)");
Guido van Rossumc6e22901998-12-04 19:26:43 +0000813
Barry Warsaw8b43b191996-12-09 22:32:36 +0000814static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +0000815math_modf(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +0000816{
Thomas Wouters89f507f2006-12-13 04:49:30 +0000817 double y, x = PyFloat_AsDouble(arg);
818 if (x == -1.0 && PyErr_Occurred())
Guido van Rossumd18ad581991-10-24 14:57:21 +0000819 return NULL;
Christian Heimesa342c012008-04-20 21:01:16 +0000820 /* some platforms don't do the right thing for NaNs and
821 infinities, so we take care of special cases directly. */
822 if (!Py_IS_FINITE(x)) {
823 if (Py_IS_INFINITY(x))
824 return Py_BuildValue("(dd)", copysign(0., x), x);
825 else if (Py_IS_NAN(x))
826 return Py_BuildValue("(dd)", x, x);
827 }
828
Guido van Rossumd18ad581991-10-24 14:57:21 +0000829 errno = 0;
Christian Heimes53876d92008-04-19 00:31:39 +0000830 PyFPE_START_PROTECT("in math_modf", return 0);
Guido van Rossumd18ad581991-10-24 14:57:21 +0000831 x = modf(x, &y);
Christian Heimes53876d92008-04-19 00:31:39 +0000832 PyFPE_END_PROTECT(x);
833 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +0000834}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000835
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000836PyDoc_STRVAR(math_modf_doc,
Tim Peters63c94532001-09-04 23:17:42 +0000837"modf(x)\n"
838"\n"
839"Return the fractional and integer parts of x. Both results carry the sign\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000840"of x. The integer part is returned as a real.");
Guido van Rossumc6e22901998-12-04 19:26:43 +0000841
Tim Peters78526162001-09-05 00:53:45 +0000842/* A decent logarithm is easy to compute even for huge longs, but libm can't
843 do that by itself -- loghelper can. func is log or log10, and name is
844 "log" or "log10". Note that overflow isn't possible: a long can contain
845 no more than INT_MAX * SHIFT bits, so has value certainly less than
846 2**(2**64 * 2**16) == 2**2**80, and log2 of that is 2**80, which is
847 small enough to fit in an IEEE single. log and log10 are even smaller.
848*/
849
850static PyObject*
Thomas Wouters89f507f2006-12-13 04:49:30 +0000851loghelper(PyObject* arg, double (*func)(double), char *funcname)
Tim Peters78526162001-09-05 00:53:45 +0000852{
Tim Peters78526162001-09-05 00:53:45 +0000853 /* If it is long, do it ourselves. */
854 if (PyLong_Check(arg)) {
855 double x;
856 int e;
857 x = _PyLong_AsScaledDouble(arg, &e);
858 if (x <= 0.0) {
859 PyErr_SetString(PyExc_ValueError,
860 "math domain error");
861 return NULL;
862 }
Christian Heimesaf98da12008-01-27 15:18:18 +0000863 /* Value is ~= x * 2**(e*PyLong_SHIFT), so the log ~=
864 log(x) + log(2) * e * PyLong_SHIFT.
865 CAUTION: e*PyLong_SHIFT may overflow using int arithmetic,
Tim Peters78526162001-09-05 00:53:45 +0000866 so force use of double. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000867 x = func(x) + (e * (double)PyLong_SHIFT) * func(2.0);
Tim Peters78526162001-09-05 00:53:45 +0000868 return PyFloat_FromDouble(x);
869 }
870
871 /* Else let libm handle it by itself. */
Christian Heimes53876d92008-04-19 00:31:39 +0000872 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +0000873}
874
875static PyObject *
876math_log(PyObject *self, PyObject *args)
877{
Raymond Hettinger866964c2002-12-14 19:51:34 +0000878 PyObject *arg;
879 PyObject *base = NULL;
880 PyObject *num, *den;
881 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +0000882
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000883 if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base))
Raymond Hettinger866964c2002-12-14 19:51:34 +0000884 return NULL;
Raymond Hettinger866964c2002-12-14 19:51:34 +0000885
Mark Dickinsone675f082008-12-11 21:56:00 +0000886 num = loghelper(arg, m_log, "log");
Thomas Wouters89f507f2006-12-13 04:49:30 +0000887 if (num == NULL || base == NULL)
888 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +0000889
Mark Dickinsone675f082008-12-11 21:56:00 +0000890 den = loghelper(base, m_log, "log");
Raymond Hettinger866964c2002-12-14 19:51:34 +0000891 if (den == NULL) {
892 Py_DECREF(num);
893 return NULL;
894 }
895
Neal Norwitzbcc0db82006-03-24 08:14:36 +0000896 ans = PyNumber_TrueDivide(num, den);
Raymond Hettinger866964c2002-12-14 19:51:34 +0000897 Py_DECREF(num);
898 Py_DECREF(den);
899 return ans;
Tim Peters78526162001-09-05 00:53:45 +0000900}
901
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000902PyDoc_STRVAR(math_log_doc,
Raymond Hettinger866964c2002-12-14 19:51:34 +0000903"log(x[, base]) -> the logarithm of x to the given base.\n\
904If the base not specified, returns the natural logarithm (base e) of x.");
Tim Peters78526162001-09-05 00:53:45 +0000905
906static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +0000907math_log10(PyObject *self, PyObject *arg)
Tim Peters78526162001-09-05 00:53:45 +0000908{
Mark Dickinsone675f082008-12-11 21:56:00 +0000909 return loghelper(arg, m_log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +0000910}
911
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000912PyDoc_STRVAR(math_log10_doc,
913"log10(x) -> the base 10 logarithm of x.");
Tim Peters78526162001-09-05 00:53:45 +0000914
Christian Heimes53876d92008-04-19 00:31:39 +0000915static PyObject *
916math_fmod(PyObject *self, PyObject *args)
917{
918 PyObject *ox, *oy;
919 double r, x, y;
920 if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy))
921 return NULL;
922 x = PyFloat_AsDouble(ox);
923 y = PyFloat_AsDouble(oy);
924 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
925 return NULL;
926 /* fmod(x, +/-Inf) returns x for finite x. */
927 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
928 return PyFloat_FromDouble(x);
929 errno = 0;
930 PyFPE_START_PROTECT("in math_fmod", return 0);
931 r = fmod(x, y);
932 PyFPE_END_PROTECT(r);
933 if (Py_IS_NAN(r)) {
934 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
935 errno = EDOM;
936 else
937 errno = 0;
938 }
939 if (errno && is_error(r))
940 return NULL;
941 else
942 return PyFloat_FromDouble(r);
943}
944
945PyDoc_STRVAR(math_fmod_doc,
946"fmod(x,y)\n\nReturn fmod(x, y), according to platform C."
947" x % y may differ.");
948
949static PyObject *
950math_hypot(PyObject *self, PyObject *args)
951{
952 PyObject *ox, *oy;
953 double r, x, y;
954 if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy))
955 return NULL;
956 x = PyFloat_AsDouble(ox);
957 y = PyFloat_AsDouble(oy);
958 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
959 return NULL;
960 /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */
961 if (Py_IS_INFINITY(x))
962 return PyFloat_FromDouble(fabs(x));
963 if (Py_IS_INFINITY(y))
964 return PyFloat_FromDouble(fabs(y));
965 errno = 0;
966 PyFPE_START_PROTECT("in math_hypot", return 0);
967 r = hypot(x, y);
968 PyFPE_END_PROTECT(r);
969 if (Py_IS_NAN(r)) {
970 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
971 errno = EDOM;
972 else
973 errno = 0;
974 }
975 else if (Py_IS_INFINITY(r)) {
976 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
977 errno = ERANGE;
978 else
979 errno = 0;
980 }
981 if (errno && is_error(r))
982 return NULL;
983 else
984 return PyFloat_FromDouble(r);
985}
986
987PyDoc_STRVAR(math_hypot_doc,
988"hypot(x,y)\n\nReturn the Euclidean distance, sqrt(x*x + y*y).");
989
990/* pow can't use math_2, but needs its own wrapper: the problem is
991 that an infinite result can arise either as a result of overflow
992 (in which case OverflowError should be raised) or as a result of
993 e.g. 0.**-5. (for which ValueError needs to be raised.)
994*/
995
996static PyObject *
997math_pow(PyObject *self, PyObject *args)
998{
999 PyObject *ox, *oy;
1000 double r, x, y;
Christian Heimesa342c012008-04-20 21:01:16 +00001001 int odd_y;
Christian Heimes53876d92008-04-19 00:31:39 +00001002
1003 if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy))
1004 return NULL;
1005 x = PyFloat_AsDouble(ox);
1006 y = PyFloat_AsDouble(oy);
1007 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1008 return NULL;
Christian Heimesa342c012008-04-20 21:01:16 +00001009
1010 /* deal directly with IEEE specials, to cope with problems on various
1011 platforms whose semantics don't exactly match C99 */
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001012 r = 0.; /* silence compiler warning */
Christian Heimesa342c012008-04-20 21:01:16 +00001013 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
1014 errno = 0;
1015 if (Py_IS_NAN(x))
1016 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
1017 else if (Py_IS_NAN(y))
1018 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
1019 else if (Py_IS_INFINITY(x)) {
1020 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
1021 if (y > 0.)
1022 r = odd_y ? x : fabs(x);
1023 else if (y == 0.)
1024 r = 1.;
1025 else /* y < 0. */
1026 r = odd_y ? copysign(0., x) : 0.;
1027 }
1028 else if (Py_IS_INFINITY(y)) {
1029 if (fabs(x) == 1.0)
1030 r = 1.;
1031 else if (y > 0. && fabs(x) > 1.0)
1032 r = y;
1033 else if (y < 0. && fabs(x) < 1.0) {
1034 r = -y; /* result is +inf */
1035 if (x == 0.) /* 0**-inf: divide-by-zero */
1036 errno = EDOM;
1037 }
1038 else
1039 r = 0.;
1040 }
Christian Heimes53876d92008-04-19 00:31:39 +00001041 }
Christian Heimesa342c012008-04-20 21:01:16 +00001042 else {
1043 /* let libm handle finite**finite */
1044 errno = 0;
1045 PyFPE_START_PROTECT("in math_pow", return 0);
1046 r = pow(x, y);
1047 PyFPE_END_PROTECT(r);
1048 /* a NaN result should arise only from (-ve)**(finite
1049 non-integer); in this case we want to raise ValueError. */
1050 if (!Py_IS_FINITE(r)) {
1051 if (Py_IS_NAN(r)) {
1052 errno = EDOM;
1053 }
1054 /*
1055 an infinite result here arises either from:
1056 (A) (+/-0.)**negative (-> divide-by-zero)
1057 (B) overflow of x**y with x and y finite
1058 */
1059 else if (Py_IS_INFINITY(r)) {
1060 if (x == 0.)
1061 errno = EDOM;
1062 else
1063 errno = ERANGE;
1064 }
1065 }
Christian Heimes53876d92008-04-19 00:31:39 +00001066 }
1067
1068 if (errno && is_error(r))
1069 return NULL;
1070 else
1071 return PyFloat_FromDouble(r);
1072}
1073
1074PyDoc_STRVAR(math_pow_doc,
1075"pow(x,y)\n\nReturn x**y (x to the power of y).");
1076
Christian Heimes072c0f12008-01-03 23:01:04 +00001077static const double degToRad = Py_MATH_PI / 180.0;
1078static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001079
1080static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001081math_degrees(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001082{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001083 double x = PyFloat_AsDouble(arg);
1084 if (x == -1.0 && PyErr_Occurred())
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001085 return NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +00001086 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001087}
1088
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001089PyDoc_STRVAR(math_degrees_doc,
1090"degrees(x) -> converts angle x from radians to degrees");
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001091
1092static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001093math_radians(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001094{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001095 double x = PyFloat_AsDouble(arg);
1096 if (x == -1.0 && PyErr_Occurred())
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001097 return NULL;
1098 return PyFloat_FromDouble(x * degToRad);
1099}
1100
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001101PyDoc_STRVAR(math_radians_doc,
1102"radians(x) -> converts angle x from degrees to radians");
Tim Peters78526162001-09-05 00:53:45 +00001103
Christian Heimes072c0f12008-01-03 23:01:04 +00001104static PyObject *
1105math_isnan(PyObject *self, PyObject *arg)
1106{
1107 double x = PyFloat_AsDouble(arg);
1108 if (x == -1.0 && PyErr_Occurred())
1109 return NULL;
1110 return PyBool_FromLong((long)Py_IS_NAN(x));
1111}
1112
1113PyDoc_STRVAR(math_isnan_doc,
1114"isnan(x) -> bool\n\
1115Checks if float x is not a number (NaN)");
1116
1117static PyObject *
1118math_isinf(PyObject *self, PyObject *arg)
1119{
1120 double x = PyFloat_AsDouble(arg);
1121 if (x == -1.0 && PyErr_Occurred())
1122 return NULL;
1123 return PyBool_FromLong((long)Py_IS_INFINITY(x));
1124}
1125
1126PyDoc_STRVAR(math_isinf_doc,
1127"isinf(x) -> bool\n\
1128Checks if float x is infinite (positive or negative)");
1129
Barry Warsaw8b43b191996-12-09 22:32:36 +00001130static PyMethodDef math_methods[] = {
Thomas Wouters89f507f2006-12-13 04:49:30 +00001131 {"acos", math_acos, METH_O, math_acos_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001132 {"acosh", math_acosh, METH_O, math_acosh_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001133 {"asin", math_asin, METH_O, math_asin_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001134 {"asinh", math_asinh, METH_O, math_asinh_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001135 {"atan", math_atan, METH_O, math_atan_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001136 {"atan2", math_atan2, METH_VARARGS, math_atan2_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001137 {"atanh", math_atanh, METH_O, math_atanh_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001138 {"ceil", math_ceil, METH_O, math_ceil_doc},
Christian Heimes072c0f12008-01-03 23:01:04 +00001139 {"copysign", math_copysign, METH_VARARGS, math_copysign_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001140 {"cos", math_cos, METH_O, math_cos_doc},
1141 {"cosh", math_cosh, METH_O, math_cosh_doc},
1142 {"degrees", math_degrees, METH_O, math_degrees_doc},
1143 {"exp", math_exp, METH_O, math_exp_doc},
1144 {"fabs", math_fabs, METH_O, math_fabs_doc},
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001145 {"factorial", math_factorial, METH_O, math_factorial_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001146 {"floor", math_floor, METH_O, math_floor_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001147 {"fmod", math_fmod, METH_VARARGS, math_fmod_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001148 {"frexp", math_frexp, METH_O, math_frexp_doc},
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001149 {"fsum", math_fsum, METH_O, math_fsum_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001150 {"hypot", math_hypot, METH_VARARGS, math_hypot_doc},
Christian Heimes072c0f12008-01-03 23:01:04 +00001151 {"isinf", math_isinf, METH_O, math_isinf_doc},
1152 {"isnan", math_isnan, METH_O, math_isnan_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001153 {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc},
1154 {"log", math_log, METH_VARARGS, math_log_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001155 {"log1p", math_log1p, METH_O, math_log1p_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001156 {"log10", math_log10, METH_O, math_log10_doc},
1157 {"modf", math_modf, METH_O, math_modf_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001158 {"pow", math_pow, METH_VARARGS, math_pow_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001159 {"radians", math_radians, METH_O, math_radians_doc},
1160 {"sin", math_sin, METH_O, math_sin_doc},
1161 {"sinh", math_sinh, METH_O, math_sinh_doc},
1162 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
1163 {"tan", math_tan, METH_O, math_tan_doc},
1164 {"tanh", math_tanh, METH_O, math_tanh_doc},
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001165 {"trunc", math_trunc, METH_O, math_trunc_doc},
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001166 {NULL, NULL} /* sentinel */
1167};
1168
Guido van Rossumc6e22901998-12-04 19:26:43 +00001169
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001170PyDoc_STRVAR(module_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001171"This module is always available. It provides access to the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001172"mathematical functions defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001173
Martin v. Löwis1a214512008-06-11 05:26:20 +00001174
1175static struct PyModuleDef mathmodule = {
1176 PyModuleDef_HEAD_INIT,
1177 "math",
1178 module_doc,
1179 -1,
1180 math_methods,
1181 NULL,
1182 NULL,
1183 NULL,
1184 NULL
1185};
1186
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001187PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001188PyInit_math(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001189{
Christian Heimes53876d92008-04-19 00:31:39 +00001190 PyObject *m;
Tim Petersfe71f812001-08-07 22:10:00 +00001191
Martin v. Löwis1a214512008-06-11 05:26:20 +00001192 m = PyModule_Create(&mathmodule);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00001193 if (m == NULL)
1194 goto finally;
Barry Warsawfc93f751996-12-17 00:47:03 +00001195
Christian Heimes53876d92008-04-19 00:31:39 +00001196 PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
1197 PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
Barry Warsawfc93f751996-12-17 00:47:03 +00001198
Christian Heimes53876d92008-04-19 00:31:39 +00001199 finally:
Martin v. Löwis1a214512008-06-11 05:26:20 +00001200 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001201}