blob: d5a8ca1ebefdc1a0fa824aa435eb183bdc7da7e8 [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"
Mark Dickinson664b5112009-12-16 20:23:42 +000056#include "_math.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000057
Serhiy Storchakac9ea9332017-01-19 18:13:09 +020058#include "clinic/mathmodule.c.h"
59
60/*[clinic input]
61module math
62[clinic start generated code]*/
63/*[clinic end generated code: output=da39a3ee5e6b4b0d input=76bc7002685dd942]*/
64
65
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000066/*
67 sin(pi*x), giving accurate results for all finite x (especially x
68 integral or close to an integer). This is here for use in the
69 reflection formula for the gamma function. It conforms to IEEE
70 754-2008 for finite arguments, but not for infinities or nans.
71*/
Tim Petersa40c7932001-09-05 22:36:56 +000072
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000073static const double pi = 3.141592653589793238462643383279502884197;
Mark Dickinson45f992a2009-12-19 11:20:49 +000074static const double sqrtpi = 1.772453850905516027298167483341145182798;
Mark Dickinson9c91eb82010-07-07 16:17:31 +000075static const double logpi = 1.144729885849400174143427351353058711647;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000076
77static double
78sinpi(double x)
79{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000080 double y, r;
81 int n;
82 /* this function should only ever be called for finite arguments */
83 assert(Py_IS_FINITE(x));
84 y = fmod(fabs(x), 2.0);
85 n = (int)round(2.0*y);
86 assert(0 <= n && n <= 4);
87 switch (n) {
88 case 0:
89 r = sin(pi*y);
90 break;
91 case 1:
92 r = cos(pi*(y-0.5));
93 break;
94 case 2:
95 /* N.B. -sin(pi*(y-1.0)) is *not* equivalent: it would give
96 -0.0 instead of 0.0 when y == 1.0. */
97 r = sin(pi*(1.0-y));
98 break;
99 case 3:
100 r = -cos(pi*(y-1.5));
101 break;
102 case 4:
103 r = sin(pi*(y-2.0));
104 break;
105 default:
106 assert(0); /* should never get here */
107 r = -1.23e200; /* silence gcc warning */
108 }
109 return copysign(1.0, x)*r;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000110}
111
112/* Implementation of the real gamma function. In extensive but non-exhaustive
113 random tests, this function proved accurate to within <= 10 ulps across the
114 entire float domain. Note that accuracy may depend on the quality of the
115 system math functions, the pow function in particular. Special cases
116 follow C99 annex F. The parameters and method are tailored to platforms
117 whose double format is the IEEE 754 binary64 format.
118
119 Method: for x > 0.0 we use the Lanczos approximation with parameters N=13
120 and g=6.024680040776729583740234375; these parameters are amongst those
121 used by the Boost library. Following Boost (again), we re-express the
122 Lanczos sum as a rational function, and compute it that way. The
123 coefficients below were computed independently using MPFR, and have been
124 double-checked against the coefficients in the Boost source code.
125
126 For x < 0.0 we use the reflection formula.
127
128 There's one minor tweak that deserves explanation: Lanczos' formula for
129 Gamma(x) involves computing pow(x+g-0.5, x-0.5) / exp(x+g-0.5). For many x
130 values, x+g-0.5 can be represented exactly. However, in cases where it
131 can't be represented exactly the small error in x+g-0.5 can be magnified
132 significantly by the pow and exp calls, especially for large x. A cheap
133 correction is to multiply by (1 + e*g/(x+g-0.5)), where e is the error
134 involved in the computation of x+g-0.5 (that is, e = computed value of
135 x+g-0.5 - exact value of x+g-0.5). Here's the proof:
136
137 Correction factor
138 -----------------
139 Write x+g-0.5 = y-e, where y is exactly representable as an IEEE 754
140 double, and e is tiny. Then:
141
142 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) = pow(y-e, x-0.5)/exp(y-e)
143 = pow(y, x-0.5)/exp(y) * C,
144
145 where the correction_factor C is given by
146
147 C = pow(1-e/y, x-0.5) * exp(e)
148
149 Since e is tiny, pow(1-e/y, x-0.5) ~ 1-(x-0.5)*e/y, and exp(x) ~ 1+e, so:
150
151 C ~ (1-(x-0.5)*e/y) * (1+e) ~ 1 + e*(y-(x-0.5))/y
152
153 But y-(x-0.5) = g+e, and g+e ~ g. So we get C ~ 1 + e*g/y, and
154
155 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) ~ pow(y, x-0.5)/exp(y) * (1 + e*g/y),
156
157 Note that for accuracy, when computing r*C it's better to do
158
159 r + e*g/y*r;
160
161 than
162
163 r * (1 + e*g/y);
164
165 since the addition in the latter throws away most of the bits of
166 information in e*g/y.
167*/
168
169#define LANCZOS_N 13
170static const double lanczos_g = 6.024680040776729583740234375;
171static const double lanczos_g_minus_half = 5.524680040776729583740234375;
172static const double lanczos_num_coeffs[LANCZOS_N] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 23531376880.410759688572007674451636754734846804940,
174 42919803642.649098768957899047001988850926355848959,
175 35711959237.355668049440185451547166705960488635843,
176 17921034426.037209699919755754458931112671403265390,
177 6039542586.3520280050642916443072979210699388420708,
178 1439720407.3117216736632230727949123939715485786772,
179 248874557.86205415651146038641322942321632125127801,
180 31426415.585400194380614231628318205362874684987640,
181 2876370.6289353724412254090516208496135991145378768,
182 186056.26539522349504029498971604569928220784236328,
183 8071.6720023658162106380029022722506138218516325024,
184 210.82427775157934587250973392071336271166969580291,
185 2.5066282746310002701649081771338373386264310793408
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000186};
187
188/* denominator is x*(x+1)*...*(x+LANCZOS_N-2) */
189static const double lanczos_den_coeffs[LANCZOS_N] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 0.0, 39916800.0, 120543840.0, 150917976.0, 105258076.0, 45995730.0,
191 13339535.0, 2637558.0, 357423.0, 32670.0, 1925.0, 66.0, 1.0};
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000192
193/* gamma values for small positive integers, 1 though NGAMMA_INTEGRAL */
194#define NGAMMA_INTEGRAL 23
195static const double gamma_integral[NGAMMA_INTEGRAL] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0,
197 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0,
198 1307674368000.0, 20922789888000.0, 355687428096000.0,
199 6402373705728000.0, 121645100408832000.0, 2432902008176640000.0,
200 51090942171709440000.0, 1124000727777607680000.0,
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000201};
202
203/* Lanczos' sum L_g(x), for positive x */
204
205static double
206lanczos_sum(double x)
207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 double num = 0.0, den = 0.0;
209 int i;
210 assert(x > 0.0);
211 /* evaluate the rational function lanczos_sum(x). For large
212 x, the obvious algorithm risks overflow, so we instead
213 rescale the denominator and numerator of the rational
214 function by x**(1-LANCZOS_N) and treat this as a
215 rational function in 1/x. This also reduces the error for
216 larger x values. The choice of cutoff point (5.0 below) is
217 somewhat arbitrary; in tests, smaller cutoff values than
218 this resulted in lower accuracy. */
219 if (x < 5.0) {
220 for (i = LANCZOS_N; --i >= 0; ) {
221 num = num * x + lanczos_num_coeffs[i];
222 den = den * x + lanczos_den_coeffs[i];
223 }
224 }
225 else {
226 for (i = 0; i < LANCZOS_N; i++) {
227 num = num / x + lanczos_num_coeffs[i];
228 den = den / x + lanczos_den_coeffs[i];
229 }
230 }
231 return num/den;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000232}
233
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +0000234/* Constant for +infinity, generated in the same way as float('inf'). */
235
236static double
237m_inf(void)
238{
239#ifndef PY_NO_SHORT_FLOAT_REPR
240 return _Py_dg_infinity(0);
241#else
242 return Py_HUGE_VAL;
243#endif
244}
245
246/* Constant nan value, generated in the same way as float('nan'). */
247/* We don't currently assume that Py_NAN is defined everywhere. */
248
249#if !defined(PY_NO_SHORT_FLOAT_REPR) || defined(Py_NAN)
250
251static double
252m_nan(void)
253{
254#ifndef PY_NO_SHORT_FLOAT_REPR
255 return _Py_dg_stdnan(0);
256#else
257 return Py_NAN;
258#endif
259}
260
261#endif
262
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000263static double
264m_tgamma(double x)
265{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 double absx, r, y, z, sqrtpow;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 /* special cases */
269 if (!Py_IS_FINITE(x)) {
270 if (Py_IS_NAN(x) || x > 0.0)
271 return x; /* tgamma(nan) = nan, tgamma(inf) = inf */
272 else {
273 errno = EDOM;
274 return Py_NAN; /* tgamma(-inf) = nan, invalid */
275 }
276 }
277 if (x == 0.0) {
278 errno = EDOM;
Mark Dickinson50203a62011-09-25 15:26:43 +0100279 /* tgamma(+-0.0) = +-inf, divide-by-zero */
280 return copysign(Py_HUGE_VAL, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 /* integer arguments */
284 if (x == floor(x)) {
285 if (x < 0.0) {
286 errno = EDOM; /* tgamma(n) = nan, invalid for */
287 return Py_NAN; /* negative integers n */
288 }
289 if (x <= NGAMMA_INTEGRAL)
290 return gamma_integral[(int)x - 1];
291 }
292 absx = fabs(x);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 /* tiny arguments: tgamma(x) ~ 1/x for x near 0 */
295 if (absx < 1e-20) {
296 r = 1.0/x;
297 if (Py_IS_INFINITY(r))
298 errno = ERANGE;
299 return r;
300 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 /* large arguments: assuming IEEE 754 doubles, tgamma(x) overflows for
303 x > 200, and underflows to +-0.0 for x < -200, not a negative
304 integer. */
305 if (absx > 200.0) {
306 if (x < 0.0) {
307 return 0.0/sinpi(x);
308 }
309 else {
310 errno = ERANGE;
311 return Py_HUGE_VAL;
312 }
313 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 y = absx + lanczos_g_minus_half;
316 /* compute error in sum */
317 if (absx > lanczos_g_minus_half) {
318 /* note: the correction can be foiled by an optimizing
319 compiler that (incorrectly) thinks that an expression like
320 a + b - a - b can be optimized to 0.0. This shouldn't
321 happen in a standards-conforming compiler. */
322 double q = y - absx;
323 z = q - lanczos_g_minus_half;
324 }
325 else {
326 double q = y - lanczos_g_minus_half;
327 z = q - absx;
328 }
329 z = z * lanczos_g / y;
330 if (x < 0.0) {
331 r = -pi / sinpi(absx) / absx * exp(y) / lanczos_sum(absx);
332 r -= z * r;
333 if (absx < 140.0) {
334 r /= pow(y, absx - 0.5);
335 }
336 else {
337 sqrtpow = pow(y, absx / 2.0 - 0.25);
338 r /= sqrtpow;
339 r /= sqrtpow;
340 }
341 }
342 else {
343 r = lanczos_sum(absx) / exp(y);
344 r += z * r;
345 if (absx < 140.0) {
346 r *= pow(y, absx - 0.5);
347 }
348 else {
349 sqrtpow = pow(y, absx / 2.0 - 0.25);
350 r *= sqrtpow;
351 r *= sqrtpow;
352 }
353 }
354 if (Py_IS_INFINITY(r))
355 errno = ERANGE;
356 return r;
Guido van Rossum8832b621991-12-16 15:44:24 +0000357}
358
Christian Heimes53876d92008-04-19 00:31:39 +0000359/*
Mark Dickinson05d2e082009-12-11 20:17:17 +0000360 lgamma: natural log of the absolute value of the Gamma function.
361 For large arguments, Lanczos' formula works extremely well here.
362*/
363
364static double
365m_lgamma(double x)
366{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200367 double r;
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200368 double absx;
Mark Dickinson05d2e082009-12-11 20:17:17 +0000369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 /* special cases */
371 if (!Py_IS_FINITE(x)) {
372 if (Py_IS_NAN(x))
373 return x; /* lgamma(nan) = nan */
374 else
375 return Py_HUGE_VAL; /* lgamma(+-inf) = +inf */
376 }
Mark Dickinson05d2e082009-12-11 20:17:17 +0000377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 /* integer arguments */
379 if (x == floor(x) && x <= 2.0) {
380 if (x <= 0.0) {
381 errno = EDOM; /* lgamma(n) = inf, divide-by-zero for */
382 return Py_HUGE_VAL; /* integers n <= 0 */
383 }
384 else {
385 return 0.0; /* lgamma(1) = lgamma(2) = 0.0 */
386 }
387 }
Mark Dickinson05d2e082009-12-11 20:17:17 +0000388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 absx = fabs(x);
390 /* tiny arguments: lgamma(x) ~ -log(fabs(x)) for small x */
391 if (absx < 1e-20)
392 return -log(absx);
Mark Dickinson05d2e082009-12-11 20:17:17 +0000393
Mark Dickinson9c91eb82010-07-07 16:17:31 +0000394 /* Lanczos' formula. We could save a fraction of a ulp in accuracy by
395 having a second set of numerator coefficients for lanczos_sum that
396 absorbed the exp(-lanczos_g) term, and throwing out the lanczos_g
397 subtraction below; it's probably not worth it. */
398 r = log(lanczos_sum(absx)) - lanczos_g;
399 r += (absx - 0.5) * (log(absx + lanczos_g - 0.5) - 1);
400 if (x < 0.0)
401 /* Use reflection formula to get value for negative x. */
402 r = logpi - log(fabs(sinpi(absx))) - log(absx) - r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 if (Py_IS_INFINITY(r))
404 errno = ERANGE;
405 return r;
Mark Dickinson05d2e082009-12-11 20:17:17 +0000406}
407
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200408#if !defined(HAVE_ERF) || !defined(HAVE_ERFC)
409
Mark Dickinson45f992a2009-12-19 11:20:49 +0000410/*
411 Implementations of the error function erf(x) and the complementary error
412 function erfc(x).
413
Brett Cannon45adb312016-01-15 09:38:24 -0800414 Method: we use a series approximation for erf for small x, and a continued
415 fraction approximation for erfc(x) for larger x;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000416 combined with the relations erf(-x) = -erf(x) and erfc(x) = 1.0 - erf(x),
417 this gives us erf(x) and erfc(x) for all x.
418
419 The series expansion used is:
420
421 erf(x) = x*exp(-x*x)/sqrt(pi) * [
422 2/1 + 4/3 x**2 + 8/15 x**4 + 16/105 x**6 + ...]
423
424 The coefficient of x**(2k-2) here is 4**k*factorial(k)/factorial(2*k).
425 This series converges well for smallish x, but slowly for larger x.
426
427 The continued fraction expansion used is:
428
429 erfc(x) = x*exp(-x*x)/sqrt(pi) * [1/(0.5 + x**2 -) 0.5/(2.5 + x**2 - )
430 3.0/(4.5 + x**2 - ) 7.5/(6.5 + x**2 - ) ...]
431
432 after the first term, the general term has the form:
433
434 k*(k-0.5)/(2*k+0.5 + x**2 - ...).
435
436 This expansion converges fast for larger x, but convergence becomes
437 infinitely slow as x approaches 0.0. The (somewhat naive) continued
438 fraction evaluation algorithm used below also risks overflow for large x;
439 but for large x, erfc(x) == 0.0 to within machine precision. (For
440 example, erfc(30.0) is approximately 2.56e-393).
441
442 Parameters: use series expansion for abs(x) < ERF_SERIES_CUTOFF and
443 continued fraction expansion for ERF_SERIES_CUTOFF <= abs(x) <
444 ERFC_CONTFRAC_CUTOFF. ERFC_SERIES_TERMS and ERFC_CONTFRAC_TERMS are the
445 numbers of terms to use for the relevant expansions. */
446
447#define ERF_SERIES_CUTOFF 1.5
448#define ERF_SERIES_TERMS 25
449#define ERFC_CONTFRAC_CUTOFF 30.0
450#define ERFC_CONTFRAC_TERMS 50
451
452/*
453 Error function, via power series.
454
455 Given a finite float x, return an approximation to erf(x).
456 Converges reasonably fast for small x.
457*/
458
459static double
460m_erf_series(double x)
461{
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000462 double x2, acc, fk, result;
463 int i, saved_errno;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 x2 = x * x;
466 acc = 0.0;
467 fk = (double)ERF_SERIES_TERMS + 0.5;
468 for (i = 0; i < ERF_SERIES_TERMS; i++) {
469 acc = 2.0 + x2 * acc / fk;
470 fk -= 1.0;
471 }
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000472 /* Make sure the exp call doesn't affect errno;
473 see m_erfc_contfrac for more. */
474 saved_errno = errno;
475 result = acc * x * exp(-x2) / sqrtpi;
476 errno = saved_errno;
477 return result;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000478}
479
480/*
481 Complementary error function, via continued fraction expansion.
482
483 Given a positive float x, return an approximation to erfc(x). Converges
484 reasonably fast for x large (say, x > 2.0), and should be safe from
485 overflow if x and nterms are not too large. On an IEEE 754 machine, with x
486 <= 30.0, we're safe up to nterms = 100. For x >= 30.0, erfc(x) is smaller
487 than the smallest representable nonzero float. */
488
489static double
490m_erfc_contfrac(double x)
491{
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000492 double x2, a, da, p, p_last, q, q_last, b, result;
493 int i, saved_errno;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 if (x >= ERFC_CONTFRAC_CUTOFF)
496 return 0.0;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 x2 = x*x;
499 a = 0.0;
500 da = 0.5;
501 p = 1.0; p_last = 0.0;
502 q = da + x2; q_last = 1.0;
503 for (i = 0; i < ERFC_CONTFRAC_TERMS; i++) {
504 double temp;
505 a += da;
506 da += 2.0;
507 b = da + x2;
508 temp = p; p = b*p - a*p_last; p_last = temp;
509 temp = q; q = b*q - a*q_last; q_last = temp;
510 }
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000511 /* Issue #8986: On some platforms, exp sets errno on underflow to zero;
512 save the current errno value so that we can restore it later. */
513 saved_errno = errno;
514 result = p / q * x * exp(-x2) / sqrtpi;
515 errno = saved_errno;
516 return result;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000517}
518
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200519#endif /* !defined(HAVE_ERF) || !defined(HAVE_ERFC) */
520
Mark Dickinson45f992a2009-12-19 11:20:49 +0000521/* Error function erf(x), for general x */
522
523static double
524m_erf(double x)
525{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200526#ifdef HAVE_ERF
527 return erf(x);
528#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 double absx, cf;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 if (Py_IS_NAN(x))
532 return x;
533 absx = fabs(x);
534 if (absx < ERF_SERIES_CUTOFF)
535 return m_erf_series(x);
536 else {
537 cf = m_erfc_contfrac(absx);
538 return x > 0.0 ? 1.0 - cf : cf - 1.0;
539 }
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200540#endif
Mark Dickinson45f992a2009-12-19 11:20:49 +0000541}
542
543/* Complementary error function erfc(x), for general x. */
544
545static double
546m_erfc(double x)
547{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200548#ifdef HAVE_ERFC
549 return erfc(x);
550#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 double absx, cf;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 if (Py_IS_NAN(x))
554 return x;
555 absx = fabs(x);
556 if (absx < ERF_SERIES_CUTOFF)
557 return 1.0 - m_erf_series(x);
558 else {
559 cf = m_erfc_contfrac(absx);
560 return x > 0.0 ? cf : 2.0 - cf;
561 }
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200562#endif
Mark Dickinson45f992a2009-12-19 11:20:49 +0000563}
Mark Dickinson05d2e082009-12-11 20:17:17 +0000564
565/*
Christian Heimese57950f2008-04-21 13:08:03 +0000566 wrapper for atan2 that deals directly with special cases before
567 delegating to the platform libm for the remaining cases. This
568 is necessary to get consistent behaviour across platforms.
569 Windows, FreeBSD and alpha Tru64 are amongst platforms that don't
570 always follow C99.
571*/
572
573static double
574m_atan2(double y, double x)
575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 if (Py_IS_NAN(x) || Py_IS_NAN(y))
577 return Py_NAN;
578 if (Py_IS_INFINITY(y)) {
579 if (Py_IS_INFINITY(x)) {
580 if (copysign(1., x) == 1.)
581 /* atan2(+-inf, +inf) == +-pi/4 */
582 return copysign(0.25*Py_MATH_PI, y);
583 else
584 /* atan2(+-inf, -inf) == +-pi*3/4 */
585 return copysign(0.75*Py_MATH_PI, y);
586 }
587 /* atan2(+-inf, x) == +-pi/2 for finite x */
588 return copysign(0.5*Py_MATH_PI, y);
589 }
590 if (Py_IS_INFINITY(x) || y == 0.) {
591 if (copysign(1., x) == 1.)
592 /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */
593 return copysign(0., y);
594 else
595 /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */
596 return copysign(Py_MATH_PI, y);
597 }
598 return atan2(y, x);
Christian Heimese57950f2008-04-21 13:08:03 +0000599}
600
601/*
Mark Dickinsone675f082008-12-11 21:56:00 +0000602 Various platforms (Solaris, OpenBSD) do nonstandard things for log(0),
603 log(-ve), log(NaN). Here are wrappers for log and log10 that deal with
604 special values directly, passing positive non-special values through to
605 the system log/log10.
606 */
607
608static double
609m_log(double x)
610{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 if (Py_IS_FINITE(x)) {
612 if (x > 0.0)
613 return log(x);
614 errno = EDOM;
615 if (x == 0.0)
616 return -Py_HUGE_VAL; /* log(0) = -inf */
617 else
618 return Py_NAN; /* log(-ve) = nan */
619 }
620 else if (Py_IS_NAN(x))
621 return x; /* log(nan) = nan */
622 else if (x > 0.0)
623 return x; /* log(inf) = inf */
624 else {
625 errno = EDOM;
626 return Py_NAN; /* log(-inf) = nan */
627 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000628}
629
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200630/*
631 log2: log to base 2.
632
633 Uses an algorithm that should:
Mark Dickinson83b8c0b2011-05-09 08:40:20 +0100634
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200635 (a) produce exact results for powers of 2, and
Mark Dickinson83b8c0b2011-05-09 08:40:20 +0100636 (b) give a monotonic log2 (for positive finite floats),
637 assuming that the system log is monotonic.
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200638*/
639
640static double
641m_log2(double x)
642{
643 if (!Py_IS_FINITE(x)) {
644 if (Py_IS_NAN(x))
645 return x; /* log2(nan) = nan */
646 else if (x > 0.0)
647 return x; /* log2(+inf) = +inf */
648 else {
649 errno = EDOM;
650 return Py_NAN; /* log2(-inf) = nan, invalid-operation */
651 }
652 }
653
654 if (x > 0.0) {
Victor Stinner8f9f8d62011-05-09 12:45:41 +0200655#ifdef HAVE_LOG2
656 return log2(x);
657#else
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200658 double m;
659 int e;
660 m = frexp(x, &e);
661 /* We want log2(m * 2**e) == log(m) / log(2) + e. Care is needed when
662 * x is just greater than 1.0: in that case e is 1, log(m) is negative,
663 * and we get significant cancellation error from the addition of
664 * log(m) / log(2) to e. The slight rewrite of the expression below
665 * avoids this problem.
666 */
667 if (x >= 1.0) {
668 return log(2.0 * m) / log(2.0) + (e - 1);
669 }
670 else {
671 return log(m) / log(2.0) + e;
672 }
Victor Stinner8f9f8d62011-05-09 12:45:41 +0200673#endif
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200674 }
675 else if (x == 0.0) {
676 errno = EDOM;
677 return -Py_HUGE_VAL; /* log2(0) = -inf, divide-by-zero */
678 }
679 else {
680 errno = EDOM;
Mark Dickinson23442582011-05-09 08:05:00 +0100681 return Py_NAN; /* log2(-inf) = nan, invalid-operation */
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200682 }
683}
684
Mark Dickinsone675f082008-12-11 21:56:00 +0000685static double
686m_log10(double x)
687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 if (Py_IS_FINITE(x)) {
689 if (x > 0.0)
690 return log10(x);
691 errno = EDOM;
692 if (x == 0.0)
693 return -Py_HUGE_VAL; /* log10(0) = -inf */
694 else
695 return Py_NAN; /* log10(-ve) = nan */
696 }
697 else if (Py_IS_NAN(x))
698 return x; /* log10(nan) = nan */
699 else if (x > 0.0)
700 return x; /* log10(inf) = inf */
701 else {
702 errno = EDOM;
703 return Py_NAN; /* log10(-inf) = nan */
704 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000705}
706
707
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200708/*[clinic input]
709math.gcd
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300710
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200711 x as a: object
712 y as b: object
713 /
714
715greatest common divisor of x and y
716[clinic start generated code]*/
717
718static PyObject *
719math_gcd_impl(PyObject *module, PyObject *a, PyObject *b)
720/*[clinic end generated code: output=7b2e0c151bd7a5d8 input=c2691e57fb2a98fa]*/
721{
722 PyObject *g;
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300723
724 a = PyNumber_Index(a);
725 if (a == NULL)
726 return NULL;
727 b = PyNumber_Index(b);
728 if (b == NULL) {
729 Py_DECREF(a);
730 return NULL;
731 }
732 g = _PyLong_GCD(a, b);
733 Py_DECREF(a);
734 Py_DECREF(b);
735 return g;
736}
737
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300738
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000739/* Call is_error when errno != 0, and where x is the result libm
740 * returned. is_error will usually set up an exception and return
741 * true (1), but may return false (0) without setting up an exception.
742 */
743static int
744is_error(double x)
745{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 int result = 1; /* presumption of guilt */
747 assert(errno); /* non-zero errno is a precondition for calling */
748 if (errno == EDOM)
749 PyErr_SetString(PyExc_ValueError, "math domain error");
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 else if (errno == ERANGE) {
752 /* ANSI C generally requires libm functions to set ERANGE
753 * on overflow, but also generally *allows* them to set
754 * ERANGE on underflow too. There's no consistency about
755 * the latter across platforms.
756 * Alas, C99 never requires that errno be set.
757 * Here we suppress the underflow errors (libm functions
758 * should return a zero on underflow, and +- HUGE_VAL on
759 * overflow, so testing the result for zero suffices to
760 * distinguish the cases).
761 *
762 * On some platforms (Ubuntu/ia64) it seems that errno can be
763 * set to ERANGE for subnormal results that do *not* underflow
764 * to zero. So to be safe, we'll ignore ERANGE whenever the
765 * function result is less than one in absolute value.
766 */
767 if (fabs(x) < 1.0)
768 result = 0;
769 else
770 PyErr_SetString(PyExc_OverflowError,
771 "math range error");
772 }
773 else
774 /* Unexpected math error */
775 PyErr_SetFromErrno(PyExc_ValueError);
776 return result;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000777}
778
Mark Dickinsone675f082008-12-11 21:56:00 +0000779/*
Christian Heimes53876d92008-04-19 00:31:39 +0000780 math_1 is used to wrap a libm function f that takes a double
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200781 argument and returns a double.
Christian Heimes53876d92008-04-19 00:31:39 +0000782
783 The error reporting follows these rules, which are designed to do
784 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
785 platforms.
786
787 - a NaN result from non-NaN inputs causes ValueError to be raised
788 - an infinite result from finite inputs causes OverflowError to be
789 raised if can_overflow is 1, or raises ValueError if can_overflow
790 is 0.
791 - if the result is finite and errno == EDOM then ValueError is
792 raised
793 - if the result is finite and nonzero and errno == ERANGE then
794 OverflowError is raised
795
796 The last rule is used to catch overflow on platforms which follow
797 C89 but for which HUGE_VAL is not an infinity.
798
799 For the majority of one-argument functions these rules are enough
800 to ensure that Python's functions behave as specified in 'Annex F'
801 of the C99 standard, with the 'invalid' and 'divide-by-zero'
802 floating-point exceptions mapping to Python's ValueError and the
803 'overflow' floating-point exception mapping to OverflowError.
804 math_1 only works for functions that don't have singularities *and*
805 the possibility of overflow; fortunately, that covers everything we
806 care about right now.
807*/
808
Barry Warsaw8b43b191996-12-09 22:32:36 +0000809static PyObject *
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000810math_1_to_whatever(PyObject *arg, double (*func) (double),
Christian Heimes53876d92008-04-19 00:31:39 +0000811 PyObject *(*from_double_func) (double),
812 int can_overflow)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000813{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 double x, r;
815 x = PyFloat_AsDouble(arg);
816 if (x == -1.0 && PyErr_Occurred())
817 return NULL;
818 errno = 0;
819 PyFPE_START_PROTECT("in math_1", return 0);
820 r = (*func)(x);
821 PyFPE_END_PROTECT(r);
822 if (Py_IS_NAN(r) && !Py_IS_NAN(x)) {
823 PyErr_SetString(PyExc_ValueError,
824 "math domain error"); /* invalid arg */
825 return NULL;
826 }
827 if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) {
Benjamin Peterson2354a752012-03-13 16:13:09 -0500828 if (can_overflow)
829 PyErr_SetString(PyExc_OverflowError,
830 "math range error"); /* overflow */
831 else
832 PyErr_SetString(PyExc_ValueError,
833 "math domain error"); /* singularity */
834 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 }
836 if (Py_IS_FINITE(r) && errno && is_error(r))
837 /* this branch unnecessary on most platforms */
838 return NULL;
Mark Dickinsonde429622008-05-01 00:19:23 +0000839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 return (*from_double_func)(r);
Christian Heimes53876d92008-04-19 00:31:39 +0000841}
842
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000843/* variant of math_1, to be used when the function being wrapped is known to
844 set errno properly (that is, errno = EDOM for invalid or divide-by-zero,
845 errno = ERANGE for overflow). */
846
847static PyObject *
848math_1a(PyObject *arg, double (*func) (double))
849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 double x, r;
851 x = PyFloat_AsDouble(arg);
852 if (x == -1.0 && PyErr_Occurred())
853 return NULL;
854 errno = 0;
855 PyFPE_START_PROTECT("in math_1a", return 0);
856 r = (*func)(x);
857 PyFPE_END_PROTECT(r);
858 if (errno && is_error(r))
859 return NULL;
860 return PyFloat_FromDouble(r);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000861}
862
Christian Heimes53876d92008-04-19 00:31:39 +0000863/*
864 math_2 is used to wrap a libm function f that takes two double
865 arguments and returns a double.
866
867 The error reporting follows these rules, which are designed to do
868 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
869 platforms.
870
871 - a NaN result from non-NaN inputs causes ValueError to be raised
872 - an infinite result from finite inputs causes OverflowError to be
873 raised.
874 - if the result is finite and errno == EDOM then ValueError is
875 raised
876 - if the result is finite and nonzero and errno == ERANGE then
877 OverflowError is raised
878
879 The last rule is used to catch overflow on platforms which follow
880 C89 but for which HUGE_VAL is not an infinity.
881
882 For most two-argument functions (copysign, fmod, hypot, atan2)
883 these rules are enough to ensure that Python's functions behave as
884 specified in 'Annex F' of the C99 standard, with the 'invalid' and
885 'divide-by-zero' floating-point exceptions mapping to Python's
886 ValueError and the 'overflow' floating-point exception mapping to
887 OverflowError.
888*/
889
890static PyObject *
891math_1(PyObject *arg, double (*func) (double), int can_overflow)
892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow);
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000894}
895
896static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000897math_1_to_int(PyObject *arg, double (*func) (double), int can_overflow)
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000898{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 return math_1_to_whatever(arg, func, PyLong_FromDouble, can_overflow);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000900}
901
Barry Warsaw8b43b191996-12-09 22:32:36 +0000902static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200903math_2(PyObject *args, double (*func) (double, double), const char *funcname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000904{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 PyObject *ox, *oy;
906 double x, y, r;
907 if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy))
908 return NULL;
909 x = PyFloat_AsDouble(ox);
910 y = PyFloat_AsDouble(oy);
911 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
912 return NULL;
913 errno = 0;
914 PyFPE_START_PROTECT("in math_2", return 0);
915 r = (*func)(x, y);
916 PyFPE_END_PROTECT(r);
917 if (Py_IS_NAN(r)) {
918 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
919 errno = EDOM;
920 else
921 errno = 0;
922 }
923 else if (Py_IS_INFINITY(r)) {
924 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
925 errno = ERANGE;
926 else
927 errno = 0;
928 }
929 if (errno && is_error(r))
930 return NULL;
931 else
932 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000933}
934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935#define FUNC1(funcname, func, can_overflow, docstring) \
936 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
937 return math_1(args, func, can_overflow); \
938 }\
939 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941#define FUNC1A(funcname, func, docstring) \
942 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
943 return math_1a(args, func); \
944 }\
945 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000946
Fred Drake40c48682000-07-03 18:11:56 +0000947#define FUNC2(funcname, func, docstring) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
949 return math_2(args, func, #funcname); \
950 }\
951 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000952
Christian Heimes53876d92008-04-19 00:31:39 +0000953FUNC1(acos, acos, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200954 "acos($module, x, /)\n--\n\n"
955 "Return the arc cosine (measured in radians) of x.")
Mark Dickinsonf3718592009-12-21 15:27:41 +0000956FUNC1(acosh, m_acosh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200957 "acosh($module, x, /)\n--\n\n"
958 "Return the inverse hyperbolic cosine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000959FUNC1(asin, asin, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200960 "asin($module, x, /)\n--\n\n"
961 "Return the arc sine (measured in radians) of x.")
Mark Dickinsonf3718592009-12-21 15:27:41 +0000962FUNC1(asinh, m_asinh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200963 "asinh($module, x, /)\n--\n\n"
964 "Return the inverse hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000965FUNC1(atan, atan, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200966 "atan($module, x, /)\n--\n\n"
967 "Return the arc tangent (measured in radians) of x.")
Christian Heimese57950f2008-04-21 13:08:03 +0000968FUNC2(atan2, m_atan2,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200969 "atan2($module, y, x, /)\n--\n\n"
970 "Return the arc tangent (measured in radians) of y/x.\n\n"
Tim Petersfe71f812001-08-07 22:10:00 +0000971 "Unlike atan(y/x), the signs of both x and y are considered.")
Mark Dickinsonf3718592009-12-21 15:27:41 +0000972FUNC1(atanh, m_atanh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200973 "atanh($module, x, /)\n--\n\n"
974 "Return the inverse hyperbolic tangent of x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +0000975
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200976/*[clinic input]
977math.ceil
978
979 x as number: object
980 /
981
982Return the ceiling of x as an Integral.
983
984This is the smallest integer >= x.
985[clinic start generated code]*/
986
987static PyObject *
988math_ceil(PyObject *module, PyObject *number)
989/*[clinic end generated code: output=6c3b8a78bc201c67 input=2725352806399cab]*/
990{
Benjamin Petersonce798522012-01-22 11:24:29 -0500991 _Py_IDENTIFIER(__ceil__);
Mark Dickinson6d02d9c2010-07-02 16:05:15 +0000992 PyObject *method, *result;
Guido van Rossum13e05de2007-08-23 22:56:55 +0000993
Benjamin Petersonce798522012-01-22 11:24:29 -0500994 method = _PyObject_LookupSpecial(number, &PyId___ceil__);
Benjamin Petersonf751bc92010-07-02 13:46:42 +0000995 if (method == NULL) {
996 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 return math_1_to_int(number, ceil, 0);
Benjamin Petersonf751bc92010-07-02 13:46:42 +0000999 }
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001000 result = _PyObject_CallNoArg(method);
Mark Dickinson6d02d9c2010-07-02 16:05:15 +00001001 Py_DECREF(method);
1002 return result;
Guido van Rossum13e05de2007-08-23 22:56:55 +00001003}
1004
Christian Heimes072c0f12008-01-03 23:01:04 +00001005FUNC2(copysign, copysign,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001006 "copysign($module, x, y, /)\n--\n\n"
1007 "Return a float with the magnitude (absolute value) of x but the sign of y.\n\n"
1008 "On platforms that support signed zeros, copysign(1.0, -0.0)\n"
1009 "returns -1.0.\n")
Christian Heimes53876d92008-04-19 00:31:39 +00001010FUNC1(cos, cos, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001011 "cos($module, x, /)\n--\n\n"
1012 "Return the cosine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001013FUNC1(cosh, cosh, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001014 "cosh($module, x, /)\n--\n\n"
1015 "Return the hyperbolic cosine of x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +00001016FUNC1A(erf, m_erf,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001017 "erf($module, x, /)\n--\n\n"
1018 "Error function at x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +00001019FUNC1A(erfc, m_erfc,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001020 "erfc($module, x, /)\n--\n\n"
1021 "Complementary error function at x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001022FUNC1(exp, exp, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001023 "exp($module, x, /)\n--\n\n"
1024 "Return e raised to the power of x.")
Mark Dickinson664b5112009-12-16 20:23:42 +00001025FUNC1(expm1, m_expm1, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001026 "expm1($module, x, /)\n--\n\n"
1027 "Return exp(x)-1.\n\n"
Mark Dickinson664b5112009-12-16 20:23:42 +00001028 "This function avoids the loss of precision involved in the direct "
1029 "evaluation of exp(x)-1 for small x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001030FUNC1(fabs, fabs, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001031 "fabs($module, x, /)\n--\n\n"
1032 "Return the absolute value of the float x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +00001033
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001034/*[clinic input]
1035math.floor
1036
1037 x as number: object
1038 /
1039
1040Return the floor of x as an Integral.
1041
1042This is the largest integer <= x.
1043[clinic start generated code]*/
1044
1045static PyObject *
1046math_floor(PyObject *module, PyObject *number)
1047/*[clinic end generated code: output=c6a65c4884884b8a input=63af6b5d7ebcc3d6]*/
1048{
Benjamin Petersonce798522012-01-22 11:24:29 -05001049 _Py_IDENTIFIER(__floor__);
Benjamin Petersonb0125892010-07-02 13:35:17 +00001050 PyObject *method, *result;
Guido van Rossum13e05de2007-08-23 22:56:55 +00001051
Benjamin Petersonce798522012-01-22 11:24:29 -05001052 method = _PyObject_LookupSpecial(number, &PyId___floor__);
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001053 if (method == NULL) {
1054 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 return math_1_to_int(number, floor, 0);
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001057 }
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001058 result = _PyObject_CallNoArg(method);
Benjamin Petersonb0125892010-07-02 13:35:17 +00001059 Py_DECREF(method);
1060 return result;
Guido van Rossum13e05de2007-08-23 22:56:55 +00001061}
1062
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001063FUNC1A(gamma, m_tgamma,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001064 "gamma($module, x, /)\n--\n\n"
1065 "Gamma function at x.")
Mark Dickinson05d2e082009-12-11 20:17:17 +00001066FUNC1A(lgamma, m_lgamma,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001067 "lgamma($module, x, /)\n--\n\n"
1068 "Natural logarithm of absolute value of Gamma function at x.")
Mark Dickinsonbe64d952010-07-07 16:21:29 +00001069FUNC1(log1p, m_log1p, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001070 "log1p($module, x, /)\n--\n\n"
1071 "Return the natural logarithm of 1+x (base e).\n\n"
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001072 "The result is computed in a way which is accurate for x near zero.")
Christian Heimes53876d92008-04-19 00:31:39 +00001073FUNC1(sin, sin, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001074 "sin($module, x, /)\n--\n\n"
1075 "Return the sine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001076FUNC1(sinh, sinh, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001077 "sinh($module, x, /)\n--\n\n"
1078 "Return the hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001079FUNC1(sqrt, sqrt, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001080 "sqrt($module, x, /)\n--\n\n"
1081 "Return the square root of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001082FUNC1(tan, tan, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001083 "tan($module, x, /)\n--\n\n"
1084 "Return the tangent of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001085FUNC1(tanh, tanh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001086 "tanh($module, x, /)\n--\n\n"
1087 "Return the hyperbolic tangent of x.")
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001088
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001089/* Precision summation function as msum() by Raymond Hettinger in
1090 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
1091 enhanced with the exact partials sum and roundoff from Mark
1092 Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
1093 See those links for more details, proofs and other references.
1094
1095 Note 1: IEEE 754R floating point semantics are assumed,
1096 but the current implementation does not re-establish special
1097 value semantics across iterations (i.e. handling -Inf + Inf).
1098
1099 Note 2: No provision is made for intermediate overflow handling;
Georg Brandlf78e02b2008-06-10 17:40:04 +00001100 therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001101 sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
1102 overflow of the first partial sum.
1103
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001104 Note 3: The intermediate values lo, yr, and hi are declared volatile so
1105 aggressive compilers won't algebraically reduce lo to always be exactly 0.0.
Georg Brandlf78e02b2008-06-10 17:40:04 +00001106 Also, the volatile declaration forces the values to be stored in memory as
1107 regular doubles instead of extended long precision (80-bit) values. This
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001108 prevents double rounding because any addition or subtraction of two doubles
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 can be resolved exactly into double-sized hi and lo values. As long as the
Georg Brandlf78e02b2008-06-10 17:40:04 +00001110 hi value gets forced into a double before yr and lo are computed, the extra
1111 bits in downstream extended precision operations (x87 for example) will be
1112 exactly zero and therefore can be losslessly stored back into a double,
1113 thereby preventing double rounding.
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001114
1115 Note 4: A similar implementation is in Modules/cmathmodule.c.
1116 Be sure to update both when making changes.
1117
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001118 Note 5: The signature of math.fsum() differs from builtins.sum()
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001119 because the start argument doesn't make sense in the context of
1120 accurate summation. Since the partials table is collapsed before
1121 returning a result, sum(seq2, start=sum(seq1)) may not equal the
1122 accurate result returned by sum(itertools.chain(seq1, seq2)).
1123*/
1124
1125#define NUM_PARTIALS 32 /* initial partials array size, on stack */
1126
1127/* Extend the partials array p[] by doubling its size. */
1128static int /* non-zero on error */
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001129_fsum_realloc(double **p_ptr, Py_ssize_t n,
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001130 double *ps, Py_ssize_t *m_ptr)
1131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 void *v = NULL;
1133 Py_ssize_t m = *m_ptr;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 m += m; /* double */
Victor Stinner049e5092014-08-17 22:20:00 +02001136 if (n < m && (size_t)m < ((size_t)PY_SSIZE_T_MAX / sizeof(double))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 double *p = *p_ptr;
1138 if (p == ps) {
1139 v = PyMem_Malloc(sizeof(double) * m);
1140 if (v != NULL)
1141 memcpy(v, ps, sizeof(double) * n);
1142 }
1143 else
1144 v = PyMem_Realloc(p, sizeof(double) * m);
1145 }
1146 if (v == NULL) { /* size overflow or no memory */
1147 PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
1148 return 1;
1149 }
1150 *p_ptr = (double*) v;
1151 *m_ptr = m;
1152 return 0;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001153}
1154
1155/* Full precision summation of a sequence of floats.
1156
1157 def msum(iterable):
1158 partials = [] # sorted, non-overlapping partial sums
1159 for x in iterable:
Mark Dickinsonfdb0acc2010-06-25 20:22:24 +00001160 i = 0
1161 for y in partials:
1162 if abs(x) < abs(y):
1163 x, y = y, x
1164 hi = x + y
1165 lo = y - (hi - x)
1166 if lo:
1167 partials[i] = lo
1168 i += 1
1169 x = hi
1170 partials[i:] = [x]
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001171 return sum_exact(partials)
1172
1173 Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
1174 are exactly equal to x+y. The inner loop applies hi/lo summation to each
1175 partial so that the list of partial sums remains exact.
1176
1177 Sum_exact() adds the partial sums exactly and correctly rounds the final
1178 result (using the round-half-to-even rule). The items in partials remain
1179 non-zero, non-special, non-overlapping and strictly increasing in
1180 magnitude, but possibly not all having the same sign.
1181
1182 Depends on IEEE 754 arithmetic guarantees and half-even rounding.
1183*/
1184
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001185/*[clinic input]
1186math.fsum
1187
1188 seq: object
1189 /
1190
1191Return an accurate floating point sum of values in the iterable seq.
1192
1193Assumes IEEE-754 floating point arithmetic.
1194[clinic start generated code]*/
1195
1196static PyObject *
1197math_fsum(PyObject *module, PyObject *seq)
1198/*[clinic end generated code: output=ba5c672b87fe34fc input=c51b7d8caf6f6e82]*/
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 PyObject *item, *iter, *sum = NULL;
1201 Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
1202 double x, y, t, ps[NUM_PARTIALS], *p = ps;
1203 double xsave, special_sum = 0.0, inf_sum = 0.0;
1204 volatile double hi, yr, lo;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 iter = PyObject_GetIter(seq);
1207 if (iter == NULL)
1208 return NULL;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 for(;;) { /* for x in iterable */
1213 assert(0 <= n && n <= m);
1214 assert((m == NUM_PARTIALS && p == ps) ||
1215 (m > NUM_PARTIALS && p != NULL));
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 item = PyIter_Next(iter);
1218 if (item == NULL) {
1219 if (PyErr_Occurred())
1220 goto _fsum_error;
1221 break;
1222 }
1223 x = PyFloat_AsDouble(item);
1224 Py_DECREF(item);
1225 if (PyErr_Occurred())
1226 goto _fsum_error;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 xsave = x;
1229 for (i = j = 0; j < n; j++) { /* for y in partials */
1230 y = p[j];
1231 if (fabs(x) < fabs(y)) {
1232 t = x; x = y; y = t;
1233 }
1234 hi = x + y;
1235 yr = hi - x;
1236 lo = y - yr;
1237 if (lo != 0.0)
1238 p[i++] = lo;
1239 x = hi;
1240 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 n = i; /* ps[i:] = [x] */
1243 if (x != 0.0) {
1244 if (! Py_IS_FINITE(x)) {
1245 /* a nonfinite x could arise either as
1246 a result of intermediate overflow, or
1247 as a result of a nan or inf in the
1248 summands */
1249 if (Py_IS_FINITE(xsave)) {
1250 PyErr_SetString(PyExc_OverflowError,
1251 "intermediate overflow in fsum");
1252 goto _fsum_error;
1253 }
1254 if (Py_IS_INFINITY(xsave))
1255 inf_sum += xsave;
1256 special_sum += xsave;
1257 /* reset partials */
1258 n = 0;
1259 }
1260 else if (n >= m && _fsum_realloc(&p, n, ps, &m))
1261 goto _fsum_error;
1262 else
1263 p[n++] = x;
1264 }
1265 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 if (special_sum != 0.0) {
1268 if (Py_IS_NAN(inf_sum))
1269 PyErr_SetString(PyExc_ValueError,
1270 "-inf + inf in fsum");
1271 else
1272 sum = PyFloat_FromDouble(special_sum);
1273 goto _fsum_error;
1274 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 hi = 0.0;
1277 if (n > 0) {
1278 hi = p[--n];
1279 /* sum_exact(ps, hi) from the top, stop when the sum becomes
1280 inexact. */
1281 while (n > 0) {
1282 x = hi;
1283 y = p[--n];
1284 assert(fabs(y) < fabs(x));
1285 hi = x + y;
1286 yr = hi - x;
1287 lo = y - yr;
1288 if (lo != 0.0)
1289 break;
1290 }
1291 /* Make half-even rounding work across multiple partials.
1292 Needed so that sum([1e-16, 1, 1e16]) will round-up the last
1293 digit to two instead of down to zero (the 1e-16 makes the 1
1294 slightly closer to two). With a potential 1 ULP rounding
1295 error fixed-up, math.fsum() can guarantee commutativity. */
1296 if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
1297 (lo > 0.0 && p[n-1] > 0.0))) {
1298 y = lo * 2.0;
1299 x = hi + y;
1300 yr = x - hi;
1301 if (y == yr)
1302 hi = x;
1303 }
1304 }
1305 sum = PyFloat_FromDouble(hi);
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001306
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001307_fsum_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 PyFPE_END_PROTECT(hi)
1309 Py_DECREF(iter);
1310 if (p != ps)
1311 PyMem_Free(p);
1312 return sum;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001313}
1314
1315#undef NUM_PARTIALS
1316
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001317
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001318/* Return the smallest integer k such that n < 2**k, or 0 if n == 0.
1319 * Equivalent to floor(lg(x))+1. Also equivalent to: bitwidth_of_type -
1320 * count_leading_zero_bits(x)
1321 */
1322
1323/* XXX: This routine does more or less the same thing as
1324 * bits_in_digit() in Objects/longobject.c. Someday it would be nice to
1325 * consolidate them. On BSD, there's a library function called fls()
1326 * that we could use, and GCC provides __builtin_clz().
1327 */
1328
1329static unsigned long
1330bit_length(unsigned long n)
1331{
1332 unsigned long len = 0;
1333 while (n != 0) {
1334 ++len;
1335 n >>= 1;
1336 }
1337 return len;
1338}
1339
1340static unsigned long
1341count_set_bits(unsigned long n)
1342{
1343 unsigned long count = 0;
1344 while (n != 0) {
1345 ++count;
1346 n &= n - 1; /* clear least significant bit */
1347 }
1348 return count;
1349}
1350
1351/* Divide-and-conquer factorial algorithm
1352 *
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07001353 * Based on the formula and pseudo-code provided at:
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001354 * http://www.luschny.de/math/factorial/binarysplitfact.html
1355 *
1356 * Faster algorithms exist, but they're more complicated and depend on
Ezio Melotti9527afd2010-07-08 15:03:02 +00001357 * a fast prime factorization algorithm.
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001358 *
1359 * Notes on the algorithm
1360 * ----------------------
1361 *
1362 * factorial(n) is written in the form 2**k * m, with m odd. k and m are
1363 * computed separately, and then combined using a left shift.
1364 *
1365 * The function factorial_odd_part computes the odd part m (i.e., the greatest
1366 * odd divisor) of factorial(n), using the formula:
1367 *
1368 * factorial_odd_part(n) =
1369 *
1370 * product_{i >= 0} product_{0 < j <= n / 2**i, j odd} j
1371 *
1372 * Example: factorial_odd_part(20) =
1373 *
1374 * (1) *
1375 * (1) *
1376 * (1 * 3 * 5) *
1377 * (1 * 3 * 5 * 7 * 9)
1378 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1379 *
1380 * Here i goes from large to small: the first term corresponds to i=4 (any
1381 * larger i gives an empty product), and the last term corresponds to i=0.
1382 * Each term can be computed from the last by multiplying by the extra odd
1383 * numbers required: e.g., to get from the penultimate term to the last one,
1384 * we multiply by (11 * 13 * 15 * 17 * 19).
1385 *
1386 * To see a hint of why this formula works, here are the same numbers as above
1387 * but with the even parts (i.e., the appropriate powers of 2) included. For
1388 * each subterm in the product for i, we multiply that subterm by 2**i:
1389 *
1390 * factorial(20) =
1391 *
1392 * (16) *
1393 * (8) *
1394 * (4 * 12 * 20) *
1395 * (2 * 6 * 10 * 14 * 18) *
1396 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1397 *
1398 * The factorial_partial_product function computes the product of all odd j in
1399 * range(start, stop) for given start and stop. It's used to compute the
1400 * partial products like (11 * 13 * 15 * 17 * 19) in the example above. It
1401 * operates recursively, repeatedly splitting the range into two roughly equal
1402 * pieces until the subranges are small enough to be computed using only C
1403 * integer arithmetic.
1404 *
1405 * The two-valuation k (i.e., the exponent of the largest power of 2 dividing
1406 * the factorial) is computed independently in the main math_factorial
1407 * function. By standard results, its value is:
1408 *
1409 * two_valuation = n//2 + n//4 + n//8 + ....
1410 *
1411 * It can be shown (e.g., by complete induction on n) that two_valuation is
1412 * equal to n - count_set_bits(n), where count_set_bits(n) gives the number of
1413 * '1'-bits in the binary expansion of n.
1414 */
1415
1416/* factorial_partial_product: Compute product(range(start, stop, 2)) using
1417 * divide and conquer. Assumes start and stop are odd and stop > start.
1418 * max_bits must be >= bit_length(stop - 2). */
1419
1420static PyObject *
1421factorial_partial_product(unsigned long start, unsigned long stop,
1422 unsigned long max_bits)
1423{
1424 unsigned long midpoint, num_operands;
1425 PyObject *left = NULL, *right = NULL, *result = NULL;
1426
1427 /* If the return value will fit an unsigned long, then we can
1428 * multiply in a tight, fast loop where each multiply is O(1).
1429 * Compute an upper bound on the number of bits required to store
1430 * the answer.
1431 *
1432 * Storing some integer z requires floor(lg(z))+1 bits, which is
1433 * conveniently the value returned by bit_length(z). The
1434 * product x*y will require at most
1435 * bit_length(x) + bit_length(y) bits to store, based
1436 * on the idea that lg product = lg x + lg y.
1437 *
1438 * We know that stop - 2 is the largest number to be multiplied. From
1439 * there, we have: bit_length(answer) <= num_operands *
1440 * bit_length(stop - 2)
1441 */
1442
1443 num_operands = (stop - start) / 2;
1444 /* The "num_operands <= 8 * SIZEOF_LONG" check guards against the
1445 * unlikely case of an overflow in num_operands * max_bits. */
1446 if (num_operands <= 8 * SIZEOF_LONG &&
1447 num_operands * max_bits <= 8 * SIZEOF_LONG) {
1448 unsigned long j, total;
1449 for (total = start, j = start + 2; j < stop; j += 2)
1450 total *= j;
1451 return PyLong_FromUnsignedLong(total);
1452 }
1453
1454 /* find midpoint of range(start, stop), rounded up to next odd number. */
1455 midpoint = (start + num_operands) | 1;
1456 left = factorial_partial_product(start, midpoint,
1457 bit_length(midpoint - 2));
1458 if (left == NULL)
1459 goto error;
1460 right = factorial_partial_product(midpoint, stop, max_bits);
1461 if (right == NULL)
1462 goto error;
1463 result = PyNumber_Multiply(left, right);
1464
1465 error:
1466 Py_XDECREF(left);
1467 Py_XDECREF(right);
1468 return result;
1469}
1470
1471/* factorial_odd_part: compute the odd part of factorial(n). */
1472
1473static PyObject *
1474factorial_odd_part(unsigned long n)
1475{
1476 long i;
1477 unsigned long v, lower, upper;
1478 PyObject *partial, *tmp, *inner, *outer;
1479
1480 inner = PyLong_FromLong(1);
1481 if (inner == NULL)
1482 return NULL;
1483 outer = inner;
1484 Py_INCREF(outer);
1485
1486 upper = 3;
1487 for (i = bit_length(n) - 2; i >= 0; i--) {
1488 v = n >> i;
1489 if (v <= 2)
1490 continue;
1491 lower = upper;
1492 /* (v + 1) | 1 = least odd integer strictly larger than n / 2**i */
1493 upper = (v + 1) | 1;
1494 /* Here inner is the product of all odd integers j in the range (0,
1495 n/2**(i+1)]. The factorial_partial_product call below gives the
1496 product of all odd integers j in the range (n/2**(i+1), n/2**i]. */
1497 partial = factorial_partial_product(lower, upper, bit_length(upper-2));
1498 /* inner *= partial */
1499 if (partial == NULL)
1500 goto error;
1501 tmp = PyNumber_Multiply(inner, partial);
1502 Py_DECREF(partial);
1503 if (tmp == NULL)
1504 goto error;
1505 Py_DECREF(inner);
1506 inner = tmp;
1507 /* Now inner is the product of all odd integers j in the range (0,
1508 n/2**i], giving the inner product in the formula above. */
1509
1510 /* outer *= inner; */
1511 tmp = PyNumber_Multiply(outer, inner);
1512 if (tmp == NULL)
1513 goto error;
1514 Py_DECREF(outer);
1515 outer = tmp;
1516 }
Mark Dickinson76464492012-10-25 10:46:28 +01001517 Py_DECREF(inner);
1518 return outer;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001519
1520 error:
1521 Py_DECREF(outer);
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001522 Py_DECREF(inner);
Mark Dickinson76464492012-10-25 10:46:28 +01001523 return NULL;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001524}
1525
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001526
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001527/* Lookup table for small factorial values */
1528
1529static const unsigned long SmallFactorials[] = {
1530 1, 1, 2, 6, 24, 120, 720, 5040, 40320,
1531 362880, 3628800, 39916800, 479001600,
1532#if SIZEOF_LONG >= 8
1533 6227020800, 87178291200, 1307674368000,
1534 20922789888000, 355687428096000, 6402373705728000,
1535 121645100408832000, 2432902008176640000
1536#endif
1537};
1538
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001539/*[clinic input]
1540math.factorial
1541
1542 x as arg: object
1543 /
1544
1545Find x!.
1546
1547Raise a ValueError if x is negative or non-integral.
1548[clinic start generated code]*/
1549
Barry Warsaw8b43b191996-12-09 22:32:36 +00001550static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001551math_factorial(PyObject *module, PyObject *arg)
1552/*[clinic end generated code: output=6686f26fae00e9ca input=6d1c8105c0d91fb4]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001553{
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001554 long x;
Mark Dickinson5990d282014-04-10 09:29:39 -04001555 int overflow;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001556 PyObject *result, *odd_part, *two_valuation;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 if (PyFloat_Check(arg)) {
1559 PyObject *lx;
1560 double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
1561 if (!(Py_IS_FINITE(dx) && dx == floor(dx))) {
1562 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001563 "factorial() only accepts integral values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 return NULL;
1565 }
1566 lx = PyLong_FromDouble(dx);
1567 if (lx == NULL)
1568 return NULL;
Mark Dickinson5990d282014-04-10 09:29:39 -04001569 x = PyLong_AsLongAndOverflow(lx, &overflow);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 Py_DECREF(lx);
1571 }
1572 else
Mark Dickinson5990d282014-04-10 09:29:39 -04001573 x = PyLong_AsLongAndOverflow(arg, &overflow);
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001574
Mark Dickinson5990d282014-04-10 09:29:39 -04001575 if (x == -1 && PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 return NULL;
Mark Dickinson5990d282014-04-10 09:29:39 -04001577 }
1578 else if (overflow == 1) {
1579 PyErr_Format(PyExc_OverflowError,
1580 "factorial() argument should not exceed %ld",
1581 LONG_MAX);
1582 return NULL;
1583 }
1584 else if (overflow == -1 || x < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001586 "factorial() not defined for negative values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 return NULL;
1588 }
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001589
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001590 /* use lookup table if x is small */
Victor Stinner63941882011-09-29 00:42:28 +02001591 if (x < (long)Py_ARRAY_LENGTH(SmallFactorials))
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001592 return PyLong_FromUnsignedLong(SmallFactorials[x]);
1593
1594 /* else express in the form odd_part * 2**two_valuation, and compute as
1595 odd_part << two_valuation. */
1596 odd_part = factorial_odd_part(x);
1597 if (odd_part == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 return NULL;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001599 two_valuation = PyLong_FromLong(x - count_set_bits(x));
1600 if (two_valuation == NULL) {
1601 Py_DECREF(odd_part);
1602 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 }
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001604 result = PyNumber_Lshift(odd_part, two_valuation);
1605 Py_DECREF(two_valuation);
1606 Py_DECREF(odd_part);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 return result;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001608}
1609
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001610
1611/*[clinic input]
1612math.trunc
1613
1614 x: object
1615 /
1616
1617Truncates the Real x to the nearest Integral toward 0.
1618
1619Uses the __trunc__ magic method.
1620[clinic start generated code]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001621
1622static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001623math_trunc(PyObject *module, PyObject *x)
1624/*[clinic end generated code: output=34b9697b707e1031 input=2168b34e0a09134d]*/
Christian Heimes400adb02008-02-01 08:12:03 +00001625{
Benjamin Petersonce798522012-01-22 11:24:29 -05001626 _Py_IDENTIFIER(__trunc__);
Benjamin Petersonb0125892010-07-02 13:35:17 +00001627 PyObject *trunc, *result;
Christian Heimes400adb02008-02-01 08:12:03 +00001628
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001629 if (Py_TYPE(x)->tp_dict == NULL) {
1630 if (PyType_Ready(Py_TYPE(x)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 return NULL;
1632 }
Christian Heimes400adb02008-02-01 08:12:03 +00001633
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001634 trunc = _PyObject_LookupSpecial(x, &PyId___trunc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 if (trunc == NULL) {
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001636 if (!PyErr_Occurred())
1637 PyErr_Format(PyExc_TypeError,
1638 "type %.100s doesn't define __trunc__ method",
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001639 Py_TYPE(x)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 return NULL;
1641 }
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001642 result = _PyObject_CallNoArg(trunc);
Benjamin Petersonb0125892010-07-02 13:35:17 +00001643 Py_DECREF(trunc);
1644 return result;
Christian Heimes400adb02008-02-01 08:12:03 +00001645}
1646
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001647
1648/*[clinic input]
1649math.frexp
1650
1651 x: double
1652 /
1653
1654Return the mantissa and exponent of x, as pair (m, e).
1655
1656m is a float and e is an int, such that x = m * 2.**e.
1657If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.
1658[clinic start generated code]*/
Christian Heimes400adb02008-02-01 08:12:03 +00001659
1660static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001661math_frexp_impl(PyObject *module, double x)
1662/*[clinic end generated code: output=03e30d252a15ad4a input=96251c9e208bc6e9]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00001663{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 /* deal with special cases directly, to sidestep platform
1666 differences */
1667 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
1668 i = 0;
1669 }
1670 else {
1671 PyFPE_START_PROTECT("in math_frexp", return 0);
1672 x = frexp(x, &i);
1673 PyFPE_END_PROTECT(x);
1674 }
1675 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001676}
1677
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001678
1679/*[clinic input]
1680math.ldexp
1681
1682 x: double
1683 i: object
1684 /
1685
1686Return x * (2**i).
1687
1688This is essentially the inverse of frexp().
1689[clinic start generated code]*/
Guido van Rossumc6e22901998-12-04 19:26:43 +00001690
Barry Warsaw8b43b191996-12-09 22:32:36 +00001691static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001692math_ldexp_impl(PyObject *module, double x, PyObject *i)
1693/*[clinic end generated code: output=b6892f3c2df9cc6a input=17d5970c1a40a8c1]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00001694{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001695 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 long exp;
1697 int overflow;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001698
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001699 if (PyLong_Check(i)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 /* on overflow, replace exponent with either LONG_MAX
1701 or LONG_MIN, depending on the sign. */
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001702 exp = PyLong_AsLongAndOverflow(i, &overflow);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 if (exp == -1 && PyErr_Occurred())
1704 return NULL;
1705 if (overflow)
1706 exp = overflow < 0 ? LONG_MIN : LONG_MAX;
1707 }
1708 else {
1709 PyErr_SetString(PyExc_TypeError,
Serhiy Storchaka95949422013-08-27 19:40:23 +03001710 "Expected an int as second argument to ldexp.");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 return NULL;
1712 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 if (x == 0. || !Py_IS_FINITE(x)) {
1715 /* NaNs, zeros and infinities are returned unchanged */
1716 r = x;
1717 errno = 0;
1718 } else if (exp > INT_MAX) {
1719 /* overflow */
1720 r = copysign(Py_HUGE_VAL, x);
1721 errno = ERANGE;
1722 } else if (exp < INT_MIN) {
1723 /* underflow to +-0 */
1724 r = copysign(0., x);
1725 errno = 0;
1726 } else {
1727 errno = 0;
1728 PyFPE_START_PROTECT("in math_ldexp", return 0);
1729 r = ldexp(x, (int)exp);
1730 PyFPE_END_PROTECT(r);
1731 if (Py_IS_INFINITY(r))
1732 errno = ERANGE;
1733 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 if (errno && is_error(r))
1736 return NULL;
1737 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001738}
1739
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001740
1741/*[clinic input]
1742math.modf
1743
1744 x: double
1745 /
1746
1747Return the fractional and integer parts of x.
1748
1749Both results carry the sign of x and are floats.
1750[clinic start generated code]*/
Guido van Rossumc6e22901998-12-04 19:26:43 +00001751
Barry Warsaw8b43b191996-12-09 22:32:36 +00001752static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001753math_modf_impl(PyObject *module, double x)
1754/*[clinic end generated code: output=90cee0260014c3c0 input=b4cfb6786afd9035]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00001755{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001756 double y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 /* some platforms don't do the right thing for NaNs and
1758 infinities, so we take care of special cases directly. */
1759 if (!Py_IS_FINITE(x)) {
1760 if (Py_IS_INFINITY(x))
1761 return Py_BuildValue("(dd)", copysign(0., x), x);
1762 else if (Py_IS_NAN(x))
1763 return Py_BuildValue("(dd)", x, x);
1764 }
Christian Heimesa342c012008-04-20 21:01:16 +00001765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 errno = 0;
1767 PyFPE_START_PROTECT("in math_modf", return 0);
1768 x = modf(x, &y);
1769 PyFPE_END_PROTECT(x);
1770 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001771}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001772
Guido van Rossumc6e22901998-12-04 19:26:43 +00001773
Serhiy Storchaka95949422013-08-27 19:40:23 +03001774/* A decent logarithm is easy to compute even for huge ints, but libm can't
Tim Peters78526162001-09-05 00:53:45 +00001775 do that by itself -- loghelper can. func is log or log10, and name is
Serhiy Storchaka95949422013-08-27 19:40:23 +03001776 "log" or "log10". Note that overflow of the result isn't possible: an int
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00001777 can contain no more than INT_MAX * SHIFT bits, so has value certainly less
1778 than 2**(2**64 * 2**16) == 2**2**80, and log2 of that is 2**80, which is
Tim Peters78526162001-09-05 00:53:45 +00001779 small enough to fit in an IEEE single. log and log10 are even smaller.
Serhiy Storchaka95949422013-08-27 19:40:23 +03001780 However, intermediate overflow is possible for an int if the number of bits
1781 in that int is larger than PY_SSIZE_T_MAX. */
Tim Peters78526162001-09-05 00:53:45 +00001782
1783static PyObject*
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001784loghelper(PyObject* arg, double (*func)(double), const char *funcname)
Tim Peters78526162001-09-05 00:53:45 +00001785{
Serhiy Storchaka95949422013-08-27 19:40:23 +03001786 /* If it is int, do it ourselves. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 if (PyLong_Check(arg)) {
Mark Dickinsonc6037172010-09-29 19:06:36 +00001788 double x, result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 Py_ssize_t e;
Mark Dickinsonc6037172010-09-29 19:06:36 +00001790
1791 /* Negative or zero inputs give a ValueError. */
1792 if (Py_SIZE(arg) <= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 PyErr_SetString(PyExc_ValueError,
1794 "math domain error");
1795 return NULL;
1796 }
Mark Dickinsonfa41e602010-09-28 07:22:27 +00001797
Mark Dickinsonc6037172010-09-29 19:06:36 +00001798 x = PyLong_AsDouble(arg);
1799 if (x == -1.0 && PyErr_Occurred()) {
1800 if (!PyErr_ExceptionMatches(PyExc_OverflowError))
1801 return NULL;
1802 /* Here the conversion to double overflowed, but it's possible
1803 to compute the log anyway. Clear the exception and continue. */
1804 PyErr_Clear();
1805 x = _PyLong_Frexp((PyLongObject *)arg, &e);
1806 if (x == -1.0 && PyErr_Occurred())
1807 return NULL;
1808 /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */
1809 result = func(x) + func(2.0) * e;
1810 }
1811 else
1812 /* Successfully converted x to a double. */
1813 result = func(x);
1814 return PyFloat_FromDouble(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 }
Tim Peters78526162001-09-05 00:53:45 +00001816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 /* Else let libm handle it by itself. */
1818 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +00001819}
1820
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001821
1822/*[clinic input]
1823math.log
1824
1825 x: object
1826 [
1827 base: object(c_default="NULL") = math.e
1828 ]
1829 /
1830
1831Return the logarithm of x to the given base.
1832
1833If the base not specified, returns the natural logarithm (base e) of x.
1834[clinic start generated code]*/
1835
Tim Peters78526162001-09-05 00:53:45 +00001836static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001837math_log_impl(PyObject *module, PyObject *x, int group_right_1,
1838 PyObject *base)
1839/*[clinic end generated code: output=7b5a39e526b73fc9 input=0f62d5726cbfebbd]*/
Tim Peters78526162001-09-05 00:53:45 +00001840{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 PyObject *num, *den;
1842 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001843
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001844 num = loghelper(x, m_log, "log");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 if (num == NULL || base == NULL)
1846 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 den = loghelper(base, m_log, "log");
1849 if (den == NULL) {
1850 Py_DECREF(num);
1851 return NULL;
1852 }
Raymond Hettinger866964c2002-12-14 19:51:34 +00001853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 ans = PyNumber_TrueDivide(num, den);
1855 Py_DECREF(num);
1856 Py_DECREF(den);
1857 return ans;
Tim Peters78526162001-09-05 00:53:45 +00001858}
1859
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001860
1861/*[clinic input]
1862math.log2
1863
1864 x: object
1865 /
1866
1867Return the base 2 logarithm of x.
1868[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00001869
1870static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001871math_log2(PyObject *module, PyObject *x)
1872/*[clinic end generated code: output=5425899a4d5d6acb input=08321262bae4f39b]*/
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001873{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001874 return loghelper(x, m_log2, "log2");
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001875}
1876
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001877
1878/*[clinic input]
1879math.log10
1880
1881 x: object
1882 /
1883
1884Return the base 10 logarithm of x.
1885[clinic start generated code]*/
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001886
1887static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001888math_log10(PyObject *module, PyObject *x)
1889/*[clinic end generated code: output=be72a64617df9c6f input=b2469d02c6469e53]*/
Tim Peters78526162001-09-05 00:53:45 +00001890{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001891 return loghelper(x, m_log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +00001892}
1893
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001894
1895/*[clinic input]
1896math.fmod
1897
1898 x: double
1899 y: double
1900 /
1901
1902Return fmod(x, y), according to platform C.
1903
1904x % y may differ.
1905[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00001906
Christian Heimes53876d92008-04-19 00:31:39 +00001907static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001908math_fmod_impl(PyObject *module, double x, double y)
1909/*[clinic end generated code: output=7559d794343a27b5 input=4f84caa8cfc26a03]*/
Christian Heimes53876d92008-04-19 00:31:39 +00001910{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001911 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 /* fmod(x, +/-Inf) returns x for finite x. */
1913 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
1914 return PyFloat_FromDouble(x);
1915 errno = 0;
1916 PyFPE_START_PROTECT("in math_fmod", return 0);
1917 r = fmod(x, y);
1918 PyFPE_END_PROTECT(r);
1919 if (Py_IS_NAN(r)) {
1920 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1921 errno = EDOM;
1922 else
1923 errno = 0;
1924 }
1925 if (errno && is_error(r))
1926 return NULL;
1927 else
1928 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00001929}
1930
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001931
1932/*[clinic input]
1933math.hypot
1934
1935 x: double
1936 y: double
1937 /
1938
1939Return the Euclidean distance, sqrt(x*x + y*y).
1940[clinic start generated code]*/
Christian Heimes53876d92008-04-19 00:31:39 +00001941
1942static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001943math_hypot_impl(PyObject *module, double x, double y)
1944/*[clinic end generated code: output=b7686e5be468ef87 input=7f8eea70406474aa]*/
Christian Heimes53876d92008-04-19 00:31:39 +00001945{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001946 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */
1948 if (Py_IS_INFINITY(x))
1949 return PyFloat_FromDouble(fabs(x));
1950 if (Py_IS_INFINITY(y))
1951 return PyFloat_FromDouble(fabs(y));
1952 errno = 0;
1953 PyFPE_START_PROTECT("in math_hypot", return 0);
1954 r = hypot(x, y);
1955 PyFPE_END_PROTECT(r);
1956 if (Py_IS_NAN(r)) {
1957 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1958 errno = EDOM;
1959 else
1960 errno = 0;
1961 }
1962 else if (Py_IS_INFINITY(r)) {
1963 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
1964 errno = ERANGE;
1965 else
1966 errno = 0;
1967 }
1968 if (errno && is_error(r))
1969 return NULL;
1970 else
1971 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00001972}
1973
Christian Heimes53876d92008-04-19 00:31:39 +00001974
1975/* pow can't use math_2, but needs its own wrapper: the problem is
1976 that an infinite result can arise either as a result of overflow
1977 (in which case OverflowError should be raised) or as a result of
1978 e.g. 0.**-5. (for which ValueError needs to be raised.)
1979*/
1980
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001981/*[clinic input]
1982math.pow
Christian Heimes53876d92008-04-19 00:31:39 +00001983
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001984 x: double
1985 y: double
1986 /
1987
1988Return x**y (x to the power of y).
1989[clinic start generated code]*/
1990
1991static PyObject *
1992math_pow_impl(PyObject *module, double x, double y)
1993/*[clinic end generated code: output=fff93e65abccd6b0 input=c26f1f6075088bfd]*/
1994{
1995 double r;
1996 int odd_y;
Christian Heimesa342c012008-04-20 21:01:16 +00001997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 /* deal directly with IEEE specials, to cope with problems on various
1999 platforms whose semantics don't exactly match C99 */
2000 r = 0.; /* silence compiler warning */
2001 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
2002 errno = 0;
2003 if (Py_IS_NAN(x))
2004 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
2005 else if (Py_IS_NAN(y))
2006 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
2007 else if (Py_IS_INFINITY(x)) {
2008 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
2009 if (y > 0.)
2010 r = odd_y ? x : fabs(x);
2011 else if (y == 0.)
2012 r = 1.;
2013 else /* y < 0. */
2014 r = odd_y ? copysign(0., x) : 0.;
2015 }
2016 else if (Py_IS_INFINITY(y)) {
2017 if (fabs(x) == 1.0)
2018 r = 1.;
2019 else if (y > 0. && fabs(x) > 1.0)
2020 r = y;
2021 else if (y < 0. && fabs(x) < 1.0) {
2022 r = -y; /* result is +inf */
2023 if (x == 0.) /* 0**-inf: divide-by-zero */
2024 errno = EDOM;
2025 }
2026 else
2027 r = 0.;
2028 }
2029 }
2030 else {
2031 /* let libm handle finite**finite */
2032 errno = 0;
2033 PyFPE_START_PROTECT("in math_pow", return 0);
2034 r = pow(x, y);
2035 PyFPE_END_PROTECT(r);
2036 /* a NaN result should arise only from (-ve)**(finite
2037 non-integer); in this case we want to raise ValueError. */
2038 if (!Py_IS_FINITE(r)) {
2039 if (Py_IS_NAN(r)) {
2040 errno = EDOM;
2041 }
2042 /*
2043 an infinite result here arises either from:
2044 (A) (+/-0.)**negative (-> divide-by-zero)
2045 (B) overflow of x**y with x and y finite
2046 */
2047 else if (Py_IS_INFINITY(r)) {
2048 if (x == 0.)
2049 errno = EDOM;
2050 else
2051 errno = ERANGE;
2052 }
2053 }
2054 }
Christian Heimes53876d92008-04-19 00:31:39 +00002055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 if (errno && is_error(r))
2057 return NULL;
2058 else
2059 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00002060}
2061
Christian Heimes53876d92008-04-19 00:31:39 +00002062
Christian Heimes072c0f12008-01-03 23:01:04 +00002063static const double degToRad = Py_MATH_PI / 180.0;
2064static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002065
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002066/*[clinic input]
2067math.degrees
2068
2069 x: double
2070 /
2071
2072Convert angle x from radians to degrees.
2073[clinic start generated code]*/
2074
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002075static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002076math_degrees_impl(PyObject *module, double x)
2077/*[clinic end generated code: output=7fea78b294acd12f input=81e016555d6e3660]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002078{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002080}
2081
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002082
2083/*[clinic input]
2084math.radians
2085
2086 x: double
2087 /
2088
2089Convert angle x from degrees to radians.
2090[clinic start generated code]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002091
2092static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002093math_radians_impl(PyObject *module, double x)
2094/*[clinic end generated code: output=34daa47caf9b1590 input=91626fc489fe3d63]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 return PyFloat_FromDouble(x * degToRad);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002097}
2098
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002099
2100/*[clinic input]
2101math.isfinite
2102
2103 x: double
2104 /
2105
2106Return True if x is neither an infinity nor a NaN, and False otherwise.
2107[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002108
Christian Heimes072c0f12008-01-03 23:01:04 +00002109static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002110math_isfinite_impl(PyObject *module, double x)
2111/*[clinic end generated code: output=8ba1f396440c9901 input=46967d254812e54a]*/
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002112{
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002113 return PyBool_FromLong((long)Py_IS_FINITE(x));
2114}
2115
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002116
2117/*[clinic input]
2118math.isnan
2119
2120 x: double
2121 /
2122
2123Return True if x is a NaN (not a number), and False otherwise.
2124[clinic start generated code]*/
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002125
2126static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002127math_isnan_impl(PyObject *module, double x)
2128/*[clinic end generated code: output=f537b4d6df878c3e input=935891e66083f46a]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00002131}
2132
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002133
2134/*[clinic input]
2135math.isinf
2136
2137 x: double
2138 /
2139
2140Return True if x is a positive or negative infinity, and False otherwise.
2141[clinic start generated code]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002142
2143static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002144math_isinf_impl(PyObject *module, double x)
2145/*[clinic end generated code: output=9f00cbec4de7b06b input=32630e4212cf961f]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00002148}
2149
Christian Heimes072c0f12008-01-03 23:01:04 +00002150
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002151/*[clinic input]
2152math.isclose -> bool
2153
2154 a: double
2155 b: double
2156 *
2157 rel_tol: double = 1e-09
2158 maximum difference for being considered "close", relative to the
2159 magnitude of the input values
2160 abs_tol: double = 0.0
2161 maximum difference for being considered "close", regardless of the
2162 magnitude of the input values
2163
2164Determine whether two floating point numbers are close in value.
2165
2166Return True if a is close in value to b, and False otherwise.
2167
2168For the values to be considered close, the difference between them
2169must be smaller than at least one of the tolerances.
2170
2171-inf, inf and NaN behave similarly to the IEEE 754 Standard. That
2172is, NaN is not close to anything, even itself. inf and -inf are
2173only close to themselves.
2174[clinic start generated code]*/
2175
2176static int
2177math_isclose_impl(PyObject *module, double a, double b, double rel_tol,
2178 double abs_tol)
2179/*[clinic end generated code: output=b73070207511952d input=f28671871ea5bfba]*/
Tal Einatd5519ed2015-05-31 22:05:00 +03002180{
Tal Einatd5519ed2015-05-31 22:05:00 +03002181 double diff = 0.0;
Tal Einatd5519ed2015-05-31 22:05:00 +03002182
2183 /* sanity check on the inputs */
2184 if (rel_tol < 0.0 || abs_tol < 0.0 ) {
2185 PyErr_SetString(PyExc_ValueError,
2186 "tolerances must be non-negative");
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002187 return -1;
Tal Einatd5519ed2015-05-31 22:05:00 +03002188 }
2189
2190 if ( a == b ) {
2191 /* short circuit exact equality -- needed to catch two infinities of
2192 the same sign. And perhaps speeds things up a bit sometimes.
2193 */
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002194 return 1;
Tal Einatd5519ed2015-05-31 22:05:00 +03002195 }
2196
2197 /* This catches the case of two infinities of opposite sign, or
2198 one infinity and one finite number. Two infinities of opposite
2199 sign would otherwise have an infinite relative tolerance.
2200 Two infinities of the same sign are caught by the equality check
2201 above.
2202 */
2203
2204 if (Py_IS_INFINITY(a) || Py_IS_INFINITY(b)) {
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002205 return 0;
Tal Einatd5519ed2015-05-31 22:05:00 +03002206 }
2207
2208 /* now do the regular computation
2209 this is essentially the "weak" test from the Boost library
2210 */
2211
2212 diff = fabs(b - a);
2213
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002214 return (((diff <= fabs(rel_tol * b)) ||
2215 (diff <= fabs(rel_tol * a))) ||
2216 (diff <= abs_tol));
Tal Einatd5519ed2015-05-31 22:05:00 +03002217}
2218
Tal Einatd5519ed2015-05-31 22:05:00 +03002219
Barry Warsaw8b43b191996-12-09 22:32:36 +00002220static PyMethodDef math_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 {"acos", math_acos, METH_O, math_acos_doc},
2222 {"acosh", math_acosh, METH_O, math_acosh_doc},
2223 {"asin", math_asin, METH_O, math_asin_doc},
2224 {"asinh", math_asinh, METH_O, math_asinh_doc},
2225 {"atan", math_atan, METH_O, math_atan_doc},
2226 {"atan2", math_atan2, METH_VARARGS, math_atan2_doc},
2227 {"atanh", math_atanh, METH_O, math_atanh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002228 MATH_CEIL_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 {"copysign", math_copysign, METH_VARARGS, math_copysign_doc},
2230 {"cos", math_cos, METH_O, math_cos_doc},
2231 {"cosh", math_cosh, METH_O, math_cosh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002232 MATH_DEGREES_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 {"erf", math_erf, METH_O, math_erf_doc},
2234 {"erfc", math_erfc, METH_O, math_erfc_doc},
2235 {"exp", math_exp, METH_O, math_exp_doc},
2236 {"expm1", math_expm1, METH_O, math_expm1_doc},
2237 {"fabs", math_fabs, METH_O, math_fabs_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002238 MATH_FACTORIAL_METHODDEF
2239 MATH_FLOOR_METHODDEF
2240 MATH_FMOD_METHODDEF
2241 MATH_FREXP_METHODDEF
2242 MATH_FSUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 {"gamma", math_gamma, METH_O, math_gamma_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002244 MATH_GCD_METHODDEF
2245 MATH_HYPOT_METHODDEF
2246 MATH_ISCLOSE_METHODDEF
2247 MATH_ISFINITE_METHODDEF
2248 MATH_ISINF_METHODDEF
2249 MATH_ISNAN_METHODDEF
2250 MATH_LDEXP_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002252 MATH_LOG_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 {"log1p", math_log1p, METH_O, math_log1p_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002254 MATH_LOG10_METHODDEF
2255 MATH_LOG2_METHODDEF
2256 MATH_MODF_METHODDEF
2257 MATH_POW_METHODDEF
2258 MATH_RADIANS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 {"sin", math_sin, METH_O, math_sin_doc},
2260 {"sinh", math_sinh, METH_O, math_sinh_doc},
2261 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
2262 {"tan", math_tan, METH_O, math_tan_doc},
2263 {"tanh", math_tanh, METH_O, math_tanh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002264 MATH_TRUNC_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002266};
2267
Guido van Rossumc6e22901998-12-04 19:26:43 +00002268
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002269PyDoc_STRVAR(module_doc,
Tim Peters63c94532001-09-04 23:17:42 +00002270"This module is always available. It provides access to the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002271"mathematical functions defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00002272
Martin v. Löwis1a214512008-06-11 05:26:20 +00002273
2274static struct PyModuleDef mathmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 PyModuleDef_HEAD_INIT,
2276 "math",
2277 module_doc,
2278 -1,
2279 math_methods,
2280 NULL,
2281 NULL,
2282 NULL,
2283 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002284};
2285
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002286PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002287PyInit_math(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 PyObject *m;
Tim Petersfe71f812001-08-07 22:10:00 +00002290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 m = PyModule_Create(&mathmodule);
2292 if (m == NULL)
2293 goto finally;
Barry Warsawfc93f751996-12-17 00:47:03 +00002294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
2296 PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
Guido van Rossum0a891d72016-08-15 09:12:52 -07002297 PyModule_AddObject(m, "tau", PyFloat_FromDouble(Py_MATH_TAU)); /* 2pi */
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +00002298 PyModule_AddObject(m, "inf", PyFloat_FromDouble(m_inf()));
2299#if !defined(PY_NO_SHORT_FLOAT_REPR) || defined(Py_NAN)
2300 PyModule_AddObject(m, "nan", PyFloat_FromDouble(m_nan()));
2301#endif
Barry Warsawfc93f751996-12-17 00:47:03 +00002302
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +00002303 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002305}