Issue #3366: Add expm1 function to math module. Thanks Eric Smith for
[python.git] / Modules / _math.c
blob9d330aa0d5950b645c79aa7427d242af9785621c
1 /* Definitions of some C99 math library functions, for those platforms
2 that don't implement these functions already. */
4 #include <float.h>
5 #include <math.h>
7 /* Mathematically, expm1(x) = exp(x) - 1. The expm1 function is designed
8 to avoid the significant loss of precision that arises from direct
9 evaluation of the expression exp(x) - 1, for x near 0. */
11 double
12 _Py_expm1(double x)
14 /* For abs(x) >= log(2), it's safe to evaluate exp(x) - 1 directly; this
15 also works fine for infinities and nans.
17 For smaller x, we can use a method due to Kahan that achieves close to
18 full accuracy.
21 if (fabs(x) < 0.7) {
22 double u;
23 u = exp(x);
24 if (u == 1.0)
25 return x;
26 else
27 return (u - 1.0) * x / log(u);
29 else
30 return exp(x) - 1.0;