Added section about adding contextual information to log output.
[python.git] / Modules / mathmodule.c
blob5e52e785416792353730ca69e8f358a6a6e40a2c
1 /* Math module -- standard C math library functions, pi and e */
3 #include "Python.h"
4 #include "longintrepr.h" /* just for SHIFT */
6 #ifndef _MSC_VER
7 #ifndef __STDC__
8 extern double fmod (double, double);
9 extern double frexp (double, int *);
10 extern double ldexp (double, int);
11 extern double modf (double, double *);
12 #endif /* __STDC__ */
13 #endif /* _MSC_VER */
15 /* Call is_error when errno != 0, and where x is the result libm
16 * returned. is_error will usually set up an exception and return
17 * true (1), but may return false (0) without setting up an exception.
19 static int
20 is_error(double x)
22 int result = 1; /* presumption of guilt */
23 assert(errno); /* non-zero errno is a precondition for calling */
24 if (errno == EDOM)
25 PyErr_SetString(PyExc_ValueError, "math domain error");
27 else if (errno == ERANGE) {
28 /* ANSI C generally requires libm functions to set ERANGE
29 * on overflow, but also generally *allows* them to set
30 * ERANGE on underflow too. There's no consistency about
31 * the latter across platforms.
32 * Alas, C99 never requires that errno be set.
33 * Here we suppress the underflow errors (libm functions
34 * should return a zero on underflow, and +- HUGE_VAL on
35 * overflow, so testing the result for zero suffices to
36 * distinguish the cases).
38 if (x)
39 PyErr_SetString(PyExc_OverflowError,
40 "math range error");
41 else
42 result = 0;
44 else
45 /* Unexpected math error */
46 PyErr_SetFromErrno(PyExc_ValueError);
47 return result;
50 static PyObject *
51 math_1(PyObject *arg, double (*func) (double))
53 double x = PyFloat_AsDouble(arg);
54 if (x == -1.0 && PyErr_Occurred())
55 return NULL;
56 errno = 0;
57 PyFPE_START_PROTECT("in math_1", return 0)
58 x = (*func)(x);
59 PyFPE_END_PROTECT(x)
60 Py_SET_ERRNO_ON_MATH_ERROR(x);
61 if (errno && is_error(x))
62 return NULL;
63 else
64 return PyFloat_FromDouble(x);
67 static PyObject *
68 math_2(PyObject *args, double (*func) (double, double), char *funcname)
70 PyObject *ox, *oy;
71 double x, y;
72 if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy))
73 return NULL;
74 x = PyFloat_AsDouble(ox);
75 y = PyFloat_AsDouble(oy);
76 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
77 return NULL;
78 errno = 0;
79 PyFPE_START_PROTECT("in math_2", return 0)
80 x = (*func)(x, y);
81 PyFPE_END_PROTECT(x)
82 Py_SET_ERRNO_ON_MATH_ERROR(x);
83 if (errno && is_error(x))
84 return NULL;
85 else
86 return PyFloat_FromDouble(x);
89 #define FUNC1(funcname, func, docstring) \
90 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
91 return math_1(args, func); \
93 PyDoc_STRVAR(math_##funcname##_doc, docstring);
95 #define FUNC2(funcname, func, docstring) \
96 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
97 return math_2(args, func, #funcname); \
99 PyDoc_STRVAR(math_##funcname##_doc, docstring);
101 FUNC1(acos, acos,
102 "acos(x)\n\nReturn the arc cosine (measured in radians) of x.")
103 FUNC1(asin, asin,
104 "asin(x)\n\nReturn the arc sine (measured in radians) of x.")
105 FUNC1(atan, atan,
106 "atan(x)\n\nReturn the arc tangent (measured in radians) of x.")
107 FUNC2(atan2, atan2,
108 "atan2(y, x)\n\nReturn the arc tangent (measured in radians) of y/x.\n"
109 "Unlike atan(y/x), the signs of both x and y are considered.")
110 FUNC1(ceil, ceil,
111 "ceil(x)\n\nReturn the ceiling of x as a float.\n"
112 "This is the smallest integral value >= x.")
113 FUNC1(cos, cos,
114 "cos(x)\n\nReturn the cosine of x (measured in radians).")
115 FUNC1(cosh, cosh,
116 "cosh(x)\n\nReturn the hyperbolic cosine of x.")
118 #ifdef MS_WINDOWS
119 # define copysign _copysign
120 # define HAVE_COPYSIGN 1
121 #endif
122 #ifdef HAVE_COPYSIGN
123 FUNC2(copysign, copysign,
124 "copysign(x,y)\n\nReturn x with the sign of y.");
125 #endif
127 FUNC1(exp, exp,
128 "exp(x)\n\nReturn e raised to the power of x.")
129 FUNC1(fabs, fabs,
130 "fabs(x)\n\nReturn the absolute value of the float x.")
131 FUNC1(floor, floor,
132 "floor(x)\n\nReturn the floor of x as a float.\n"
133 "This is the largest integral value <= x.")
134 FUNC2(fmod, fmod,
135 "fmod(x,y)\n\nReturn fmod(x, y), according to platform C."
136 " x % y may differ.")
137 FUNC2(hypot, hypot,
138 "hypot(x,y)\n\nReturn the Euclidean distance, sqrt(x*x + y*y).")
139 FUNC2(pow, pow,
140 "pow(x,y)\n\nReturn x**y (x to the power of y).")
141 FUNC1(sin, sin,
142 "sin(x)\n\nReturn the sine of x (measured in radians).")
143 FUNC1(sinh, sinh,
144 "sinh(x)\n\nReturn the hyperbolic sine of x.")
145 FUNC1(sqrt, sqrt,
146 "sqrt(x)\n\nReturn the square root of x.")
147 FUNC1(tan, tan,
148 "tan(x)\n\nReturn the tangent of x (measured in radians).")
149 FUNC1(tanh, tanh,
150 "tanh(x)\n\nReturn the hyperbolic tangent of x.")
152 static PyObject *
153 math_frexp(PyObject *self, PyObject *arg)
155 int i;
156 double x = PyFloat_AsDouble(arg);
157 if (x == -1.0 && PyErr_Occurred())
158 return NULL;
159 errno = 0;
160 x = frexp(x, &i);
161 Py_SET_ERRNO_ON_MATH_ERROR(x);
162 if (errno && is_error(x))
163 return NULL;
164 else
165 return Py_BuildValue("(di)", x, i);
168 PyDoc_STRVAR(math_frexp_doc,
169 "frexp(x)\n"
170 "\n"
171 "Return the mantissa and exponent of x, as pair (m, e).\n"
172 "m is a float and e is an int, such that x = m * 2.**e.\n"
173 "If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.");
175 static PyObject *
176 math_ldexp(PyObject *self, PyObject *args)
178 double x;
179 int exp;
180 if (! PyArg_ParseTuple(args, "di:ldexp", &x, &exp))
181 return NULL;
182 errno = 0;
183 PyFPE_START_PROTECT("ldexp", return 0)
184 x = ldexp(x, exp);
185 PyFPE_END_PROTECT(x)
186 Py_SET_ERRNO_ON_MATH_ERROR(x);
187 if (errno && is_error(x))
188 return NULL;
189 else
190 return PyFloat_FromDouble(x);
193 PyDoc_STRVAR(math_ldexp_doc,
194 "ldexp(x, i) -> x * (2**i)");
196 static PyObject *
197 math_modf(PyObject *self, PyObject *arg)
199 double y, x = PyFloat_AsDouble(arg);
200 if (x == -1.0 && PyErr_Occurred())
201 return NULL;
202 errno = 0;
203 x = modf(x, &y);
204 Py_SET_ERRNO_ON_MATH_ERROR(x);
205 if (errno && is_error(x))
206 return NULL;
207 else
208 return Py_BuildValue("(dd)", x, y);
211 PyDoc_STRVAR(math_modf_doc,
212 "modf(x)\n"
213 "\n"
214 "Return the fractional and integer parts of x. Both results carry the sign\n"
215 "of x. The integer part is returned as a real.");
217 /* A decent logarithm is easy to compute even for huge longs, but libm can't
218 do that by itself -- loghelper can. func is log or log10, and name is
219 "log" or "log10". Note that overflow isn't possible: a long can contain
220 no more than INT_MAX * SHIFT bits, so has value certainly less than
221 2**(2**64 * 2**16) == 2**2**80, and log2 of that is 2**80, which is
222 small enough to fit in an IEEE single. log and log10 are even smaller.
225 static PyObject*
226 loghelper(PyObject* arg, double (*func)(double), char *funcname)
228 /* If it is long, do it ourselves. */
229 if (PyLong_Check(arg)) {
230 double x;
231 int e;
232 x = _PyLong_AsScaledDouble(arg, &e);
233 if (x <= 0.0) {
234 PyErr_SetString(PyExc_ValueError,
235 "math domain error");
236 return NULL;
238 /* Value is ~= x * 2**(e*SHIFT), so the log ~=
239 log(x) + log(2) * e * SHIFT.
240 CAUTION: e*SHIFT may overflow using int arithmetic,
241 so force use of double. */
242 x = func(x) + (e * (double)SHIFT) * func(2.0);
243 return PyFloat_FromDouble(x);
246 /* Else let libm handle it by itself. */
247 return math_1(arg, func);
250 static PyObject *
251 math_log(PyObject *self, PyObject *args)
253 PyObject *arg;
254 PyObject *base = NULL;
255 PyObject *num, *den;
256 PyObject *ans;
258 if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base))
259 return NULL;
261 num = loghelper(arg, log, "log");
262 if (num == NULL || base == NULL)
263 return num;
265 den = loghelper(base, log, "log");
266 if (den == NULL) {
267 Py_DECREF(num);
268 return NULL;
271 ans = PyNumber_Divide(num, den);
272 Py_DECREF(num);
273 Py_DECREF(den);
274 return ans;
277 PyDoc_STRVAR(math_log_doc,
278 "log(x[, base]) -> the logarithm of x to the given base.\n\
279 If the base not specified, returns the natural logarithm (base e) of x.");
281 static PyObject *
282 math_log10(PyObject *self, PyObject *arg)
284 return loghelper(arg, log10, "log10");
287 PyDoc_STRVAR(math_log10_doc,
288 "log10(x) -> the base 10 logarithm of x.");
290 static const double degToRad = Py_MATH_PI / 180.0;
291 static const double radToDeg = 180.0 / Py_MATH_PI;
293 static PyObject *
294 math_degrees(PyObject *self, PyObject *arg)
296 double x = PyFloat_AsDouble(arg);
297 if (x == -1.0 && PyErr_Occurred())
298 return NULL;
299 return PyFloat_FromDouble(x * radToDeg);
302 PyDoc_STRVAR(math_degrees_doc,
303 "degrees(x) -> converts angle x from radians to degrees");
305 static PyObject *
306 math_radians(PyObject *self, PyObject *arg)
308 double x = PyFloat_AsDouble(arg);
309 if (x == -1.0 && PyErr_Occurred())
310 return NULL;
311 return PyFloat_FromDouble(x * degToRad);
314 PyDoc_STRVAR(math_radians_doc,
315 "radians(x) -> converts angle x from degrees to radians");
317 static PyObject *
318 math_isnan(PyObject *self, PyObject *arg)
320 double x = PyFloat_AsDouble(arg);
321 if (x == -1.0 && PyErr_Occurred())
322 return NULL;
323 return PyBool_FromLong((long)Py_IS_NAN(x));
326 PyDoc_STRVAR(math_isnan_doc,
327 "isnan(x) -> bool\n\
328 Checks if float x is not a number (NaN)");
330 static PyObject *
331 math_isinf(PyObject *self, PyObject *arg)
333 double x = PyFloat_AsDouble(arg);
334 if (x == -1.0 && PyErr_Occurred())
335 return NULL;
336 return PyBool_FromLong((long)Py_IS_INFINITY(x));
339 PyDoc_STRVAR(math_isinf_doc,
340 "isinf(x) -> bool\n\
341 Checks if float x is infinite (positive or negative)");
344 static PyMethodDef math_methods[] = {
345 {"acos", math_acos, METH_O, math_acos_doc},
346 {"asin", math_asin, METH_O, math_asin_doc},
347 {"atan", math_atan, METH_O, math_atan_doc},
348 {"atan2", math_atan2, METH_VARARGS, math_atan2_doc},
349 {"ceil", math_ceil, METH_O, math_ceil_doc},
350 #ifdef HAVE_COPYSIGN
351 {"copysign", math_copysign, METH_VARARGS, math_copysign_doc},
352 #endif
353 {"cos", math_cos, METH_O, math_cos_doc},
354 {"cosh", math_cosh, METH_O, math_cosh_doc},
355 {"degrees", math_degrees, METH_O, math_degrees_doc},
356 {"exp", math_exp, METH_O, math_exp_doc},
357 {"fabs", math_fabs, METH_O, math_fabs_doc},
358 {"floor", math_floor, METH_O, math_floor_doc},
359 {"fmod", math_fmod, METH_VARARGS, math_fmod_doc},
360 {"frexp", math_frexp, METH_O, math_frexp_doc},
361 {"hypot", math_hypot, METH_VARARGS, math_hypot_doc},
362 {"isinf", math_isinf, METH_O, math_isinf_doc},
363 {"isnan", math_isnan, METH_O, math_isnan_doc},
364 {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc},
365 {"log", math_log, METH_VARARGS, math_log_doc},
366 {"log10", math_log10, METH_O, math_log10_doc},
367 {"modf", math_modf, METH_O, math_modf_doc},
368 {"pow", math_pow, METH_VARARGS, math_pow_doc},
369 {"radians", math_radians, METH_O, math_radians_doc},
370 {"sin", math_sin, METH_O, math_sin_doc},
371 {"sinh", math_sinh, METH_O, math_sinh_doc},
372 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
373 {"tan", math_tan, METH_O, math_tan_doc},
374 {"tanh", math_tanh, METH_O, math_tanh_doc},
375 {NULL, NULL} /* sentinel */
379 PyDoc_STRVAR(module_doc,
380 "This module is always available. It provides access to the\n"
381 "mathematical functions defined by the C standard.");
383 PyMODINIT_FUNC
384 initmath(void)
386 PyObject *m, *d, *v;
388 m = Py_InitModule3("math", math_methods, module_doc);
389 if (m == NULL)
390 goto finally;
391 d = PyModule_GetDict(m);
392 if (d == NULL)
393 goto finally;
395 if (!(v = PyFloat_FromDouble(Py_MATH_PI)))
396 goto finally;
397 if (PyDict_SetItemString(d, "pi", v) < 0)
398 goto finally;
399 Py_DECREF(v);
401 if (!(v = PyFloat_FromDouble(Py_MATH_E)))
402 goto finally;
403 if (PyDict_SetItemString(d, "e", v) < 0)
404 goto finally;
405 Py_DECREF(v);
407 finally:
408 return;