blob: 45d842f3907226ea0b35f6391d73460aaf9d64b3 [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).
Tim Peters1d120612000-10-12 06:10:25 +000085 */
86 if (x)
Tim Petersfe71f812001-08-07 22:10:00 +000087 PyErr_SetString(PyExc_OverflowError,
Tim Peters1d120612000-10-12 06:10:25 +000088 "math range error");
89 else
90 result = 0;
91 }
Guido van Rossum8832b621991-12-16 15:44:24 +000092 else
Barry Warsaw8b43b191996-12-09 22:32:36 +000093 /* Unexpected math error */
94 PyErr_SetFromErrno(PyExc_ValueError);
Tim Peters1d120612000-10-12 06:10:25 +000095 return result;
Guido van Rossum8832b621991-12-16 15:44:24 +000096}
97
Christian Heimes53876d92008-04-19 00:31:39 +000098/*
Christian Heimese57950f2008-04-21 13:08:03 +000099 wrapper for atan2 that deals directly with special cases before
100 delegating to the platform libm for the remaining cases. This
101 is necessary to get consistent behaviour across platforms.
102 Windows, FreeBSD and alpha Tru64 are amongst platforms that don't
103 always follow C99.
104*/
105
106static double
107m_atan2(double y, double x)
108{
109 if (Py_IS_NAN(x) || Py_IS_NAN(y))
110 return Py_NAN;
111 if (Py_IS_INFINITY(y)) {
112 if (Py_IS_INFINITY(x)) {
113 if (copysign(1., x) == 1.)
114 /* atan2(+-inf, +inf) == +-pi/4 */
115 return copysign(0.25*Py_MATH_PI, y);
116 else
117 /* atan2(+-inf, -inf) == +-pi*3/4 */
118 return copysign(0.75*Py_MATH_PI, y);
119 }
120 /* atan2(+-inf, x) == +-pi/2 for finite x */
121 return copysign(0.5*Py_MATH_PI, y);
122 }
123 if (Py_IS_INFINITY(x) || y == 0.) {
124 if (copysign(1., x) == 1.)
125 /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */
126 return copysign(0., y);
127 else
128 /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */
129 return copysign(Py_MATH_PI, y);
130 }
131 return atan2(y, x);
132}
133
134/*
Christian Heimes53876d92008-04-19 00:31:39 +0000135 math_1 is used to wrap a libm function f that takes a double
136 arguments and returns a double.
137
138 The error reporting follows these rules, which are designed to do
139 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
140 platforms.
141
142 - a NaN result from non-NaN inputs causes ValueError to be raised
143 - an infinite result from finite inputs causes OverflowError to be
144 raised if can_overflow is 1, or raises ValueError if can_overflow
145 is 0.
146 - if the result is finite and errno == EDOM then ValueError is
147 raised
148 - if the result is finite and nonzero and errno == ERANGE then
149 OverflowError is raised
150
151 The last rule is used to catch overflow on platforms which follow
152 C89 but for which HUGE_VAL is not an infinity.
153
154 For the majority of one-argument functions these rules are enough
155 to ensure that Python's functions behave as specified in 'Annex F'
156 of the C99 standard, with the 'invalid' and 'divide-by-zero'
157 floating-point exceptions mapping to Python's ValueError and the
158 'overflow' floating-point exception mapping to OverflowError.
159 math_1 only works for functions that don't have singularities *and*
160 the possibility of overflow; fortunately, that covers everything we
161 care about right now.
162*/
163
Barry Warsaw8b43b191996-12-09 22:32:36 +0000164static PyObject *
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000165math_1_to_whatever(PyObject *arg, double (*func) (double),
Christian Heimes53876d92008-04-19 00:31:39 +0000166 PyObject *(*from_double_func) (double),
167 int can_overflow)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000168{
Christian Heimes53876d92008-04-19 00:31:39 +0000169 double x, r;
170 x = PyFloat_AsDouble(arg);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000171 if (x == -1.0 && PyErr_Occurred())
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000172 return NULL;
173 errno = 0;
Christian Heimes53876d92008-04-19 00:31:39 +0000174 PyFPE_START_PROTECT("in math_1", return 0);
175 r = (*func)(x);
176 PyFPE_END_PROTECT(r);
Mark Dickinsona0de26c2008-04-30 23:30:57 +0000177 if (Py_IS_NAN(r) && !Py_IS_NAN(x)) {
178 PyErr_SetString(PyExc_ValueError,
179 "math domain error (invalid argument)");
180 return NULL;
Christian Heimes53876d92008-04-19 00:31:39 +0000181 }
Mark Dickinsona0de26c2008-04-30 23:30:57 +0000182 if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) {
183 if (can_overflow)
184 PyErr_SetString(PyExc_OverflowError,
185 "math range error (overflow)");
Mark Dickinsonb63aff12008-05-09 14:10:27 +0000186 else
187 PyErr_SetString(PyExc_ValueError,
188 "math domain error (singularity)");
Mark Dickinsona0de26c2008-04-30 23:30:57 +0000189 return NULL;
Christian Heimes53876d92008-04-19 00:31:39 +0000190 }
Mark Dickinsonde429622008-05-01 00:19:23 +0000191 if (Py_IS_FINITE(r) && errno && is_error(r))
192 /* this branch unnecessary on most platforms */
Tim Peters1d120612000-10-12 06:10:25 +0000193 return NULL;
Mark Dickinsonde429622008-05-01 00:19:23 +0000194
195 return (*from_double_func)(r);
Christian Heimes53876d92008-04-19 00:31:39 +0000196}
197
198/*
199 math_2 is used to wrap a libm function f that takes two double
200 arguments and returns a double.
201
202 The error reporting follows these rules, which are designed to do
203 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
204 platforms.
205
206 - a NaN result from non-NaN inputs causes ValueError to be raised
207 - an infinite result from finite inputs causes OverflowError to be
208 raised.
209 - if the result is finite and errno == EDOM then ValueError is
210 raised
211 - if the result is finite and nonzero and errno == ERANGE then
212 OverflowError is raised
213
214 The last rule is used to catch overflow on platforms which follow
215 C89 but for which HUGE_VAL is not an infinity.
216
217 For most two-argument functions (copysign, fmod, hypot, atan2)
218 these rules are enough to ensure that Python's functions behave as
219 specified in 'Annex F' of the C99 standard, with the 'invalid' and
220 'divide-by-zero' floating-point exceptions mapping to Python's
221 ValueError and the 'overflow' floating-point exception mapping to
222 OverflowError.
223*/
224
225static PyObject *
226math_1(PyObject *arg, double (*func) (double), int can_overflow)
227{
228 return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow);
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000229}
230
231static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000232math_1_to_int(PyObject *arg, double (*func) (double), int can_overflow)
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000233{
Christian Heimes53876d92008-04-19 00:31:39 +0000234 return math_1_to_whatever(arg, func, PyLong_FromDouble, can_overflow);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000235}
236
Barry Warsaw8b43b191996-12-09 22:32:36 +0000237static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +0000238math_2(PyObject *args, double (*func) (double, double), char *funcname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000239{
Thomas Wouters89f507f2006-12-13 04:49:30 +0000240 PyObject *ox, *oy;
Christian Heimes53876d92008-04-19 00:31:39 +0000241 double x, y, r;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000242 if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy))
243 return NULL;
244 x = PyFloat_AsDouble(ox);
245 y = PyFloat_AsDouble(oy);
246 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000247 return NULL;
248 errno = 0;
Christian Heimes53876d92008-04-19 00:31:39 +0000249 PyFPE_START_PROTECT("in math_2", return 0);
250 r = (*func)(x, y);
251 PyFPE_END_PROTECT(r);
252 if (Py_IS_NAN(r)) {
253 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
254 errno = EDOM;
255 else
256 errno = 0;
257 }
258 else if (Py_IS_INFINITY(r)) {
259 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
260 errno = ERANGE;
261 else
262 errno = 0;
263 }
264 if (errno && is_error(r))
Tim Peters1d120612000-10-12 06:10:25 +0000265 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000266 else
Christian Heimes53876d92008-04-19 00:31:39 +0000267 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000268}
269
Christian Heimes53876d92008-04-19 00:31:39 +0000270#define FUNC1(funcname, func, can_overflow, docstring) \
Fred Drake40c48682000-07-03 18:11:56 +0000271 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
Christian Heimes53876d92008-04-19 00:31:39 +0000272 return math_1(args, func, can_overflow); \
Guido van Rossumc6e22901998-12-04 19:26:43 +0000273 }\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000274 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000275
Fred Drake40c48682000-07-03 18:11:56 +0000276#define FUNC2(funcname, func, docstring) \
277 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
Thomas Wouters89f507f2006-12-13 04:49:30 +0000278 return math_2(args, func, #funcname); \
Guido van Rossumc6e22901998-12-04 19:26:43 +0000279 }\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000280 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000281
Christian Heimes53876d92008-04-19 00:31:39 +0000282FUNC1(acos, acos, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000283 "acos(x)\n\nReturn the arc cosine (measured in radians) of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000284FUNC1(acosh, acosh, 0,
285 "acosh(x)\n\nReturn the hyperbolic arc cosine (measured in radians) of x.")
286FUNC1(asin, asin, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000287 "asin(x)\n\nReturn the arc sine (measured in radians) of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000288FUNC1(asinh, asinh, 0,
289 "asinh(x)\n\nReturn the hyperbolic arc sine (measured in radians) of x.")
290FUNC1(atan, atan, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000291 "atan(x)\n\nReturn the arc tangent (measured in radians) of x.")
Christian Heimese57950f2008-04-21 13:08:03 +0000292FUNC2(atan2, m_atan2,
Tim Petersfe71f812001-08-07 22:10:00 +0000293 "atan2(y, x)\n\nReturn the arc tangent (measured in radians) of y/x.\n"
294 "Unlike atan(y/x), the signs of both x and y are considered.")
Christian Heimes53876d92008-04-19 00:31:39 +0000295FUNC1(atanh, atanh, 0,
296 "atanh(x)\n\nReturn the hyperbolic arc tangent (measured in radians) of x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +0000297
298static PyObject * math_ceil(PyObject *self, PyObject *number) {
299 static PyObject *ceil_str = NULL;
300 PyObject *method;
301
302 if (ceil_str == NULL) {
Christian Heimesfe82e772008-01-28 02:38:20 +0000303 ceil_str = PyUnicode_InternFromString("__ceil__");
Guido van Rossum13e05de2007-08-23 22:56:55 +0000304 if (ceil_str == NULL)
305 return NULL;
306 }
307
Christian Heimes90aa7642007-12-19 02:45:37 +0000308 method = _PyType_Lookup(Py_TYPE(number), ceil_str);
Guido van Rossum13e05de2007-08-23 22:56:55 +0000309 if (method == NULL)
Christian Heimes53876d92008-04-19 00:31:39 +0000310 return math_1_to_int(number, ceil, 0);
Guido van Rossum13e05de2007-08-23 22:56:55 +0000311 else
312 return PyObject_CallFunction(method, "O", number);
313}
314
315PyDoc_STRVAR(math_ceil_doc,
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000316 "ceil(x)\n\nReturn the ceiling of x as an int.\n"
Guido van Rossum13e05de2007-08-23 22:56:55 +0000317 "This is the smallest integral value >= x.");
318
Christian Heimes072c0f12008-01-03 23:01:04 +0000319FUNC2(copysign, copysign,
Christian Heimes53876d92008-04-19 00:31:39 +0000320 "copysign(x,y)\n\nReturn x with the sign of y.")
321FUNC1(cos, cos, 0,
322 "cos(x)\n\nReturn the cosine of x (measured in radians).")
323FUNC1(cosh, cosh, 1,
324 "cosh(x)\n\nReturn the hyperbolic cosine of x.")
325FUNC1(exp, exp, 1,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000326 "exp(x)\n\nReturn e raised to the power of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000327FUNC1(fabs, fabs, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000328 "fabs(x)\n\nReturn the absolute value of the float x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +0000329
330static PyObject * math_floor(PyObject *self, PyObject *number) {
331 static PyObject *floor_str = NULL;
332 PyObject *method;
333
334 if (floor_str == NULL) {
Christian Heimesfe82e772008-01-28 02:38:20 +0000335 floor_str = PyUnicode_InternFromString("__floor__");
Guido van Rossum13e05de2007-08-23 22:56:55 +0000336 if (floor_str == NULL)
337 return NULL;
338 }
339
Christian Heimes90aa7642007-12-19 02:45:37 +0000340 method = _PyType_Lookup(Py_TYPE(number), floor_str);
Guido van Rossum13e05de2007-08-23 22:56:55 +0000341 if (method == NULL)
Christian Heimes53876d92008-04-19 00:31:39 +0000342 return math_1_to_int(number, floor, 0);
Guido van Rossum13e05de2007-08-23 22:56:55 +0000343 else
344 return PyObject_CallFunction(method, "O", number);
345}
346
347PyDoc_STRVAR(math_floor_doc,
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000348 "floor(x)\n\nReturn the floor of x as an int.\n"
Guido van Rossum13e05de2007-08-23 22:56:55 +0000349 "This is the largest integral value <= x.");
350
Christian Heimes53876d92008-04-19 00:31:39 +0000351FUNC1(log1p, log1p, 1,
352 "log1p(x)\n\nReturn the natural logarithm of 1+x (base e).\n\
353 The result is computed in a way which is accurate for x near zero.")
354FUNC1(sin, sin, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000355 "sin(x)\n\nReturn the sine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +0000356FUNC1(sinh, sinh, 1,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000357 "sinh(x)\n\nReturn the hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000358FUNC1(sqrt, sqrt, 0,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000359 "sqrt(x)\n\nReturn the square root of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000360FUNC1(tan, tan, 0,
Tim Petersfe71f812001-08-07 22:10:00 +0000361 "tan(x)\n\nReturn the tangent of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +0000362FUNC1(tanh, tanh, 0,
Guido van Rossumc6e22901998-12-04 19:26:43 +0000363 "tanh(x)\n\nReturn the hyperbolic tangent of x.")
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000364
Barry Warsaw8b43b191996-12-09 22:32:36 +0000365static PyObject *
Christian Heimes400adb02008-02-01 08:12:03 +0000366math_trunc(PyObject *self, PyObject *number)
367{
368 static PyObject *trunc_str = NULL;
369 PyObject *trunc;
370
371 if (Py_TYPE(number)->tp_dict == NULL) {
372 if (PyType_Ready(Py_TYPE(number)) < 0)
373 return NULL;
374 }
375
376 if (trunc_str == NULL) {
377 trunc_str = PyUnicode_InternFromString("__trunc__");
378 if (trunc_str == NULL)
379 return NULL;
380 }
381
382 trunc = _PyType_Lookup(Py_TYPE(number), trunc_str);
383 if (trunc == NULL) {
384 PyErr_Format(PyExc_TypeError,
385 "type %.100s doesn't define __trunc__ method",
386 Py_TYPE(number)->tp_name);
387 return NULL;
388 }
389 return PyObject_CallFunctionObjArgs(trunc, number, NULL);
390}
391
392PyDoc_STRVAR(math_trunc_doc,
393"trunc(x:Real) -> Integral\n"
394"\n"
Christian Heimes292d3512008-02-03 16:51:08 +0000395"Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.");
Christian Heimes400adb02008-02-01 08:12:03 +0000396
397static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +0000398math_frexp(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +0000399{
Guido van Rossumd18ad581991-10-24 14:57:21 +0000400 int i;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000401 double x = PyFloat_AsDouble(arg);
402 if (x == -1.0 && PyErr_Occurred())
Guido van Rossumd18ad581991-10-24 14:57:21 +0000403 return NULL;
Christian Heimes53876d92008-04-19 00:31:39 +0000404 /* deal with special cases directly, to sidestep platform
405 differences */
406 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
407 i = 0;
408 }
409 else {
410 PyFPE_START_PROTECT("in math_frexp", return 0);
411 x = frexp(x, &i);
412 PyFPE_END_PROTECT(x);
413 }
414 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +0000415}
416
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000417PyDoc_STRVAR(math_frexp_doc,
Tim Peters63c94532001-09-04 23:17:42 +0000418"frexp(x)\n"
419"\n"
420"Return the mantissa and exponent of x, as pair (m, e).\n"
421"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 +0000422"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 +0000423
Barry Warsaw8b43b191996-12-09 22:32:36 +0000424static PyObject *
Fred Drake40c48682000-07-03 18:11:56 +0000425math_ldexp(PyObject *self, PyObject *args)
Guido van Rossumd18ad581991-10-24 14:57:21 +0000426{
Christian Heimes53876d92008-04-19 00:31:39 +0000427 double x, r;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000428 PyObject *oexp;
429 long exp;
430 if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp))
Guido van Rossumd18ad581991-10-24 14:57:21 +0000431 return NULL;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000432
433 if (PyLong_Check(oexp)) {
434 /* on overflow, replace exponent with either LONG_MAX
435 or LONG_MIN, depending on the sign. */
436 exp = PyLong_AsLong(oexp);
437 if (exp == -1 && PyErr_Occurred()) {
438 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
439 if (Py_SIZE(oexp) < 0) {
440 exp = LONG_MIN;
441 }
442 else {
443 exp = LONG_MAX;
444 }
445 PyErr_Clear();
446 }
447 else {
448 /* propagate any unexpected exception */
449 return NULL;
450 }
451 }
452 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000453 else {
454 PyErr_SetString(PyExc_TypeError,
455 "Expected an int or long as second argument "
456 "to ldexp.");
457 return NULL;
458 }
459
460 if (x == 0. || !Py_IS_FINITE(x)) {
461 /* NaNs, zeros and infinities are returned unchanged */
462 r = x;
Christian Heimes53876d92008-04-19 00:31:39 +0000463 errno = 0;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000464 } else if (exp > INT_MAX) {
465 /* overflow */
466 r = copysign(Py_HUGE_VAL, x);
467 errno = ERANGE;
468 } else if (exp < INT_MIN) {
469 /* underflow to +-0 */
470 r = copysign(0., x);
471 errno = 0;
472 } else {
473 errno = 0;
474 PyFPE_START_PROTECT("in math_ldexp", return 0);
475 r = ldexp(x, (int)exp);
476 PyFPE_END_PROTECT(r);
477 if (Py_IS_INFINITY(r))
478 errno = ERANGE;
479 }
480
Christian Heimes53876d92008-04-19 00:31:39 +0000481 if (errno && is_error(r))
Tim Peters1d120612000-10-12 06:10:25 +0000482 return NULL;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000483 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +0000484}
485
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000486PyDoc_STRVAR(math_ldexp_doc,
487"ldexp(x, i) -> x * (2**i)");
Guido van Rossumc6e22901998-12-04 19:26:43 +0000488
Barry Warsaw8b43b191996-12-09 22:32:36 +0000489static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +0000490math_modf(PyObject *self, PyObject *arg)
Guido van Rossumd18ad581991-10-24 14:57:21 +0000491{
Thomas Wouters89f507f2006-12-13 04:49:30 +0000492 double y, x = PyFloat_AsDouble(arg);
493 if (x == -1.0 && PyErr_Occurred())
Guido van Rossumd18ad581991-10-24 14:57:21 +0000494 return NULL;
Christian Heimesa342c012008-04-20 21:01:16 +0000495 /* some platforms don't do the right thing for NaNs and
496 infinities, so we take care of special cases directly. */
497 if (!Py_IS_FINITE(x)) {
498 if (Py_IS_INFINITY(x))
499 return Py_BuildValue("(dd)", copysign(0., x), x);
500 else if (Py_IS_NAN(x))
501 return Py_BuildValue("(dd)", x, x);
502 }
503
Guido van Rossumd18ad581991-10-24 14:57:21 +0000504 errno = 0;
Christian Heimes53876d92008-04-19 00:31:39 +0000505 PyFPE_START_PROTECT("in math_modf", return 0);
Guido van Rossumd18ad581991-10-24 14:57:21 +0000506 x = modf(x, &y);
Christian Heimes53876d92008-04-19 00:31:39 +0000507 PyFPE_END_PROTECT(x);
508 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +0000509}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000510
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000511PyDoc_STRVAR(math_modf_doc,
Tim Peters63c94532001-09-04 23:17:42 +0000512"modf(x)\n"
513"\n"
514"Return the fractional and integer parts of x. Both results carry the sign\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000515"of x. The integer part is returned as a real.");
Guido van Rossumc6e22901998-12-04 19:26:43 +0000516
Tim Peters78526162001-09-05 00:53:45 +0000517/* A decent logarithm is easy to compute even for huge longs, but libm can't
518 do that by itself -- loghelper can. func is log or log10, and name is
519 "log" or "log10". Note that overflow isn't possible: a long can contain
520 no more than INT_MAX * SHIFT bits, so has value certainly less than
521 2**(2**64 * 2**16) == 2**2**80, and log2 of that is 2**80, which is
522 small enough to fit in an IEEE single. log and log10 are even smaller.
523*/
524
525static PyObject*
Thomas Wouters89f507f2006-12-13 04:49:30 +0000526loghelper(PyObject* arg, double (*func)(double), char *funcname)
Tim Peters78526162001-09-05 00:53:45 +0000527{
Tim Peters78526162001-09-05 00:53:45 +0000528 /* If it is long, do it ourselves. */
529 if (PyLong_Check(arg)) {
530 double x;
531 int e;
532 x = _PyLong_AsScaledDouble(arg, &e);
533 if (x <= 0.0) {
534 PyErr_SetString(PyExc_ValueError,
535 "math domain error");
536 return NULL;
537 }
Christian Heimesaf98da12008-01-27 15:18:18 +0000538 /* Value is ~= x * 2**(e*PyLong_SHIFT), so the log ~=
539 log(x) + log(2) * e * PyLong_SHIFT.
540 CAUTION: e*PyLong_SHIFT may overflow using int arithmetic,
Tim Peters78526162001-09-05 00:53:45 +0000541 so force use of double. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000542 x = func(x) + (e * (double)PyLong_SHIFT) * func(2.0);
Tim Peters78526162001-09-05 00:53:45 +0000543 return PyFloat_FromDouble(x);
544 }
545
546 /* Else let libm handle it by itself. */
Christian Heimes53876d92008-04-19 00:31:39 +0000547 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +0000548}
549
550static PyObject *
551math_log(PyObject *self, PyObject *args)
552{
Raymond Hettinger866964c2002-12-14 19:51:34 +0000553 PyObject *arg;
554 PyObject *base = NULL;
555 PyObject *num, *den;
556 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +0000557
Raymond Hettingerea3fdf42002-12-29 16:33:45 +0000558 if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base))
Raymond Hettinger866964c2002-12-14 19:51:34 +0000559 return NULL;
Raymond Hettinger866964c2002-12-14 19:51:34 +0000560
Thomas Wouters89f507f2006-12-13 04:49:30 +0000561 num = loghelper(arg, log, "log");
562 if (num == NULL || base == NULL)
563 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +0000564
Thomas Wouters89f507f2006-12-13 04:49:30 +0000565 den = loghelper(base, log, "log");
Raymond Hettinger866964c2002-12-14 19:51:34 +0000566 if (den == NULL) {
567 Py_DECREF(num);
568 return NULL;
569 }
570
Neal Norwitzbcc0db82006-03-24 08:14:36 +0000571 ans = PyNumber_TrueDivide(num, den);
Raymond Hettinger866964c2002-12-14 19:51:34 +0000572 Py_DECREF(num);
573 Py_DECREF(den);
574 return ans;
Tim Peters78526162001-09-05 00:53:45 +0000575}
576
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000577PyDoc_STRVAR(math_log_doc,
Raymond Hettinger866964c2002-12-14 19:51:34 +0000578"log(x[, base]) -> the logarithm of x to the given base.\n\
579If the base not specified, returns the natural logarithm (base e) of x.");
Tim Peters78526162001-09-05 00:53:45 +0000580
581static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +0000582math_log10(PyObject *self, PyObject *arg)
Tim Peters78526162001-09-05 00:53:45 +0000583{
Thomas Wouters89f507f2006-12-13 04:49:30 +0000584 return loghelper(arg, log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +0000585}
586
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000587PyDoc_STRVAR(math_log10_doc,
588"log10(x) -> the base 10 logarithm of x.");
Tim Peters78526162001-09-05 00:53:45 +0000589
Christian Heimes53876d92008-04-19 00:31:39 +0000590static PyObject *
591math_fmod(PyObject *self, PyObject *args)
592{
593 PyObject *ox, *oy;
594 double r, x, y;
595 if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy))
596 return NULL;
597 x = PyFloat_AsDouble(ox);
598 y = PyFloat_AsDouble(oy);
599 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
600 return NULL;
601 /* fmod(x, +/-Inf) returns x for finite x. */
602 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
603 return PyFloat_FromDouble(x);
604 errno = 0;
605 PyFPE_START_PROTECT("in math_fmod", return 0);
606 r = fmod(x, y);
607 PyFPE_END_PROTECT(r);
608 if (Py_IS_NAN(r)) {
609 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
610 errno = EDOM;
611 else
612 errno = 0;
613 }
614 if (errno && is_error(r))
615 return NULL;
616 else
617 return PyFloat_FromDouble(r);
618}
619
620PyDoc_STRVAR(math_fmod_doc,
621"fmod(x,y)\n\nReturn fmod(x, y), according to platform C."
622" x % y may differ.");
623
624static PyObject *
625math_hypot(PyObject *self, PyObject *args)
626{
627 PyObject *ox, *oy;
628 double r, x, y;
629 if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy))
630 return NULL;
631 x = PyFloat_AsDouble(ox);
632 y = PyFloat_AsDouble(oy);
633 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
634 return NULL;
635 /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */
636 if (Py_IS_INFINITY(x))
637 return PyFloat_FromDouble(fabs(x));
638 if (Py_IS_INFINITY(y))
639 return PyFloat_FromDouble(fabs(y));
640 errno = 0;
641 PyFPE_START_PROTECT("in math_hypot", return 0);
642 r = hypot(x, y);
643 PyFPE_END_PROTECT(r);
644 if (Py_IS_NAN(r)) {
645 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
646 errno = EDOM;
647 else
648 errno = 0;
649 }
650 else if (Py_IS_INFINITY(r)) {
651 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
652 errno = ERANGE;
653 else
654 errno = 0;
655 }
656 if (errno && is_error(r))
657 return NULL;
658 else
659 return PyFloat_FromDouble(r);
660}
661
662PyDoc_STRVAR(math_hypot_doc,
663"hypot(x,y)\n\nReturn the Euclidean distance, sqrt(x*x + y*y).");
664
665/* pow can't use math_2, but needs its own wrapper: the problem is
666 that an infinite result can arise either as a result of overflow
667 (in which case OverflowError should be raised) or as a result of
668 e.g. 0.**-5. (for which ValueError needs to be raised.)
669*/
670
671static PyObject *
672math_pow(PyObject *self, PyObject *args)
673{
674 PyObject *ox, *oy;
675 double r, x, y;
Christian Heimesa342c012008-04-20 21:01:16 +0000676 int odd_y;
Christian Heimes53876d92008-04-19 00:31:39 +0000677
678 if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy))
679 return NULL;
680 x = PyFloat_AsDouble(ox);
681 y = PyFloat_AsDouble(oy);
682 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
683 return NULL;
Christian Heimesa342c012008-04-20 21:01:16 +0000684
685 /* deal directly with IEEE specials, to cope with problems on various
686 platforms whose semantics don't exactly match C99 */
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000687 r = 0.; /* silence compiler warning */
Christian Heimesa342c012008-04-20 21:01:16 +0000688 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
689 errno = 0;
690 if (Py_IS_NAN(x))
691 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
692 else if (Py_IS_NAN(y))
693 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
694 else if (Py_IS_INFINITY(x)) {
695 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
696 if (y > 0.)
697 r = odd_y ? x : fabs(x);
698 else if (y == 0.)
699 r = 1.;
700 else /* y < 0. */
701 r = odd_y ? copysign(0., x) : 0.;
702 }
703 else if (Py_IS_INFINITY(y)) {
704 if (fabs(x) == 1.0)
705 r = 1.;
706 else if (y > 0. && fabs(x) > 1.0)
707 r = y;
708 else if (y < 0. && fabs(x) < 1.0) {
709 r = -y; /* result is +inf */
710 if (x == 0.) /* 0**-inf: divide-by-zero */
711 errno = EDOM;
712 }
713 else
714 r = 0.;
715 }
Christian Heimes53876d92008-04-19 00:31:39 +0000716 }
Christian Heimesa342c012008-04-20 21:01:16 +0000717 else {
718 /* let libm handle finite**finite */
719 errno = 0;
720 PyFPE_START_PROTECT("in math_pow", return 0);
721 r = pow(x, y);
722 PyFPE_END_PROTECT(r);
723 /* a NaN result should arise only from (-ve)**(finite
724 non-integer); in this case we want to raise ValueError. */
725 if (!Py_IS_FINITE(r)) {
726 if (Py_IS_NAN(r)) {
727 errno = EDOM;
728 }
729 /*
730 an infinite result here arises either from:
731 (A) (+/-0.)**negative (-> divide-by-zero)
732 (B) overflow of x**y with x and y finite
733 */
734 else if (Py_IS_INFINITY(r)) {
735 if (x == 0.)
736 errno = EDOM;
737 else
738 errno = ERANGE;
739 }
740 }
Christian Heimes53876d92008-04-19 00:31:39 +0000741 }
742
743 if (errno && is_error(r))
744 return NULL;
745 else
746 return PyFloat_FromDouble(r);
747}
748
749PyDoc_STRVAR(math_pow_doc,
750"pow(x,y)\n\nReturn x**y (x to the power of y).");
751
Christian Heimes072c0f12008-01-03 23:01:04 +0000752static const double degToRad = Py_MATH_PI / 180.0;
753static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +0000754
755static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +0000756math_degrees(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +0000757{
Thomas Wouters89f507f2006-12-13 04:49:30 +0000758 double x = PyFloat_AsDouble(arg);
759 if (x == -1.0 && PyErr_Occurred())
Raymond Hettingerd6f22672002-05-13 03:56:10 +0000760 return NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +0000761 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +0000762}
763
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000764PyDoc_STRVAR(math_degrees_doc,
765"degrees(x) -> converts angle x from radians to degrees");
Raymond Hettingerd6f22672002-05-13 03:56:10 +0000766
767static PyObject *
Thomas Wouters89f507f2006-12-13 04:49:30 +0000768math_radians(PyObject *self, PyObject *arg)
Raymond Hettingerd6f22672002-05-13 03:56:10 +0000769{
Thomas Wouters89f507f2006-12-13 04:49:30 +0000770 double x = PyFloat_AsDouble(arg);
771 if (x == -1.0 && PyErr_Occurred())
Raymond Hettingerd6f22672002-05-13 03:56:10 +0000772 return NULL;
773 return PyFloat_FromDouble(x * degToRad);
774}
775
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000776PyDoc_STRVAR(math_radians_doc,
777"radians(x) -> converts angle x from degrees to radians");
Tim Peters78526162001-09-05 00:53:45 +0000778
Christian Heimes072c0f12008-01-03 23:01:04 +0000779static PyObject *
780math_isnan(PyObject *self, PyObject *arg)
781{
782 double x = PyFloat_AsDouble(arg);
783 if (x == -1.0 && PyErr_Occurred())
784 return NULL;
785 return PyBool_FromLong((long)Py_IS_NAN(x));
786}
787
788PyDoc_STRVAR(math_isnan_doc,
789"isnan(x) -> bool\n\
790Checks if float x is not a number (NaN)");
791
792static PyObject *
793math_isinf(PyObject *self, PyObject *arg)
794{
795 double x = PyFloat_AsDouble(arg);
796 if (x == -1.0 && PyErr_Occurred())
797 return NULL;
798 return PyBool_FromLong((long)Py_IS_INFINITY(x));
799}
800
801PyDoc_STRVAR(math_isinf_doc,
802"isinf(x) -> bool\n\
803Checks if float x is infinite (positive or negative)");
804
Barry Warsaw8b43b191996-12-09 22:32:36 +0000805static PyMethodDef math_methods[] = {
Thomas Wouters89f507f2006-12-13 04:49:30 +0000806 {"acos", math_acos, METH_O, math_acos_doc},
Christian Heimes53876d92008-04-19 00:31:39 +0000807 {"acosh", math_acosh, METH_O, math_acosh_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +0000808 {"asin", math_asin, METH_O, math_asin_doc},
Christian Heimes53876d92008-04-19 00:31:39 +0000809 {"asinh", math_asinh, METH_O, math_asinh_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +0000810 {"atan", math_atan, METH_O, math_atan_doc},
Fred Drake40c48682000-07-03 18:11:56 +0000811 {"atan2", math_atan2, METH_VARARGS, math_atan2_doc},
Christian Heimes53876d92008-04-19 00:31:39 +0000812 {"atanh", math_atanh, METH_O, math_atanh_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +0000813 {"ceil", math_ceil, METH_O, math_ceil_doc},
Christian Heimes072c0f12008-01-03 23:01:04 +0000814 {"copysign", math_copysign, METH_VARARGS, math_copysign_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +0000815 {"cos", math_cos, METH_O, math_cos_doc},
816 {"cosh", math_cosh, METH_O, math_cosh_doc},
817 {"degrees", math_degrees, METH_O, math_degrees_doc},
818 {"exp", math_exp, METH_O, math_exp_doc},
819 {"fabs", math_fabs, METH_O, math_fabs_doc},
820 {"floor", math_floor, METH_O, math_floor_doc},
Fred Drake40c48682000-07-03 18:11:56 +0000821 {"fmod", math_fmod, METH_VARARGS, math_fmod_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +0000822 {"frexp", math_frexp, METH_O, math_frexp_doc},
Fred Drake40c48682000-07-03 18:11:56 +0000823 {"hypot", math_hypot, METH_VARARGS, math_hypot_doc},
Christian Heimes072c0f12008-01-03 23:01:04 +0000824 {"isinf", math_isinf, METH_O, math_isinf_doc},
825 {"isnan", math_isnan, METH_O, math_isnan_doc},
Fred Drake40c48682000-07-03 18:11:56 +0000826 {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc},
827 {"log", math_log, METH_VARARGS, math_log_doc},
Christian Heimes53876d92008-04-19 00:31:39 +0000828 {"log1p", math_log1p, METH_O, math_log1p_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +0000829 {"log10", math_log10, METH_O, math_log10_doc},
830 {"modf", math_modf, METH_O, math_modf_doc},
Fred Drake40c48682000-07-03 18:11:56 +0000831 {"pow", math_pow, METH_VARARGS, math_pow_doc},
Thomas Wouters89f507f2006-12-13 04:49:30 +0000832 {"radians", math_radians, METH_O, math_radians_doc},
833 {"sin", math_sin, METH_O, math_sin_doc},
834 {"sinh", math_sinh, METH_O, math_sinh_doc},
835 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
836 {"tan", math_tan, METH_O, math_tan_doc},
837 {"tanh", math_tanh, METH_O, math_tanh_doc},
Christian Heimes400adb02008-02-01 08:12:03 +0000838 {"trunc", math_trunc, METH_O, math_trunc_doc},
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000839 {NULL, NULL} /* sentinel */
840};
841
Guido van Rossumc6e22901998-12-04 19:26:43 +0000842
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000843PyDoc_STRVAR(module_doc,
Tim Peters63c94532001-09-04 23:17:42 +0000844"This module is always available. It provides access to the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000845"mathematical functions defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +0000846
Mark Hammondfe51c6d2002-08-02 02:27:13 +0000847PyMODINIT_FUNC
Thomas Woutersf3f33dc2000-07-21 06:00:07 +0000848initmath(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000849{
Christian Heimes53876d92008-04-19 00:31:39 +0000850 PyObject *m;
Tim Petersfe71f812001-08-07 22:10:00 +0000851
Guido van Rossumc6e22901998-12-04 19:26:43 +0000852 m = Py_InitModule3("math", math_methods, module_doc);
Neal Norwitz1ac754f2006-01-19 06:09:39 +0000853 if (m == NULL)
854 goto finally;
Barry Warsawfc93f751996-12-17 00:47:03 +0000855
Christian Heimes53876d92008-04-19 00:31:39 +0000856 PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
857 PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
Barry Warsawfc93f751996-12-17 00:47:03 +0000858
Christian Heimes53876d92008-04-19 00:31:39 +0000859 finally:
Barry Warsaw9bfd2bf2000-09-01 09:01:32 +0000860 return;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000861}