blob: 5087ecc481bbef4030c3774c31ce483310029feb [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Math module -- standard C math library functions, pi and e */
2
Christian Heimes6f341092008-04-18 23:13:07 +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
Neal Norwitz5f95a792008-01-25 08:04:16 +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).
Mark Dickinsonfb1c4b92008-06-17 21:16:55 +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 */
Mark Dickinsonfb1c4b92008-06-17 21:16:55 +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 Heimes6f341092008-04-18 23:13:07 +0000103/*
Mark Dickinson92483cd2008-04-20 21:39:04 +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 Dickinson4c96fa52008-12-11 19:28:08 +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 Heimes6f341092008-04-18 23:13:07 +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 *
Christian Heimes6f341092008-04-18 23:13:07 +0000222math_1(PyObject *arg, double (*func) (double), int can_overflow)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000223{
Christian Heimes6f341092008-04-18 23:13:07 +0000224 double x, r;
225 x = PyFloat_AsDouble(arg);
Neal Norwitz45e230a2006-11-19 21:26:53 +0000226 if (x == -1.0 && PyErr_Occurred())
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000227 return NULL;
228 errno = 0;
Christian Heimes6f341092008-04-18 23:13:07 +0000229 PyFPE_START_PROTECT("in math_1", return 0);
230 r = (*func)(x);
231 PyFPE_END_PROTECT(r);
232 if (Py_IS_NAN(r)) {
233 if (!Py_IS_NAN(x))
234 errno = EDOM;
235 else
236 errno = 0;
237 }
238 else if (Py_IS_INFINITY(r)) {
239 if (Py_IS_FINITE(x))
240 errno = can_overflow ? ERANGE : EDOM;
241 else
242 errno = 0;
243 }
244 if (errno && is_error(r))
Tim Peters1d120612000-10-12 06:10:25 +0000245 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000246 else
Christian Heimes6f341092008-04-18 23:13:07 +0000247 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000248}
249
Christian Heimes6f341092008-04-18 23:13:07 +0000250/*
251 math_2 is used to wrap a libm function f that takes two double
252 arguments and returns a double.
253
254 The error reporting follows these rules, which are designed to do
255 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
256 platforms.
257
258 - a NaN result from non-NaN inputs causes ValueError to be raised
259 - an infinite result from finite inputs causes OverflowError to be
260 raised.
261 - if the result is finite and errno == EDOM then ValueError is
262 raised
263 - if the result is finite and nonzero and errno == ERANGE then
264 OverflowError is raised
265
266 The last rule is used to catch overflow on platforms which follow
267 C89 but for which HUGE_VAL is not an infinity.
268
269 For most two-argument functions (copysign, fmod, hypot, atan2)
270 these rules are enough to ensure that Python's functions behave as
271 specified in 'Annex F' of the C99 standard, with the 'invalid' and
272 'divide-by-zero' floating-point exceptions mapping to Python's
273 ValueError and the 'overflow' floating-point exception mapping to
274 OverflowError.
275*/
276
Barry Warsaw8b43b191996-12-09 22:32:36 +0000277static PyObject *
Neal Norwitz45e230a2006-11-19 21:26:53 +0000278math_2(PyObject *args, double (*func) (double, double), char *funcname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000279{
Neal Norwitz45e230a2006-11-19 21:26:53 +0000280 PyObject *ox, *oy;
Christian Heimes6f341092008-04-18 23:13:07 +0000281 double x, y, r;
Neal Norwitz45e230a2006-11-19 21:26:53 +0000282 if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy))
283 return NULL;
284 x = PyFloat_AsDouble(ox);
285 y = PyFloat_AsDouble(oy);
286 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000287 return NULL;
288 errno = 0;
Christian Heimes6f341092008-04-18 23:13:07 +0000289 PyFPE_START_PROTECT("in math_2", return 0);
290 r = (*func)(x, y);
291 PyFPE_END_PROTECT(r);
292 if (Py_IS_NAN(r)) {
293 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
294 errno = EDOM;
295 else
296 errno = 0;
297 }
298 else if (Py_IS_INFINITY(r)) {
299 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
300 errno = ERANGE;
301 else
302 errno = 0;
303 }
304 if (errno && is_error(r))
Tim Peters1d120612000-10-12 06:10:25 +0000305 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000306 else
Christian Heimes6f341092008-04-18 23:13:07 +0000307 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000308}
309
Christian Heimes6f341092008-04-18 23:13:07 +0000310#define FUNC1(funcname, func, can_overflow, docstring) \
Fred Drake40c48682000-07-03 18:11:56 +0000311 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
Christian Heimes6f341092008-04-18 23:13:07 +0000312 return math_1(args, func, can_overflow); \
Guido van Rossumc6e22901998-12-04 19:26:43 +0000313 }\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000314 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000315
Fred Drake40c48682000-07-03 18:11:56 +0000316#define FUNC2(funcname, func, docstring) \
317 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
Neal Norwitz45e230a2006-11-19 21:26:53 +0000318 return math_2(args, func, #funcname); \
Guido van Rossumc6e22901998-12-04 19:26:43 +0000319 }\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000320 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000321
Christian Heimes6f341092008-04-18 23:13:07 +0000322FUNC1(acos, acos, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000323 "acos(x)\n\nReturn the arc cosine (measured in radians) of x.")
Christian Heimes6f341092008-04-18 23:13:07 +0000324FUNC1(acosh, acosh, 0,
325 "acosh(x)\n\nReturn the hyperbolic arc cosine (measured in radians) of x.")
326FUNC1(asin, asin, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000327 "asin(x)\n\nReturn the arc sine (measured in radians) of x.")
Christian Heimes6f341092008-04-18 23:13:07 +0000328FUNC1(asinh, asinh, 0,
329 "asinh(x)\n\nReturn the hyperbolic arc sine (measured in radians) of x.")
330FUNC1(atan, atan, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000331 "atan(x)\n\nReturn the arc tangent (measured in radians) of x.")
Mark Dickinson92483cd2008-04-20 21:39:04 +0000332FUNC2(atan2, m_atan2,
Tim Petersfe71f812001-08-07 22:10:00 +0000333 "atan2(y, x)\n\nReturn the arc tangent (measured in radians) of y/x.\n"
334 "Unlike atan(y/x), the signs of both x and y are considered.")
Christian Heimes6f341092008-04-18 23:13:07 +0000335FUNC1(atanh, atanh, 0,
336 "atanh(x)\n\nReturn the hyperbolic arc tangent (measured in radians) of x.")
337FUNC1(ceil, ceil, 0,
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +0000338 "ceil(x)\n\nReturn the ceiling of x as a float.\n"
339 "This is the smallest integral value >= x.")
Christian Heimeseebb79c2008-01-03 22:32:26 +0000340FUNC2(copysign, copysign,
Christian Heimes6f341092008-04-18 23:13:07 +0000341 "copysign(x,y)\n\nReturn x with the sign of y.")
342FUNC1(cos, cos, 0,
343 "cos(x)\n\nReturn the cosine of x (measured in radians).")
344FUNC1(cosh, cosh, 1,
345 "cosh(x)\n\nReturn the hyperbolic cosine of x.")
346FUNC1(exp, exp, 1,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000347 "exp(x)\n\nReturn e raised to the power of x.")
Christian Heimes6f341092008-04-18 23:13:07 +0000348FUNC1(fabs, fabs, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000349 "fabs(x)\n\nReturn the absolute value of the float x.")
Christian Heimes6f341092008-04-18 23:13:07 +0000350FUNC1(floor, floor, 0,
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +0000351 "floor(x)\n\nReturn the floor of x as a float.\n"
352 "This is the largest integral value <= x.")
Christian Heimes6f341092008-04-18 23:13:07 +0000353FUNC1(log1p, log1p, 1,
354 "log1p(x)\n\nReturn the natural logarithm of 1+x (base e).\n\
355 The result is computed in a way which is accurate for x near zero.")
356FUNC1(sin, sin, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000357 "sin(x)\n\nReturn the sine of x (measured in radians).")
Christian Heimes6f341092008-04-18 23:13:07 +0000358FUNC1(sinh, sinh, 1,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000359 "sinh(x)\n\nReturn the hyperbolic sine of x.")
Christian Heimes6f341092008-04-18 23:13:07 +0000360FUNC1(sqrt, sqrt, 0,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000361 "sqrt(x)\n\nReturn the square root of x.")
Christian Heimes6f341092008-04-18 23:13:07 +0000362FUNC1(tan, tan, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000363 "tan(x)\n\nReturn the tangent of x (measured in radians).")
Christian Heimes6f341092008-04-18 23:13:07 +0000364FUNC1(tanh, tanh, 0,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000365 "tanh(x)\n\nReturn the hyperbolic tangent of x.")
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000366
Mark Dickinson99dfe922008-05-23 01:35:30 +0000367/* Precision summation function as msum() by Raymond Hettinger in
368 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
369 enhanced with the exact partials sum and roundoff from Mark
370 Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000371 See those links for more details, proofs and other references.
Mark Dickinson99dfe922008-05-23 01:35:30 +0000372
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000373 Note 1: IEEE 754R floating point semantics are assumed,
374 but the current implementation does not re-establish special
375 value semantics across iterations (i.e. handling -Inf + Inf).
Mark Dickinson99dfe922008-05-23 01:35:30 +0000376
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000377 Note 2: No provision is made for intermediate overflow handling;
Raymond Hettinger2a9179a2008-05-29 08:38:23 +0000378 therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000379 sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
380 overflow of the first partial sum.
Mark Dickinson99dfe922008-05-23 01:35:30 +0000381
Andrew M. Kuchling5f198be2008-06-20 02:11:42 +0000382 Note 3: The intermediate values lo, yr, and hi are declared volatile so
Mark Dickinson2fcd8c92008-06-20 15:26:19 +0000383 aggressive compilers won't algebraically reduce lo to always be exactly 0.0.
Raymond Hettingerd6234142008-06-09 11:24:47 +0000384 Also, the volatile declaration forces the values to be stored in memory as
385 regular doubles instead of extended long precision (80-bit) values. This
Andrew M. Kuchling5f198be2008-06-20 02:11:42 +0000386 prevents double rounding because any addition or subtraction of two doubles
Raymond Hettingerd6234142008-06-09 11:24:47 +0000387 can be resolved exactly into double-sized hi and lo values. As long as the
388 hi value gets forced into a double before yr and lo are computed, the extra
389 bits in downstream extended precision operations (x87 for example) will be
390 exactly zero and therefore can be losslessly stored back into a double,
391 thereby preventing double rounding.
Mark Dickinson99dfe922008-05-23 01:35:30 +0000392
Raymond Hettingerd6234142008-06-09 11:24:47 +0000393 Note 4: A similar implementation is in Modules/cmathmodule.c.
394 Be sure to update both when making changes.
Mark Dickinson99dfe922008-05-23 01:35:30 +0000395
Mark Dickinsonff3fdce2008-07-30 16:25:16 +0000396 Note 5: The signature of math.fsum() differs from __builtin__.sum()
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000397 because the start argument doesn't make sense in the context of
398 accurate summation. Since the partials table is collapsed before
399 returning a result, sum(seq2, start=sum(seq1)) may not equal the
400 accurate result returned by sum(itertools.chain(seq1, seq2)).
Mark Dickinson99dfe922008-05-23 01:35:30 +0000401*/
402
403#define NUM_PARTIALS 32 /* initial partials array size, on stack */
404
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000405/* Extend the partials array p[] by doubling its size. */
406static int /* non-zero on error */
Mark Dickinsonfef6b132008-07-30 16:20:10 +0000407_fsum_realloc(double **p_ptr, Py_ssize_t n,
Raymond Hettingerd6234142008-06-09 11:24:47 +0000408 double *ps, Py_ssize_t *m_ptr)
Mark Dickinson99dfe922008-05-23 01:35:30 +0000409{
410 void *v = NULL;
411 Py_ssize_t m = *m_ptr;
412
Raymond Hettingerd6234142008-06-09 11:24:47 +0000413 m += m; /* double */
414 if (n < m && m < (PY_SSIZE_T_MAX / sizeof(double))) {
415 double *p = *p_ptr;
Mark Dickinson99dfe922008-05-23 01:35:30 +0000416 if (p == ps) {
Raymond Hettingerd6234142008-06-09 11:24:47 +0000417 v = PyMem_Malloc(sizeof(double) * m);
Mark Dickinson99dfe922008-05-23 01:35:30 +0000418 if (v != NULL)
Raymond Hettingerd6234142008-06-09 11:24:47 +0000419 memcpy(v, ps, sizeof(double) * n);
Mark Dickinson99dfe922008-05-23 01:35:30 +0000420 }
421 else
Raymond Hettingerd6234142008-06-09 11:24:47 +0000422 v = PyMem_Realloc(p, sizeof(double) * m);
Mark Dickinson99dfe922008-05-23 01:35:30 +0000423 }
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000424 if (v == NULL) { /* size overflow or no memory */
Mark Dickinsonfef6b132008-07-30 16:20:10 +0000425 PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
Mark Dickinson99dfe922008-05-23 01:35:30 +0000426 return 1;
427 }
Raymond Hettingerd6234142008-06-09 11:24:47 +0000428 *p_ptr = (double*) v;
Mark Dickinson99dfe922008-05-23 01:35:30 +0000429 *m_ptr = m;
430 return 0;
431}
432
433/* Full precision summation of a sequence of floats.
434
435 def msum(iterable):
436 partials = [] # sorted, non-overlapping partial sums
437 for x in iterable:
438 i = 0
439 for y in partials:
440 if abs(x) < abs(y):
441 x, y = y, x
442 hi = x + y
443 lo = y - (hi - x)
444 if lo:
445 partials[i] = lo
446 i += 1
447 x = hi
448 partials[i:] = [x]
449 return sum_exact(partials)
450
451 Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
452 are exactly equal to x+y. The inner loop applies hi/lo summation to each
453 partial so that the list of partial sums remains exact.
454
455 Sum_exact() adds the partial sums exactly and correctly rounds the final
456 result (using the round-half-to-even rule). The items in partials remain
457 non-zero, non-special, non-overlapping and strictly increasing in
458 magnitude, but possibly not all having the same sign.
459
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000460 Depends on IEEE 754 arithmetic guarantees and half-even rounding.
461*/
462
Mark Dickinson99dfe922008-05-23 01:35:30 +0000463static PyObject*
Mark Dickinsonfef6b132008-07-30 16:20:10 +0000464math_fsum(PyObject *self, PyObject *seq)
Mark Dickinson99dfe922008-05-23 01:35:30 +0000465{
466 PyObject *item, *iter, *sum = NULL;
467 Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
Raymond Hettingerd6234142008-06-09 11:24:47 +0000468 double x, y, t, ps[NUM_PARTIALS], *p = ps;
Mark Dickinsonabe0aee2008-07-30 12:01:41 +0000469 double xsave, special_sum = 0.0, inf_sum = 0.0;
Raymond Hettingerd6234142008-06-09 11:24:47 +0000470 volatile double hi, yr, lo;
Mark Dickinson99dfe922008-05-23 01:35:30 +0000471
472 iter = PyObject_GetIter(seq);
473 if (iter == NULL)
474 return NULL;
475
Mark Dickinsonfef6b132008-07-30 16:20:10 +0000476 PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL)
Mark Dickinson99dfe922008-05-23 01:35:30 +0000477
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000478 for(;;) { /* for x in iterable */
Mark Dickinson99dfe922008-05-23 01:35:30 +0000479 assert(0 <= n && n <= m);
480 assert((m == NUM_PARTIALS && p == ps) ||
481 (m > NUM_PARTIALS && p != NULL));
482
483 item = PyIter_Next(iter);
484 if (item == NULL) {
485 if (PyErr_Occurred())
Mark Dickinsonfef6b132008-07-30 16:20:10 +0000486 goto _fsum_error;
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000487 break;
Mark Dickinson99dfe922008-05-23 01:35:30 +0000488 }
Raymond Hettingerd6234142008-06-09 11:24:47 +0000489 x = PyFloat_AsDouble(item);
Mark Dickinson99dfe922008-05-23 01:35:30 +0000490 Py_DECREF(item);
491 if (PyErr_Occurred())
Mark Dickinsonfef6b132008-07-30 16:20:10 +0000492 goto _fsum_error;
Mark Dickinson99dfe922008-05-23 01:35:30 +0000493
Mark Dickinsonabe0aee2008-07-30 12:01:41 +0000494 xsave = x;
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000495 for (i = j = 0; j < n; j++) { /* for y in partials */
Mark Dickinson99dfe922008-05-23 01:35:30 +0000496 y = p[j];
Raymond Hettingeref712d62008-05-30 18:20:50 +0000497 if (fabs(x) < fabs(y)) {
Mark Dickinsonabe0aee2008-07-30 12:01:41 +0000498 t = x; x = y; y = t;
Raymond Hettingeref712d62008-05-30 18:20:50 +0000499 }
Mark Dickinson99dfe922008-05-23 01:35:30 +0000500 hi = x + y;
Raymond Hettingeref712d62008-05-30 18:20:50 +0000501 yr = hi - x;
502 lo = y - yr;
Mark Dickinson99dfe922008-05-23 01:35:30 +0000503 if (lo != 0.0)
504 p[i++] = lo;
505 x = hi;
506 }
Mark Dickinsonabe0aee2008-07-30 12:01:41 +0000507
508 n = i; /* ps[i:] = [x] */
Mark Dickinson99dfe922008-05-23 01:35:30 +0000509 if (x != 0.0) {
Mark Dickinsonabe0aee2008-07-30 12:01:41 +0000510 if (! Py_IS_FINITE(x)) {
511 /* a nonfinite x could arise either as
512 a result of intermediate overflow, or
513 as a result of a nan or inf in the
514 summands */
515 if (Py_IS_FINITE(xsave)) {
516 PyErr_SetString(PyExc_OverflowError,
Mark Dickinsonfef6b132008-07-30 16:20:10 +0000517 "intermediate overflow in fsum");
518 goto _fsum_error;
Mark Dickinsonabe0aee2008-07-30 12:01:41 +0000519 }
520 if (Py_IS_INFINITY(xsave))
521 inf_sum += xsave;
522 special_sum += xsave;
523 /* reset partials */
Mark Dickinson99dfe922008-05-23 01:35:30 +0000524 n = 0;
Mark Dickinsonabe0aee2008-07-30 12:01:41 +0000525 }
Mark Dickinsonfef6b132008-07-30 16:20:10 +0000526 else if (n >= m && _fsum_realloc(&p, n, ps, &m))
527 goto _fsum_error;
Mark Dickinsonabe0aee2008-07-30 12:01:41 +0000528 else
529 p[n++] = x;
Mark Dickinson99dfe922008-05-23 01:35:30 +0000530 }
531 }
Mark Dickinson99dfe922008-05-23 01:35:30 +0000532
Mark Dickinsonabe0aee2008-07-30 12:01:41 +0000533 if (special_sum != 0.0) {
534 if (Py_IS_NAN(inf_sum))
535 PyErr_SetString(PyExc_ValueError,
Mark Dickinsonfef6b132008-07-30 16:20:10 +0000536 "-inf + inf in fsum");
Mark Dickinsonabe0aee2008-07-30 12:01:41 +0000537 else
538 sum = PyFloat_FromDouble(special_sum);
Mark Dickinsonfef6b132008-07-30 16:20:10 +0000539 goto _fsum_error;
Mark Dickinsonabe0aee2008-07-30 12:01:41 +0000540 }
541
Raymond Hettingeref712d62008-05-30 18:20:50 +0000542 hi = 0.0;
Mark Dickinson99dfe922008-05-23 01:35:30 +0000543 if (n > 0) {
544 hi = p[--n];
Mark Dickinsonabe0aee2008-07-30 12:01:41 +0000545 /* sum_exact(ps, hi) from the top, stop when the sum becomes
546 inexact. */
547 while (n > 0) {
548 x = hi;
549 y = p[--n];
550 assert(fabs(y) < fabs(x));
551 hi = x + y;
552 yr = hi - x;
553 lo = y - yr;
554 if (lo != 0.0)
555 break;
Mark Dickinson99dfe922008-05-23 01:35:30 +0000556 }
Mark Dickinsonabe0aee2008-07-30 12:01:41 +0000557 /* Make half-even rounding work across multiple partials.
558 Needed so that sum([1e-16, 1, 1e16]) will round-up the last
559 digit to two instead of down to zero (the 1e-16 makes the 1
560 slightly closer to two). With a potential 1 ULP rounding
Mark Dickinsonff3fdce2008-07-30 16:25:16 +0000561 error fixed-up, math.fsum() can guarantee commutativity. */
Mark Dickinsonabe0aee2008-07-30 12:01:41 +0000562 if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
563 (lo > 0.0 && p[n-1] > 0.0))) {
564 y = lo * 2.0;
565 x = hi + y;
566 yr = x - hi;
567 if (y == yr)
568 hi = x;
Mark Dickinson99dfe922008-05-23 01:35:30 +0000569 }
570 }
Raymond Hettingerd6234142008-06-09 11:24:47 +0000571 sum = PyFloat_FromDouble(hi);
Mark Dickinson99dfe922008-05-23 01:35:30 +0000572
Mark Dickinsonfef6b132008-07-30 16:20:10 +0000573_fsum_error:
Mark Dickinson99dfe922008-05-23 01:35:30 +0000574 PyFPE_END_PROTECT(hi)
Mark Dickinson99dfe922008-05-23 01:35:30 +0000575 Py_DECREF(iter);
576 if (p != ps)
577 PyMem_Free(p);
578 return sum;
579}
580
581#undef NUM_PARTIALS
582
Mark Dickinsonfef6b132008-07-30 16:20:10 +0000583PyDoc_STRVAR(math_fsum_doc,
Raymond Hettinger778d5cc2008-05-23 04:32:43 +0000584"sum(iterable)\n\n\
585Return an accurate floating point sum of values in the iterable.\n\
586Assumes IEEE-754 floating point arithmetic.");
Mark Dickinson99dfe922008-05-23 01:35:30 +0000587
Raymond Hettingerecbdd2e2008-06-09 06:54:45 +0000588static PyObject *
589math_factorial(PyObject *self, PyObject *arg)
590{
591 long i, x;
592 PyObject *result, *iobj, *newresult;
593
594 if (PyFloat_Check(arg)) {
595 double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
596 if (dx != floor(dx)) {
597 PyErr_SetString(PyExc_ValueError,
598 "factorial() only accepts integral values");
599 return NULL;
600 }
601 }
602
603 x = PyInt_AsLong(arg);
604 if (x == -1 && PyErr_Occurred())
605 return NULL;
606 if (x < 0) {
607 PyErr_SetString(PyExc_ValueError,
608 "factorial() not defined for negative values");
609 return NULL;
610 }
611
612 result = (PyObject *)PyInt_FromLong(1);
613 if (result == NULL)
614 return NULL;
615 for (i=1 ; i<=x ; i++) {
616 iobj = (PyObject *)PyInt_FromLong(i);
617 if (iobj == NULL)
618 goto error;
619 newresult = PyNumber_Multiply(result, iobj);
620 Py_DECREF(iobj);
621 if (newresult == NULL)
622 goto error;
623 Py_DECREF(result);
624 result = newresult;
625 }
626 return result;
627
628error:
629 Py_DECREF(result);
Raymond Hettingerecbdd2e2008-06-09 06:54:45 +0000630 return NULL;
631}
632
633PyDoc_STRVAR(math_factorial_doc, "Return n!");
634
Barry Warsaw8b43b191996-12-09 22:32:36 +0000635static PyObject *
Jeffrey Yasskinca2b69f2008-02-01 06:22:46 +0000636math_trunc(PyObject *self, PyObject *number)
637{
Jeffrey Yasskinca2b69f2008-02-01 06:22:46 +0000638 return PyObject_CallMethod(number, "__trunc__", NULL);
639}
640
641PyDoc_STRVAR(math_trunc_doc,
642"trunc(x:Real) -> Integral\n"
643"\n"
Raymond Hettingerfe424f72008-02-02 05:24:44 +0000644"Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.");
Jeffrey Yasskinca2b69f2008-02-01 06:22:46 +0000645
646static PyObject *
Neal Norwitz45e230a2006-11-19 21:26:53 +0000647math_frexp(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +0000648{
Guido van Rossumd18ad581991-10-24 14:57:21 +0000649 int i;
Neal Norwitz45e230a2006-11-19 21:26:53 +0000650 double x = PyFloat_AsDouble(arg);
651 if (x == -1.0 && PyErr_Occurred())
Guido van Rossumd18ad581991-10-24 14:57:21 +0000652 return NULL;
Christian Heimes6f341092008-04-18 23:13:07 +0000653 /* deal with special cases directly, to sidestep platform
654 differences */
655 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
656 i = 0;
657 }
658 else {
659 PyFPE_START_PROTECT("in math_frexp", return 0);
660 x = frexp(x, &i);
661 PyFPE_END_PROTECT(x);
662 }
663 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +0000664}
665
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000666PyDoc_STRVAR(math_frexp_doc,
Tim Peters63c94532001-09-04 23:17:42 +0000667"frexp(x)\n"
668"\n"
669"Return the mantissa and exponent of x, as pair (m, e).\n"
670"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 +0000671"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 +0000672
Barry Warsaw8b43b191996-12-09 22:32:36 +0000673static PyObject *
Fred Drake40c48682000-07-03 18:11:56 +0000674math_ldexp(PyObject *self, PyObject *args)
Guido van Rossumd18ad581991-10-24 14:57:21 +0000675{
Christian Heimes6f341092008-04-18 23:13:07 +0000676 double x, r;
Mark Dickinsonf8476c12008-05-09 17:54:23 +0000677 PyObject *oexp;
678 long exp;
679 if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp))
Guido van Rossumd18ad581991-10-24 14:57:21 +0000680 return NULL;
Mark Dickinsonf8476c12008-05-09 17:54:23 +0000681
682 if (PyLong_Check(oexp)) {
683 /* on overflow, replace exponent with either LONG_MAX
684 or LONG_MIN, depending on the sign. */
685 exp = PyLong_AsLong(oexp);
686 if (exp == -1 && PyErr_Occurred()) {
687 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
688 if (Py_SIZE(oexp) < 0) {
689 exp = LONG_MIN;
690 }
691 else {
692 exp = LONG_MAX;
693 }
694 PyErr_Clear();
695 }
696 else {
697 /* propagate any unexpected exception */
698 return NULL;
699 }
700 }
701 }
702 else if (PyInt_Check(oexp)) {
703 exp = PyInt_AS_LONG(oexp);
704 }
705 else {
706 PyErr_SetString(PyExc_TypeError,
707 "Expected an int or long as second argument "
708 "to ldexp.");
709 return NULL;
710 }
711
712 if (x == 0. || !Py_IS_FINITE(x)) {
713 /* NaNs, zeros and infinities are returned unchanged */
714 r = x;
Christian Heimes6f341092008-04-18 23:13:07 +0000715 errno = 0;
Mark Dickinsonf8476c12008-05-09 17:54:23 +0000716 } else if (exp > INT_MAX) {
717 /* overflow */
718 r = copysign(Py_HUGE_VAL, x);
719 errno = ERANGE;
720 } else if (exp < INT_MIN) {
721 /* underflow to +-0 */
722 r = copysign(0., x);
723 errno = 0;
724 } else {
725 errno = 0;
726 PyFPE_START_PROTECT("in math_ldexp", return 0);
727 r = ldexp(x, (int)exp);
728 PyFPE_END_PROTECT(r);
729 if (Py_IS_INFINITY(r))
730 errno = ERANGE;
731 }
732
Christian Heimes6f341092008-04-18 23:13:07 +0000733 if (errno && is_error(r))
Tim Peters1d120612000-10-12 06:10:25 +0000734 return NULL;
Mark Dickinsonf8476c12008-05-09 17:54:23 +0000735 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +0000736}
737
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000738PyDoc_STRVAR(math_ldexp_doc,
739"ldexp(x, i) -> x * (2**i)");
Guido van Rossumc6e22901998-12-04 19:26:43 +0000740
Barry Warsaw8b43b191996-12-09 22:32:36 +0000741static PyObject *
Neal Norwitz45e230a2006-11-19 21:26:53 +0000742math_modf(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +0000743{
Neal Norwitz45e230a2006-11-19 21:26:53 +0000744 double y, x = PyFloat_AsDouble(arg);
745 if (x == -1.0 && PyErr_Occurred())
Guido van Rossumd18ad581991-10-24 14:57:21 +0000746 return NULL;
Mark Dickinsonb2f70902008-04-20 01:39:24 +0000747 /* some platforms don't do the right thing for NaNs and
748 infinities, so we take care of special cases directly. */
749 if (!Py_IS_FINITE(x)) {
750 if (Py_IS_INFINITY(x))
751 return Py_BuildValue("(dd)", copysign(0., x), x);
752 else if (Py_IS_NAN(x))
753 return Py_BuildValue("(dd)", x, x);
754 }
755
Guido van Rossumd18ad581991-10-24 14:57:21 +0000756 errno = 0;
Christian Heimes6f341092008-04-18 23:13:07 +0000757 PyFPE_START_PROTECT("in math_modf", return 0);
Guido van Rossumd18ad581991-10-24 14:57:21 +0000758 x = modf(x, &y);
Christian Heimes6f341092008-04-18 23:13:07 +0000759 PyFPE_END_PROTECT(x);
760 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +0000761}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000762
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000763PyDoc_STRVAR(math_modf_doc,
Tim Peters63c94532001-09-04 23:17:42 +0000764"modf(x)\n"
765"\n"
766"Return the fractional and integer parts of x. Both results carry the sign\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000767"of x. The integer part is returned as a real.");
Guido van Rossumc6e22901998-12-04 19:26:43 +0000768
Tim Peters78526162001-09-05 00:53:45 +0000769/* A decent logarithm is easy to compute even for huge longs, but libm can't
770 do that by itself -- loghelper can. func is log or log10, and name is
771 "log" or "log10". Note that overflow isn't possible: a long can contain
772 no more than INT_MAX * SHIFT bits, so has value certainly less than
773 2**(2**64 * 2**16) == 2**2**80, and log2 of that is 2**80, which is
774 small enough to fit in an IEEE single. log and log10 are even smaller.
775*/
776
777static PyObject*
Neal Norwitz45e230a2006-11-19 21:26:53 +0000778loghelper(PyObject* arg, double (*func)(double), char *funcname)
Tim Peters78526162001-09-05 00:53:45 +0000779{
Tim Peters78526162001-09-05 00:53:45 +0000780 /* If it is long, do it ourselves. */
781 if (PyLong_Check(arg)) {
782 double x;
783 int e;
784 x = _PyLong_AsScaledDouble(arg, &e);
785 if (x <= 0.0) {
786 PyErr_SetString(PyExc_ValueError,
787 "math domain error");
788 return NULL;
789 }
Christian Heimes543cabc2008-01-25 14:54:23 +0000790 /* Value is ~= x * 2**(e*PyLong_SHIFT), so the log ~=
791 log(x) + log(2) * e * PyLong_SHIFT.
792 CAUTION: e*PyLong_SHIFT may overflow using int arithmetic,
Tim Peters78526162001-09-05 00:53:45 +0000793 so force use of double. */
Christian Heimes543cabc2008-01-25 14:54:23 +0000794 x = func(x) + (e * (double)PyLong_SHIFT) * func(2.0);
Tim Peters78526162001-09-05 00:53:45 +0000795 return PyFloat_FromDouble(x);
796 }
797
798 /* Else let libm handle it by itself. */
Christian Heimes6f341092008-04-18 23:13:07 +0000799 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +0000800}
801
802static PyObject *
803math_log(PyObject *self, PyObject *args)
804{
Raymond Hettinger866964c2002-12-14 19:51:34 +0000805 PyObject *arg;
806 PyObject *base = NULL;
807 PyObject *num, *den;
808 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +0000809
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000810 if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base))
Raymond Hettinger866964c2002-12-14 19:51:34 +0000811 return NULL;
Raymond Hettinger866964c2002-12-14 19:51:34 +0000812
Mark Dickinson4c96fa52008-12-11 19:28:08 +0000813 num = loghelper(arg, m_log, "log");
Neal Norwitz45e230a2006-11-19 21:26:53 +0000814 if (num == NULL || base == NULL)
815 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +0000816
Mark Dickinson4c96fa52008-12-11 19:28:08 +0000817 den = loghelper(base, m_log, "log");
Raymond Hettinger866964c2002-12-14 19:51:34 +0000818 if (den == NULL) {
819 Py_DECREF(num);
820 return NULL;
821 }
822
823 ans = PyNumber_Divide(num, den);
824 Py_DECREF(num);
825 Py_DECREF(den);
826 return ans;
Tim Peters78526162001-09-05 00:53:45 +0000827}
828
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000829PyDoc_STRVAR(math_log_doc,
Raymond Hettinger866964c2002-12-14 19:51:34 +0000830"log(x[, base]) -> the logarithm of x to the given base.\n\
831If the base not specified, returns the natural logarithm (base e) of x.");
Tim Peters78526162001-09-05 00:53:45 +0000832
833static PyObject *
Neal Norwitz45e230a2006-11-19 21:26:53 +0000834math_log10(PyObject *self, PyObject *arg)
Tim Peters78526162001-09-05 00:53:45 +0000835{
Mark Dickinson4c96fa52008-12-11 19:28:08 +0000836 return loghelper(arg, m_log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +0000837}
838
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000839PyDoc_STRVAR(math_log10_doc,
840"log10(x) -> the base 10 logarithm of x.");
Tim Peters78526162001-09-05 00:53:45 +0000841
Christian Heimes6f341092008-04-18 23:13:07 +0000842static PyObject *
843math_fmod(PyObject *self, PyObject *args)
844{
845 PyObject *ox, *oy;
846 double r, x, y;
847 if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy))
848 return NULL;
849 x = PyFloat_AsDouble(ox);
850 y = PyFloat_AsDouble(oy);
851 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
852 return NULL;
853 /* fmod(x, +/-Inf) returns x for finite x. */
854 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
855 return PyFloat_FromDouble(x);
856 errno = 0;
857 PyFPE_START_PROTECT("in math_fmod", return 0);
858 r = fmod(x, y);
859 PyFPE_END_PROTECT(r);
860 if (Py_IS_NAN(r)) {
861 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
862 errno = EDOM;
863 else
864 errno = 0;
865 }
866 if (errno && is_error(r))
867 return NULL;
868 else
869 return PyFloat_FromDouble(r);
870}
871
872PyDoc_STRVAR(math_fmod_doc,
873"fmod(x,y)\n\nReturn fmod(x, y), according to platform C."
874" x % y may differ.");
875
876static PyObject *
877math_hypot(PyObject *self, PyObject *args)
878{
879 PyObject *ox, *oy;
880 double r, x, y;
881 if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy))
882 return NULL;
883 x = PyFloat_AsDouble(ox);
884 y = PyFloat_AsDouble(oy);
885 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
886 return NULL;
887 /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */
888 if (Py_IS_INFINITY(x))
889 return PyFloat_FromDouble(fabs(x));
890 if (Py_IS_INFINITY(y))
891 return PyFloat_FromDouble(fabs(y));
892 errno = 0;
893 PyFPE_START_PROTECT("in math_hypot", return 0);
894 r = hypot(x, y);
895 PyFPE_END_PROTECT(r);
896 if (Py_IS_NAN(r)) {
897 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
898 errno = EDOM;
899 else
900 errno = 0;
901 }
902 else if (Py_IS_INFINITY(r)) {
903 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
904 errno = ERANGE;
905 else
906 errno = 0;
907 }
908 if (errno && is_error(r))
909 return NULL;
910 else
911 return PyFloat_FromDouble(r);
912}
913
914PyDoc_STRVAR(math_hypot_doc,
915"hypot(x,y)\n\nReturn the Euclidean distance, sqrt(x*x + y*y).");
916
917/* pow can't use math_2, but needs its own wrapper: the problem is
918 that an infinite result can arise either as a result of overflow
919 (in which case OverflowError should be raised) or as a result of
920 e.g. 0.**-5. (for which ValueError needs to be raised.)
921*/
922
923static PyObject *
924math_pow(PyObject *self, PyObject *args)
925{
926 PyObject *ox, *oy;
927 double r, x, y;
Mark Dickinsoncec3f132008-04-20 04:13:13 +0000928 int odd_y;
Christian Heimes6f341092008-04-18 23:13:07 +0000929
930 if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy))
931 return NULL;
932 x = PyFloat_AsDouble(ox);
933 y = PyFloat_AsDouble(oy);
934 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
935 return NULL;
Mark Dickinsona1293eb2008-04-19 19:41:52 +0000936
Mark Dickinsoncec3f132008-04-20 04:13:13 +0000937 /* deal directly with IEEE specials, to cope with problems on various
938 platforms whose semantics don't exactly match C99 */
Mark Dickinson0da94c82008-04-21 01:55:50 +0000939 r = 0.; /* silence compiler warning */
Mark Dickinsoncec3f132008-04-20 04:13:13 +0000940 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
941 errno = 0;
942 if (Py_IS_NAN(x))
943 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
944 else if (Py_IS_NAN(y))
945 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
946 else if (Py_IS_INFINITY(x)) {
947 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
948 if (y > 0.)
949 r = odd_y ? x : fabs(x);
950 else if (y == 0.)
951 r = 1.;
952 else /* y < 0. */
953 r = odd_y ? copysign(0., x) : 0.;
954 }
955 else if (Py_IS_INFINITY(y)) {
956 if (fabs(x) == 1.0)
957 r = 1.;
958 else if (y > 0. && fabs(x) > 1.0)
959 r = y;
960 else if (y < 0. && fabs(x) < 1.0) {
961 r = -y; /* result is +inf */
962 if (x == 0.) /* 0**-inf: divide-by-zero */
963 errno = EDOM;
964 }
965 else
966 r = 0.;
967 }
Mark Dickinsone941d972008-04-19 18:51:48 +0000968 }
Mark Dickinsoncec3f132008-04-20 04:13:13 +0000969 else {
970 /* let libm handle finite**finite */
971 errno = 0;
972 PyFPE_START_PROTECT("in math_pow", return 0);
973 r = pow(x, y);
974 PyFPE_END_PROTECT(r);
975 /* a NaN result should arise only from (-ve)**(finite
976 non-integer); in this case we want to raise ValueError. */
977 if (!Py_IS_FINITE(r)) {
978 if (Py_IS_NAN(r)) {
979 errno = EDOM;
980 }
981 /*
982 an infinite result here arises either from:
983 (A) (+/-0.)**negative (-> divide-by-zero)
984 (B) overflow of x**y with x and y finite
985 */
986 else if (Py_IS_INFINITY(r)) {
987 if (x == 0.)
988 errno = EDOM;
989 else
990 errno = ERANGE;
991 }
992 }
Christian Heimes6f341092008-04-18 23:13:07 +0000993 }
994
995 if (errno && is_error(r))
996 return NULL;
997 else
998 return PyFloat_FromDouble(r);
999}
1000
1001PyDoc_STRVAR(math_pow_doc,
1002"pow(x,y)\n\nReturn x**y (x to the power of y).");
1003
Christian Heimese2ca4242008-01-03 20:23:15 +00001004static const double degToRad = Py_MATH_PI / 180.0;
1005static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001006
1007static PyObject *
Neal Norwitz45e230a2006-11-19 21:26:53 +00001008math_degrees(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001009{
Neal Norwitz45e230a2006-11-19 21:26:53 +00001010 double x = PyFloat_AsDouble(arg);
1011 if (x == -1.0 && PyErr_Occurred())
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001012 return NULL;
Christian Heimese2ca4242008-01-03 20:23:15 +00001013 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001014}
1015
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001016PyDoc_STRVAR(math_degrees_doc,
1017"degrees(x) -> converts angle x from radians to degrees");
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001018
1019static PyObject *
Neal Norwitz45e230a2006-11-19 21:26:53 +00001020math_radians(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001021{
Neal Norwitz45e230a2006-11-19 21:26:53 +00001022 double x = PyFloat_AsDouble(arg);
1023 if (x == -1.0 && PyErr_Occurred())
Raymond Hettingerd6f22672002-05-13 03:56:10 +00001024 return NULL;
1025 return PyFloat_FromDouble(x * degToRad);
1026}
1027
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001028PyDoc_STRVAR(math_radians_doc,
1029"radians(x) -> converts angle x from degrees to radians");
Tim Peters78526162001-09-05 00:53:45 +00001030
Christian Heimese2ca4242008-01-03 20:23:15 +00001031static PyObject *
1032math_isnan(PyObject *self, PyObject *arg)
1033{
1034 double x = PyFloat_AsDouble(arg);
1035 if (x == -1.0 && PyErr_Occurred())
1036 return NULL;
1037 return PyBool_FromLong((long)Py_IS_NAN(x));
1038}
1039
1040PyDoc_STRVAR(math_isnan_doc,
1041"isnan(x) -> bool\n\
1042Checks if float x is not a number (NaN)");
1043
1044static PyObject *
1045math_isinf(PyObject *self, PyObject *arg)
1046{
1047 double x = PyFloat_AsDouble(arg);
1048 if (x == -1.0 && PyErr_Occurred())
1049 return NULL;
1050 return PyBool_FromLong((long)Py_IS_INFINITY(x));
1051}
1052
1053PyDoc_STRVAR(math_isinf_doc,
1054"isinf(x) -> bool\n\
1055Checks if float x is infinite (positive or negative)");
1056
Barry Warsaw8b43b191996-12-09 22:32:36 +00001057static PyMethodDef math_methods[] = {
Neal Norwitz45e230a2006-11-19 21:26:53 +00001058 {"acos", math_acos, METH_O, math_acos_doc},
Christian Heimes6f341092008-04-18 23:13:07 +00001059 {"acosh", math_acosh, METH_O, math_acosh_doc},
Neal Norwitz45e230a2006-11-19 21:26:53 +00001060 {"asin", math_asin, METH_O, math_asin_doc},
Christian Heimes6f341092008-04-18 23:13:07 +00001061 {"asinh", math_asinh, METH_O, math_asinh_doc},
Neal Norwitz45e230a2006-11-19 21:26:53 +00001062 {"atan", math_atan, METH_O, math_atan_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001063 {"atan2", math_atan2, METH_VARARGS, math_atan2_doc},
Christian Heimes6f341092008-04-18 23:13:07 +00001064 {"atanh", math_atanh, METH_O, math_atanh_doc},
Neal Norwitz45e230a2006-11-19 21:26:53 +00001065 {"ceil", math_ceil, METH_O, math_ceil_doc},
Christian Heimeseebb79c2008-01-03 22:32:26 +00001066 {"copysign", math_copysign, METH_VARARGS, math_copysign_doc},
Neal Norwitz45e230a2006-11-19 21:26:53 +00001067 {"cos", math_cos, METH_O, math_cos_doc},
1068 {"cosh", math_cosh, METH_O, math_cosh_doc},
1069 {"degrees", math_degrees, METH_O, math_degrees_doc},
1070 {"exp", math_exp, METH_O, math_exp_doc},
1071 {"fabs", math_fabs, METH_O, math_fabs_doc},
Raymond Hettingerecbdd2e2008-06-09 06:54:45 +00001072 {"factorial", math_factorial, METH_O, math_factorial_doc},
Neal Norwitz45e230a2006-11-19 21:26:53 +00001073 {"floor", math_floor, METH_O, math_floor_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001074 {"fmod", math_fmod, METH_VARARGS, math_fmod_doc},
Neal Norwitz45e230a2006-11-19 21:26:53 +00001075 {"frexp", math_frexp, METH_O, math_frexp_doc},
Mark Dickinsonfef6b132008-07-30 16:20:10 +00001076 {"fsum", math_fsum, METH_O, math_fsum_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001077 {"hypot", math_hypot, METH_VARARGS, math_hypot_doc},
Christian Heimese2ca4242008-01-03 20:23:15 +00001078 {"isinf", math_isinf, METH_O, math_isinf_doc},
1079 {"isnan", math_isnan, METH_O, math_isnan_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001080 {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc},
1081 {"log", math_log, METH_VARARGS, math_log_doc},
Christian Heimes6f341092008-04-18 23:13:07 +00001082 {"log1p", math_log1p, METH_O, math_log1p_doc},
Neal Norwitz45e230a2006-11-19 21:26:53 +00001083 {"log10", math_log10, METH_O, math_log10_doc},
1084 {"modf", math_modf, METH_O, math_modf_doc},
Fred Drake40c48682000-07-03 18:11:56 +00001085 {"pow", math_pow, METH_VARARGS, math_pow_doc},
Neal Norwitz45e230a2006-11-19 21:26:53 +00001086 {"radians", math_radians, METH_O, math_radians_doc},
1087 {"sin", math_sin, METH_O, math_sin_doc},
1088 {"sinh", math_sinh, METH_O, math_sinh_doc},
1089 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
1090 {"tan", math_tan, METH_O, math_tan_doc},
1091 {"tanh", math_tanh, METH_O, math_tanh_doc},
Mark Dickinsonfef6b132008-07-30 16:20:10 +00001092 {"trunc", math_trunc, METH_O, math_trunc_doc},
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001093 {NULL, NULL} /* sentinel */
1094};
1095
Guido van Rossumc6e22901998-12-04 19:26:43 +00001096
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001097PyDoc_STRVAR(module_doc,
Tim Peters63c94532001-09-04 23:17:42 +00001098"This module is always available. It provides access to the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001099"mathematical functions defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00001100
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001101PyMODINIT_FUNC
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001102initmath(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001103{
Christian Heimes6f341092008-04-18 23:13:07 +00001104 PyObject *m;
Tim Petersfe71f812001-08-07 22:10:00 +00001105
Guido van Rossumc6e22901998-12-04 19:26:43 +00001106 m = Py_InitModule3("math", math_methods, module_doc);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00001107 if (m == NULL)
1108 goto finally;
Barry Warsawfc93f751996-12-17 00:47:03 +00001109
Christian Heimes6f341092008-04-18 23:13:07 +00001110 PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
1111 PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
Barry Warsawfc93f751996-12-17 00:47:03 +00001112
Christian Heimes6f341092008-04-18 23:13:07 +00001113 finally:
Barry Warsaw9bfd2bf2000-09-01 09:01:32 +00001114 return;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001115}