blob: 38d214a5897a6f78fcaf1f3e9db96543163f1c56 [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
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{
696 static PyObject *trunc_str = NULL;
697 PyObject *trunc;
698
699 if (Py_TYPE(number)->tp_dict == NULL) {
700 if (PyType_Ready(Py_TYPE(number)) < 0)
701 return NULL;
702 }
703
704 if (trunc_str == NULL) {
705 trunc_str = PyUnicode_InternFromString("__trunc__");
706 if (trunc_str == NULL)
707 return NULL;
708 }
709
710 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);
718}
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{
Guido van Rossumd18ad581991-10-24 14:57:21 +0000728 int i;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000729 double x = PyFloat_AsDouble(arg);
730 if (x == -1.0 && PyErr_Occurred())
Guido van Rossumd18ad581991-10-24 14:57:21 +0000731 return NULL;
Christian Heimes53876d92008-04-19 00:31:39 +0000732 /* 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{
Christian Heimes53876d92008-04-19 00:31:39 +0000755 double x, r;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000756 PyObject *oexp;
757 long exp;
758 if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp))
Guido van Rossumd18ad581991-10-24 14:57:21 +0000759 return NULL;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000760
761 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 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000781 else {
782 PyErr_SetString(PyExc_TypeError,
783 "Expected an int or long as second argument "
784 "to ldexp.");
785 return NULL;
786 }
787
788 if (x == 0. || !Py_IS_FINITE(x)) {
789 /* NaNs, zeros and infinities are returned unchanged */
790 r = x;
Christian Heimes53876d92008-04-19 00:31:39 +0000791 errno = 0;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000792 } 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 }
808
Christian Heimes53876d92008-04-19 00:31:39 +0000809 if (errno && is_error(r))
Tim Peters1d120612000-10-12 06:10:25 +0000810 return NULL;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000811 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,
815"ldexp(x, i) -> x * (2**i)");
Guido van Rossumc6e22901998-12-04 19:26:43 +0000816
Barry Warsaw8b43b191996-12-09 22:32:36 +0000817static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +0000818math_modf(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +0000819{
Thomas Wouters89f507f2006-12-13 04:49:30 +0000820 double y, x = PyFloat_AsDouble(arg);
821 if (x == -1.0 && PyErr_Occurred())
Guido van Rossumd18ad581991-10-24 14:57:21 +0000822 return NULL;
Christian Heimesa342c012008-04-20 21:01:16 +0000823 /* some platforms don't do the right thing for NaNs and
824 infinities, so we take care of special cases directly. */
825 if (!Py_IS_FINITE(x)) {
826 if (Py_IS_INFINITY(x))
827 return Py_BuildValue("(dd)", copysign(0., x), x);
828 else if (Py_IS_NAN(x))
829 return Py_BuildValue("(dd)", x, x);
830 }
831
Guido van Rossumd18ad581991-10-24 14:57:21 +0000832 errno = 0;
Christian Heimes53876d92008-04-19 00:31:39 +0000833 PyFPE_START_PROTECT("in math_modf", return 0);
Guido van Rossumd18ad581991-10-24 14:57:21 +0000834 x = modf(x, &y);
Christian Heimes53876d92008-04-19 00:31:39 +0000835 PyFPE_END_PROTECT(x);
836 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +0000837}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000838
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000839PyDoc_STRVAR(math_modf_doc,
Tim Peters63c94532001-09-04 23:17:42 +0000840"modf(x)\n"
841"\n"
842"Return the fractional and integer parts of x. Both results carry the sign\n"
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +0000843"of x and are floats.");
Guido van Rossumc6e22901998-12-04 19:26:43 +0000844
Tim Peters78526162001-09-05 00:53:45 +0000845/* A decent logarithm is easy to compute even for huge longs, but libm can't
846 do that by itself -- loghelper can. func is log or log10, and name is
847 "log" or "log10". Note that overflow isn't possible: a long can contain
848 no more than INT_MAX * SHIFT bits, so has value certainly less than
849 2**(2**64 * 2**16) == 2**2**80, and log2 of that is 2**80, which is
850 small enough to fit in an IEEE single. log and log10 are even smaller.
851*/
852
853static PyObject*
Thomas Wouters89f507f2006-12-13 04:49:30 +0000854loghelper(PyObject* arg, double (*func)(double), char *funcname)
Tim Peters78526162001-09-05 00:53:45 +0000855{
Tim Peters78526162001-09-05 00:53:45 +0000856 /* If it is long, do it ourselves. */
857 if (PyLong_Check(arg)) {
858 double x;
859 int e;
860 x = _PyLong_AsScaledDouble(arg, &e);
861 if (x <= 0.0) {
862 PyErr_SetString(PyExc_ValueError,
863 "math domain error");
864 return NULL;
865 }
Christian Heimesaf98da12008-01-27 15:18:18 +0000866 /* Value is ~= x * 2**(e*PyLong_SHIFT), so the log ~=
867 log(x) + log(2) * e * PyLong_SHIFT.
868 CAUTION: e*PyLong_SHIFT may overflow using int arithmetic,
Tim Peters78526162001-09-05 00:53:45 +0000869 so force use of double. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000870 x = func(x) + (e * (double)PyLong_SHIFT) * func(2.0);
Tim Peters78526162001-09-05 00:53:45 +0000871 return PyFloat_FromDouble(x);
872 }
873
874 /* Else let libm handle it by itself. */
Christian Heimes53876d92008-04-19 00:31:39 +0000875 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +0000876}
877
878static PyObject *
879math_log(PyObject *self, PyObject *args)
880{
Raymond Hettinger866964c2002-12-14 19:51:34 +0000881 PyObject *arg;
882 PyObject *base = NULL;
883 PyObject *num, *den;
884 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +0000885
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000886 if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base))
Raymond Hettinger866964c2002-12-14 19:51:34 +0000887 return NULL;
Raymond Hettinger866964c2002-12-14 19:51:34 +0000888
Mark Dickinsone675f082008-12-11 21:56:00 +0000889 num = loghelper(arg, m_log, "log");
Thomas Wouters89f507f2006-12-13 04:49:30 +0000890 if (num == NULL || base == NULL)
891 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +0000892
Mark Dickinsone675f082008-12-11 21:56:00 +0000893 den = loghelper(base, m_log, "log");
Raymond Hettinger866964c2002-12-14 19:51:34 +0000894 if (den == NULL) {
895 Py_DECREF(num);
896 return NULL;
897 }
898
Neal Norwitzbcc0db82006-03-24 08:14:36 +0000899 ans = PyNumber_TrueDivide(num, den);
Raymond Hettinger866964c2002-12-14 19:51:34 +0000900 Py_DECREF(num);
901 Py_DECREF(den);
902 return ans;
Tim Peters78526162001-09-05 00:53:45 +0000903}
904
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000905PyDoc_STRVAR(math_log_doc,
Raymond Hettinger866964c2002-12-14 19:51:34 +0000906"log(x[, base]) -> the logarithm of x to the given base.\n\
907If the base not specified, returns the natural logarithm (base e) of x.");
Tim Peters78526162001-09-05 00:53:45 +0000908
909static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +0000910math_log10(PyObject *self, PyObject *arg)
Tim Peters78526162001-09-05 00:53:45 +0000911{
Mark Dickinsone675f082008-12-11 21:56:00 +0000912 return loghelper(arg, m_log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +0000913}
914
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000915PyDoc_STRVAR(math_log10_doc,
916"log10(x) -> the base 10 logarithm of x.");
Tim Peters78526162001-09-05 00:53:45 +0000917
Christian Heimes53876d92008-04-19 00:31:39 +0000918static PyObject *
919math_fmod(PyObject *self, PyObject *args)
920{
921 PyObject *ox, *oy;
922 double r, x, y;
923 if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy))
924 return NULL;
925 x = PyFloat_AsDouble(ox);
926 y = PyFloat_AsDouble(oy);
927 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
928 return NULL;
929 /* fmod(x, +/-Inf) returns x for finite x. */
930 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
931 return PyFloat_FromDouble(x);
932 errno = 0;
933 PyFPE_START_PROTECT("in math_fmod", return 0);
934 r = fmod(x, y);
935 PyFPE_END_PROTECT(r);
936 if (Py_IS_NAN(r)) {
937 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
938 errno = EDOM;
939 else
940 errno = 0;
941 }
942 if (errno && is_error(r))
943 return NULL;
944 else
945 return PyFloat_FromDouble(r);
946}
947
948PyDoc_STRVAR(math_fmod_doc,
949"fmod(x,y)\n\nReturn fmod(x, y), according to platform C."
950" x % y may differ.");
951
952static PyObject *
953math_hypot(PyObject *self, PyObject *args)
954{
955 PyObject *ox, *oy;
956 double r, x, y;
957 if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy))
958 return NULL;
959 x = PyFloat_AsDouble(ox);
960 y = PyFloat_AsDouble(oy);
961 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
962 return NULL;
963 /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */
964 if (Py_IS_INFINITY(x))
965 return PyFloat_FromDouble(fabs(x));
966 if (Py_IS_INFINITY(y))
967 return PyFloat_FromDouble(fabs(y));
968 errno = 0;
969 PyFPE_START_PROTECT("in math_hypot", return 0);
970 r = hypot(x, y);
971 PyFPE_END_PROTECT(r);
972 if (Py_IS_NAN(r)) {
973 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
974 errno = EDOM;
975 else
976 errno = 0;
977 }
978 else if (Py_IS_INFINITY(r)) {
979 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
980 errno = ERANGE;
981 else
982 errno = 0;
983 }
984 if (errno && is_error(r))
985 return NULL;
986 else
987 return PyFloat_FromDouble(r);
988}
989
990PyDoc_STRVAR(math_hypot_doc,
991"hypot(x,y)\n\nReturn the Euclidean distance, sqrt(x*x + y*y).");
992
993/* pow can't use math_2, but needs its own wrapper: the problem is
994 that an infinite result can arise either as a result of overflow
995 (in which case OverflowError should be raised) or as a result of
996 e.g. 0.**-5. (for which ValueError needs to be raised.)
997*/
998
999static PyObject *
1000math_pow(PyObject *self, PyObject *args)
1001{
1002 PyObject *ox, *oy;
1003 double r, x, y;
Christian Heimesa342c012008-04-20 21:01:16 +00001004 int odd_y;
Christian Heimes53876d92008-04-19 00:31:39 +00001005
1006 if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy))
1007 return NULL;
1008 x = PyFloat_AsDouble(ox);
1009 y = PyFloat_AsDouble(oy);
1010 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1011 return NULL;
Christian Heimesa342c012008-04-20 21:01:16 +00001012
1013 /* deal directly with IEEE specials, to cope with problems on various
1014 platforms whose semantics don't exactly match C99 */
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001015 r = 0.; /* silence compiler warning */
Christian Heimesa342c012008-04-20 21:01:16 +00001016 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
1017 errno = 0;
1018 if (Py_IS_NAN(x))
1019 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
1020 else if (Py_IS_NAN(y))
1021 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
1022 else if (Py_IS_INFINITY(x)) {
1023 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
1024 if (y > 0.)
1025 r = odd_y ? x : fabs(x);
1026 else if (y == 0.)
1027 r = 1.;
1028 else /* y < 0. */
1029 r = odd_y ? copysign(0., x) : 0.;
1030 }
1031 else if (Py_IS_INFINITY(y)) {
1032 if (fabs(x) == 1.0)
1033 r = 1.;
1034 else if (y > 0. && fabs(x) > 1.0)
1035 r = y;
1036 else if (y < 0. && fabs(x) < 1.0) {
1037 r = -y; /* result is +inf */
1038 if (x == 0.) /* 0**-inf: divide-by-zero */
1039 errno = EDOM;
1040 }
1041 else
1042 r = 0.;
1043 }
Christian Heimes53876d92008-04-19 00:31:39 +00001044 }
Christian Heimesa342c012008-04-20 21:01:16 +00001045 else {
1046 /* let libm handle finite**finite */
1047 errno = 0;
1048 PyFPE_START_PROTECT("in math_pow", return 0);
1049 r = pow(x, y);
1050 PyFPE_END_PROTECT(r);
1051 /* a NaN result should arise only from (-ve)**(finite
1052 non-integer); in this case we want to raise ValueError. */
1053 if (!Py_IS_FINITE(r)) {
1054 if (Py_IS_NAN(r)) {
1055 errno = EDOM;
1056 }
1057 /*
1058 an infinite result here arises either from:
1059 (A) (+/-0.)**negative (-> divide-by-zero)
1060 (B) overflow of x**y with x and y finite
1061 */
1062 else if (Py_IS_INFINITY(r)) {
1063 if (x == 0.)
1064 errno = EDOM;
1065 else
1066 errno = ERANGE;
1067 }
1068 }
Christian Heimes53876d92008-04-19 00:31:39 +00001069 }
1070
1071 if (errno && is_error(r))
1072 return NULL;
1073 else
1074 return PyFloat_FromDouble(r);
1075}
1076
1077PyDoc_STRVAR(math_pow_doc,
1078"pow(x,y)\n\nReturn x**y (x to the power of y).");
1079
Christian Heimes072c0f12008-01-03 23:01:04 +00001080static const double degToRad = Py_MATH_PI / 180.0;
1081static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001082
1083static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001084math_degrees(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001085{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001086 double x = PyFloat_AsDouble(arg);
1087 if (x == -1.0 && PyErr_Occurred())
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001088 return NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +00001089 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001090}
1091
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001092PyDoc_STRVAR(math_degrees_doc,
1093"degrees(x) -> converts angle x from radians to degrees");
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001094
1095static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +00001096math_radians(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001097{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001098 double x = PyFloat_AsDouble(arg);
1099 if (x == -1.0 && PyErr_Occurred())
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001100 return NULL;
1101 return PyFloat_FromDouble(x * degToRad);
1102}
1103
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001104PyDoc_STRVAR(math_radians_doc,
1105"radians(x) -> converts angle x from degrees to radians");
Tim Peters78526162001-09-05 00:53:45 +00001106
Christian Heimes072c0f12008-01-03 23:01:04 +00001107static PyObject *
1108math_isnan(PyObject *self, PyObject *arg)
1109{
1110 double x = PyFloat_AsDouble(arg);
1111 if (x == -1.0 && PyErr_Occurred())
1112 return NULL;
1113 return PyBool_FromLong((long)Py_IS_NAN(x));
1114}
1115
1116PyDoc_STRVAR(math_isnan_doc,
1117"isnan(x) -> bool\n\
1118Checks if float x is not a number (NaN)");
1119
1120static PyObject *
1121math_isinf(PyObject *self, PyObject *arg)
1122{
1123 double x = PyFloat_AsDouble(arg);
1124 if (x == -1.0 && PyErr_Occurred())
1125 return NULL;
1126 return PyBool_FromLong((long)Py_IS_INFINITY(x));
1127}
1128
1129PyDoc_STRVAR(math_isinf_doc,
1130"isinf(x) -> bool\n\
1131Checks if float x is infinite (positive or negative)");
1132
Barry Warsaw8b43b191996-12-09 22:32:36 +00001133static PyMethodDef math_methods[] = {
Thomas Wouters89f507f2006-12-13 04:49:30 +00001134 {"acos", math_acos, METH_O, math_acos_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001135 {"acosh", math_acosh, METH_O, math_acosh_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001136 {"asin", math_asin, METH_O, math_asin_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001137 {"asinh", math_asinh, METH_O, math_asinh_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001138 {"atan", math_atan, METH_O, math_atan_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001139 {"atan2", math_atan2, METH_VARARGS, math_atan2_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001140 {"atanh", math_atanh, METH_O, math_atanh_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001141 {"ceil", math_ceil, METH_O, math_ceil_doc},
Christian Heimes072c0f12008-01-03 23:01:04 +00001142 {"copysign", math_copysign, METH_VARARGS, math_copysign_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001143 {"cos", math_cos, METH_O, math_cos_doc},
1144 {"cosh", math_cosh, METH_O, math_cosh_doc},
1145 {"degrees", math_degrees, METH_O, math_degrees_doc},
1146 {"exp", math_exp, METH_O, math_exp_doc},
1147 {"fabs", math_fabs, METH_O, math_fabs_doc},
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001148 {"factorial", math_factorial, METH_O, math_factorial_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001149 {"floor", math_floor, METH_O, math_floor_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001150 {"fmod", math_fmod, METH_VARARGS, math_fmod_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001151 {"frexp", math_frexp, METH_O, math_frexp_doc},
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001152 {"fsum", math_fsum, METH_O, math_fsum_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001153 {"hypot", math_hypot, METH_VARARGS, math_hypot_doc},
Christian Heimes072c0f12008-01-03 23:01:04 +00001154 {"isinf", math_isinf, METH_O, math_isinf_doc},
1155 {"isnan", math_isnan, METH_O, math_isnan_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001156 {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc},
1157 {"log", math_log, METH_VARARGS, math_log_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00001158 {"log1p", math_log1p, METH_O, math_log1p_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001159 {"log10", math_log10, METH_O, math_log10_doc},
1160 {"modf", math_modf, METH_O, math_modf_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001161 {"pow", math_pow, METH_VARARGS, math_pow_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +00001162 {"radians", math_radians, METH_O, math_radians_doc},
1163 {"sin", math_sin, METH_O, math_sin_doc},
1164 {"sinh", math_sinh, METH_O, math_sinh_doc},
1165 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
1166 {"tan", math_tan, METH_O, math_tan_doc},
1167 {"tanh", math_tanh, METH_O, math_tanh_doc},
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001168 {"trunc", math_trunc, METH_O, math_trunc_doc},
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001169 {NULL, NULL} /* sentinel */
1170};
1171
Guido van Rossumc6e22901998-12-04 19:26:43 +00001172
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001173PyDoc_STRVAR(module_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001174"This module is always available. It provides access to the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001175"mathematical functions defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001176
Martin v. Löwis1a214512008-06-11 05:26:20 +00001177
1178static struct PyModuleDef mathmodule = {
1179 PyModuleDef_HEAD_INIT,
1180 "math",
1181 module_doc,
1182 -1,
1183 math_methods,
1184 NULL,
1185 NULL,
1186 NULL,
1187 NULL
1188};
1189
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001190PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001191PyInit_math(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001192{
Christian Heimes53876d92008-04-19 00:31:39 +00001193 PyObject *m;
Tim Petersfe71f812001-08-07 22:10:00 +00001194
Martin v. Löwis1a214512008-06-11 05:26:20 +00001195 m = PyModule_Create(&mathmodule);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00001196 if (m == NULL)
1197 goto finally;
Barry Warsawfc93f751996-12-17 00:47:03 +00001198
Christian Heimes53876d92008-04-19 00:31:39 +00001199 PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
1200 PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
Barry Warsawfc93f751996-12-17 00:47:03 +00001201
Christian Heimes53876d92008-04-19 00:31:39 +00001202 finally:
Martin v. Löwis1a214512008-06-11 05:26:20 +00001203 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001204}