blob: 8bd38d0eb865c5c8a3ee288ab2b5f7a4e3edcfb3 [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{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 double r, absx;
Mark Dickinson05d2e082009-12-11 20:17:17 +0000368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 /* special cases */
370 if (!Py_IS_FINITE(x)) {
371 if (Py_IS_NAN(x))
372 return x; /* lgamma(nan) = nan */
373 else
374 return Py_HUGE_VAL; /* lgamma(+-inf) = +inf */
375 }
Mark Dickinson05d2e082009-12-11 20:17:17 +0000376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 /* integer arguments */
378 if (x == floor(x) && x <= 2.0) {
379 if (x <= 0.0) {
380 errno = EDOM; /* lgamma(n) = inf, divide-by-zero for */
381 return Py_HUGE_VAL; /* integers n <= 0 */
382 }
383 else {
384 return 0.0; /* lgamma(1) = lgamma(2) = 0.0 */
385 }
386 }
Mark Dickinson05d2e082009-12-11 20:17:17 +0000387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 absx = fabs(x);
389 /* tiny arguments: lgamma(x) ~ -log(fabs(x)) for small x */
390 if (absx < 1e-20)
391 return -log(absx);
Mark Dickinson05d2e082009-12-11 20:17:17 +0000392
Mark Dickinson9c91eb82010-07-07 16:17:31 +0000393 /* Lanczos' formula. We could save a fraction of a ulp in accuracy by
394 having a second set of numerator coefficients for lanczos_sum that
395 absorbed the exp(-lanczos_g) term, and throwing out the lanczos_g
396 subtraction below; it's probably not worth it. */
397 r = log(lanczos_sum(absx)) - lanczos_g;
398 r += (absx - 0.5) * (log(absx + lanczos_g - 0.5) - 1);
399 if (x < 0.0)
400 /* Use reflection formula to get value for negative x. */
401 r = logpi - log(fabs(sinpi(absx))) - log(absx) - r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 if (Py_IS_INFINITY(r))
403 errno = ERANGE;
404 return r;
Mark Dickinson05d2e082009-12-11 20:17:17 +0000405}
406
Mark Dickinson45f992a2009-12-19 11:20:49 +0000407/*
408 Implementations of the error function erf(x) and the complementary error
409 function erfc(x).
410
Brett Cannon45adb312016-01-15 09:38:24 -0800411 Method: we use a series approximation for erf for small x, and a continued
412 fraction approximation for erfc(x) for larger x;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000413 combined with the relations erf(-x) = -erf(x) and erfc(x) = 1.0 - erf(x),
414 this gives us erf(x) and erfc(x) for all x.
415
416 The series expansion used is:
417
418 erf(x) = x*exp(-x*x)/sqrt(pi) * [
419 2/1 + 4/3 x**2 + 8/15 x**4 + 16/105 x**6 + ...]
420
421 The coefficient of x**(2k-2) here is 4**k*factorial(k)/factorial(2*k).
422 This series converges well for smallish x, but slowly for larger x.
423
424 The continued fraction expansion used is:
425
426 erfc(x) = x*exp(-x*x)/sqrt(pi) * [1/(0.5 + x**2 -) 0.5/(2.5 + x**2 - )
427 3.0/(4.5 + x**2 - ) 7.5/(6.5 + x**2 - ) ...]
428
429 after the first term, the general term has the form:
430
431 k*(k-0.5)/(2*k+0.5 + x**2 - ...).
432
433 This expansion converges fast for larger x, but convergence becomes
434 infinitely slow as x approaches 0.0. The (somewhat naive) continued
435 fraction evaluation algorithm used below also risks overflow for large x;
436 but for large x, erfc(x) == 0.0 to within machine precision. (For
437 example, erfc(30.0) is approximately 2.56e-393).
438
439 Parameters: use series expansion for abs(x) < ERF_SERIES_CUTOFF and
440 continued fraction expansion for ERF_SERIES_CUTOFF <= abs(x) <
441 ERFC_CONTFRAC_CUTOFF. ERFC_SERIES_TERMS and ERFC_CONTFRAC_TERMS are the
442 numbers of terms to use for the relevant expansions. */
443
444#define ERF_SERIES_CUTOFF 1.5
445#define ERF_SERIES_TERMS 25
446#define ERFC_CONTFRAC_CUTOFF 30.0
447#define ERFC_CONTFRAC_TERMS 50
448
449/*
450 Error function, via power series.
451
452 Given a finite float x, return an approximation to erf(x).
453 Converges reasonably fast for small x.
454*/
455
456static double
457m_erf_series(double x)
458{
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000459 double x2, acc, fk, result;
460 int i, saved_errno;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 x2 = x * x;
463 acc = 0.0;
464 fk = (double)ERF_SERIES_TERMS + 0.5;
465 for (i = 0; i < ERF_SERIES_TERMS; i++) {
466 acc = 2.0 + x2 * acc / fk;
467 fk -= 1.0;
468 }
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000469 /* Make sure the exp call doesn't affect errno;
470 see m_erfc_contfrac for more. */
471 saved_errno = errno;
472 result = acc * x * exp(-x2) / sqrtpi;
473 errno = saved_errno;
474 return result;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000475}
476
477/*
478 Complementary error function, via continued fraction expansion.
479
480 Given a positive float x, return an approximation to erfc(x). Converges
481 reasonably fast for x large (say, x > 2.0), and should be safe from
482 overflow if x and nterms are not too large. On an IEEE 754 machine, with x
483 <= 30.0, we're safe up to nterms = 100. For x >= 30.0, erfc(x) is smaller
484 than the smallest representable nonzero float. */
485
486static double
487m_erfc_contfrac(double x)
488{
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000489 double x2, a, da, p, p_last, q, q_last, b, result;
490 int i, saved_errno;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 if (x >= ERFC_CONTFRAC_CUTOFF)
493 return 0.0;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 x2 = x*x;
496 a = 0.0;
497 da = 0.5;
498 p = 1.0; p_last = 0.0;
499 q = da + x2; q_last = 1.0;
500 for (i = 0; i < ERFC_CONTFRAC_TERMS; i++) {
501 double temp;
502 a += da;
503 da += 2.0;
504 b = da + x2;
505 temp = p; p = b*p - a*p_last; p_last = temp;
506 temp = q; q = b*q - a*q_last; q_last = temp;
507 }
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000508 /* Issue #8986: On some platforms, exp sets errno on underflow to zero;
509 save the current errno value so that we can restore it later. */
510 saved_errno = errno;
511 result = p / q * x * exp(-x2) / sqrtpi;
512 errno = saved_errno;
513 return result;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000514}
515
516/* Error function erf(x), for general x */
517
518static double
519m_erf(double x)
520{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 double absx, cf;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 if (Py_IS_NAN(x))
524 return x;
525 absx = fabs(x);
526 if (absx < ERF_SERIES_CUTOFF)
527 return m_erf_series(x);
528 else {
529 cf = m_erfc_contfrac(absx);
530 return x > 0.0 ? 1.0 - cf : cf - 1.0;
531 }
Mark Dickinson45f992a2009-12-19 11:20:49 +0000532}
533
534/* Complementary error function erfc(x), for general x. */
535
536static double
537m_erfc(double x)
538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 double absx, cf;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 if (Py_IS_NAN(x))
542 return x;
543 absx = fabs(x);
544 if (absx < ERF_SERIES_CUTOFF)
545 return 1.0 - m_erf_series(x);
546 else {
547 cf = m_erfc_contfrac(absx);
548 return x > 0.0 ? cf : 2.0 - cf;
549 }
Mark Dickinson45f992a2009-12-19 11:20:49 +0000550}
Mark Dickinson05d2e082009-12-11 20:17:17 +0000551
552/*
Christian Heimese57950f2008-04-21 13:08:03 +0000553 wrapper for atan2 that deals directly with special cases before
554 delegating to the platform libm for the remaining cases. This
555 is necessary to get consistent behaviour across platforms.
556 Windows, FreeBSD and alpha Tru64 are amongst platforms that don't
557 always follow C99.
558*/
559
560static double
561m_atan2(double y, double x)
562{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 if (Py_IS_NAN(x) || Py_IS_NAN(y))
564 return Py_NAN;
565 if (Py_IS_INFINITY(y)) {
566 if (Py_IS_INFINITY(x)) {
567 if (copysign(1., x) == 1.)
568 /* atan2(+-inf, +inf) == +-pi/4 */
569 return copysign(0.25*Py_MATH_PI, y);
570 else
571 /* atan2(+-inf, -inf) == +-pi*3/4 */
572 return copysign(0.75*Py_MATH_PI, y);
573 }
574 /* atan2(+-inf, x) == +-pi/2 for finite x */
575 return copysign(0.5*Py_MATH_PI, y);
576 }
577 if (Py_IS_INFINITY(x) || y == 0.) {
578 if (copysign(1., x) == 1.)
579 /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */
580 return copysign(0., y);
581 else
582 /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */
583 return copysign(Py_MATH_PI, y);
584 }
585 return atan2(y, x);
Christian Heimese57950f2008-04-21 13:08:03 +0000586}
587
588/*
Mark Dickinsone675f082008-12-11 21:56:00 +0000589 Various platforms (Solaris, OpenBSD) do nonstandard things for log(0),
590 log(-ve), log(NaN). Here are wrappers for log and log10 that deal with
591 special values directly, passing positive non-special values through to
592 the system log/log10.
593 */
594
595static double
596m_log(double x)
597{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 if (Py_IS_FINITE(x)) {
599 if (x > 0.0)
600 return log(x);
601 errno = EDOM;
602 if (x == 0.0)
603 return -Py_HUGE_VAL; /* log(0) = -inf */
604 else
605 return Py_NAN; /* log(-ve) = nan */
606 }
607 else if (Py_IS_NAN(x))
608 return x; /* log(nan) = nan */
609 else if (x > 0.0)
610 return x; /* log(inf) = inf */
611 else {
612 errno = EDOM;
613 return Py_NAN; /* log(-inf) = nan */
614 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000615}
616
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200617/*
618 log2: log to base 2.
619
620 Uses an algorithm that should:
Mark Dickinson83b8c0b2011-05-09 08:40:20 +0100621
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200622 (a) produce exact results for powers of 2, and
Mark Dickinson83b8c0b2011-05-09 08:40:20 +0100623 (b) give a monotonic log2 (for positive finite floats),
624 assuming that the system log is monotonic.
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200625*/
626
627static double
628m_log2(double x)
629{
630 if (!Py_IS_FINITE(x)) {
631 if (Py_IS_NAN(x))
632 return x; /* log2(nan) = nan */
633 else if (x > 0.0)
634 return x; /* log2(+inf) = +inf */
635 else {
636 errno = EDOM;
637 return Py_NAN; /* log2(-inf) = nan, invalid-operation */
638 }
639 }
640
641 if (x > 0.0) {
Victor Stinner8f9f8d62011-05-09 12:45:41 +0200642#ifdef HAVE_LOG2
643 return log2(x);
644#else
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200645 double m;
646 int e;
647 m = frexp(x, &e);
648 /* We want log2(m * 2**e) == log(m) / log(2) + e. Care is needed when
649 * x is just greater than 1.0: in that case e is 1, log(m) is negative,
650 * and we get significant cancellation error from the addition of
651 * log(m) / log(2) to e. The slight rewrite of the expression below
652 * avoids this problem.
653 */
654 if (x >= 1.0) {
655 return log(2.0 * m) / log(2.0) + (e - 1);
656 }
657 else {
658 return log(m) / log(2.0) + e;
659 }
Victor Stinner8f9f8d62011-05-09 12:45:41 +0200660#endif
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200661 }
662 else if (x == 0.0) {
663 errno = EDOM;
664 return -Py_HUGE_VAL; /* log2(0) = -inf, divide-by-zero */
665 }
666 else {
667 errno = EDOM;
Mark Dickinson23442582011-05-09 08:05:00 +0100668 return Py_NAN; /* log2(-inf) = nan, invalid-operation */
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200669 }
670}
671
Mark Dickinsone675f082008-12-11 21:56:00 +0000672static double
673m_log10(double x)
674{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 if (Py_IS_FINITE(x)) {
676 if (x > 0.0)
677 return log10(x);
678 errno = EDOM;
679 if (x == 0.0)
680 return -Py_HUGE_VAL; /* log10(0) = -inf */
681 else
682 return Py_NAN; /* log10(-ve) = nan */
683 }
684 else if (Py_IS_NAN(x))
685 return x; /* log10(nan) = nan */
686 else if (x > 0.0)
687 return x; /* log10(inf) = inf */
688 else {
689 errno = EDOM;
690 return Py_NAN; /* log10(-inf) = nan */
691 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000692}
693
694
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200695/*[clinic input]
696math.gcd
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300697
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200698 x as a: object
699 y as b: object
700 /
701
702greatest common divisor of x and y
703[clinic start generated code]*/
704
705static PyObject *
706math_gcd_impl(PyObject *module, PyObject *a, PyObject *b)
707/*[clinic end generated code: output=7b2e0c151bd7a5d8 input=c2691e57fb2a98fa]*/
708{
709 PyObject *g;
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300710
711 a = PyNumber_Index(a);
712 if (a == NULL)
713 return NULL;
714 b = PyNumber_Index(b);
715 if (b == NULL) {
716 Py_DECREF(a);
717 return NULL;
718 }
719 g = _PyLong_GCD(a, b);
720 Py_DECREF(a);
721 Py_DECREF(b);
722 return g;
723}
724
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300725
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000726/* Call is_error when errno != 0, and where x is the result libm
727 * returned. is_error will usually set up an exception and return
728 * true (1), but may return false (0) without setting up an exception.
729 */
730static int
731is_error(double x)
732{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 int result = 1; /* presumption of guilt */
734 assert(errno); /* non-zero errno is a precondition for calling */
735 if (errno == EDOM)
736 PyErr_SetString(PyExc_ValueError, "math domain error");
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 else if (errno == ERANGE) {
739 /* ANSI C generally requires libm functions to set ERANGE
740 * on overflow, but also generally *allows* them to set
741 * ERANGE on underflow too. There's no consistency about
742 * the latter across platforms.
743 * Alas, C99 never requires that errno be set.
744 * Here we suppress the underflow errors (libm functions
745 * should return a zero on underflow, and +- HUGE_VAL on
746 * overflow, so testing the result for zero suffices to
747 * distinguish the cases).
748 *
749 * On some platforms (Ubuntu/ia64) it seems that errno can be
750 * set to ERANGE for subnormal results that do *not* underflow
751 * to zero. So to be safe, we'll ignore ERANGE whenever the
752 * function result is less than one in absolute value.
753 */
754 if (fabs(x) < 1.0)
755 result = 0;
756 else
757 PyErr_SetString(PyExc_OverflowError,
758 "math range error");
759 }
760 else
761 /* Unexpected math error */
762 PyErr_SetFromErrno(PyExc_ValueError);
763 return result;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000764}
765
Mark Dickinsone675f082008-12-11 21:56:00 +0000766/*
Christian Heimes53876d92008-04-19 00:31:39 +0000767 math_1 is used to wrap a libm function f that takes a double
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200768 argument and returns a double.
Christian Heimes53876d92008-04-19 00:31:39 +0000769
770 The error reporting follows these rules, which are designed to do
771 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
772 platforms.
773
774 - a NaN result from non-NaN inputs causes ValueError to be raised
775 - an infinite result from finite inputs causes OverflowError to be
776 raised if can_overflow is 1, or raises ValueError if can_overflow
777 is 0.
778 - if the result is finite and errno == EDOM then ValueError is
779 raised
780 - if the result is finite and nonzero and errno == ERANGE then
781 OverflowError is raised
782
783 The last rule is used to catch overflow on platforms which follow
784 C89 but for which HUGE_VAL is not an infinity.
785
786 For the majority of one-argument functions these rules are enough
787 to ensure that Python's functions behave as specified in 'Annex F'
788 of the C99 standard, with the 'invalid' and 'divide-by-zero'
789 floating-point exceptions mapping to Python's ValueError and the
790 'overflow' floating-point exception mapping to OverflowError.
791 math_1 only works for functions that don't have singularities *and*
792 the possibility of overflow; fortunately, that covers everything we
793 care about right now.
794*/
795
Barry Warsaw8b43b191996-12-09 22:32:36 +0000796static PyObject *
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000797math_1_to_whatever(PyObject *arg, double (*func) (double),
Christian Heimes53876d92008-04-19 00:31:39 +0000798 PyObject *(*from_double_func) (double),
799 int can_overflow)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000800{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 double x, r;
802 x = PyFloat_AsDouble(arg);
803 if (x == -1.0 && PyErr_Occurred())
804 return NULL;
805 errno = 0;
806 PyFPE_START_PROTECT("in math_1", return 0);
807 r = (*func)(x);
808 PyFPE_END_PROTECT(r);
809 if (Py_IS_NAN(r) && !Py_IS_NAN(x)) {
810 PyErr_SetString(PyExc_ValueError,
811 "math domain error"); /* invalid arg */
812 return NULL;
813 }
814 if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) {
Benjamin Peterson2354a752012-03-13 16:13:09 -0500815 if (can_overflow)
816 PyErr_SetString(PyExc_OverflowError,
817 "math range error"); /* overflow */
818 else
819 PyErr_SetString(PyExc_ValueError,
820 "math domain error"); /* singularity */
821 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 }
823 if (Py_IS_FINITE(r) && errno && is_error(r))
824 /* this branch unnecessary on most platforms */
825 return NULL;
Mark Dickinsonde429622008-05-01 00:19:23 +0000826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 return (*from_double_func)(r);
Christian Heimes53876d92008-04-19 00:31:39 +0000828}
829
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000830/* variant of math_1, to be used when the function being wrapped is known to
831 set errno properly (that is, errno = EDOM for invalid or divide-by-zero,
832 errno = ERANGE for overflow). */
833
834static PyObject *
835math_1a(PyObject *arg, double (*func) (double))
836{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 double x, r;
838 x = PyFloat_AsDouble(arg);
839 if (x == -1.0 && PyErr_Occurred())
840 return NULL;
841 errno = 0;
842 PyFPE_START_PROTECT("in math_1a", return 0);
843 r = (*func)(x);
844 PyFPE_END_PROTECT(r);
845 if (errno && is_error(r))
846 return NULL;
847 return PyFloat_FromDouble(r);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000848}
849
Christian Heimes53876d92008-04-19 00:31:39 +0000850/*
851 math_2 is used to wrap a libm function f that takes two double
852 arguments and returns a double.
853
854 The error reporting follows these rules, which are designed to do
855 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
856 platforms.
857
858 - a NaN result from non-NaN inputs causes ValueError to be raised
859 - an infinite result from finite inputs causes OverflowError to be
860 raised.
861 - if the result is finite and errno == EDOM then ValueError is
862 raised
863 - if the result is finite and nonzero and errno == ERANGE then
864 OverflowError is raised
865
866 The last rule is used to catch overflow on platforms which follow
867 C89 but for which HUGE_VAL is not an infinity.
868
869 For most two-argument functions (copysign, fmod, hypot, atan2)
870 these rules are enough to ensure that Python's functions behave as
871 specified in 'Annex F' of the C99 standard, with the 'invalid' and
872 'divide-by-zero' floating-point exceptions mapping to Python's
873 ValueError and the 'overflow' floating-point exception mapping to
874 OverflowError.
875*/
876
877static PyObject *
878math_1(PyObject *arg, double (*func) (double), int can_overflow)
879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow);
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000881}
882
883static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000884math_1_to_int(PyObject *arg, double (*func) (double), int can_overflow)
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 return math_1_to_whatever(arg, func, PyLong_FromDouble, can_overflow);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000887}
888
Barry Warsaw8b43b191996-12-09 22:32:36 +0000889static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200890math_2(PyObject *args, double (*func) (double, double), const char *funcname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000891{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 PyObject *ox, *oy;
893 double x, y, r;
894 if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy))
895 return NULL;
896 x = PyFloat_AsDouble(ox);
897 y = PyFloat_AsDouble(oy);
898 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
899 return NULL;
900 errno = 0;
901 PyFPE_START_PROTECT("in math_2", return 0);
902 r = (*func)(x, y);
903 PyFPE_END_PROTECT(r);
904 if (Py_IS_NAN(r)) {
905 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
906 errno = EDOM;
907 else
908 errno = 0;
909 }
910 else if (Py_IS_INFINITY(r)) {
911 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
912 errno = ERANGE;
913 else
914 errno = 0;
915 }
916 if (errno && is_error(r))
917 return NULL;
918 else
919 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000920}
921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922#define FUNC1(funcname, func, can_overflow, docstring) \
923 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
924 return math_1(args, func, can_overflow); \
925 }\
926 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928#define FUNC1A(funcname, func, docstring) \
929 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
930 return math_1a(args, func); \
931 }\
932 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000933
Fred Drake40c48682000-07-03 18:11:56 +0000934#define FUNC2(funcname, func, docstring) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
936 return math_2(args, func, #funcname); \
937 }\
938 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000939
Christian Heimes53876d92008-04-19 00:31:39 +0000940FUNC1(acos, acos, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200941 "acos($module, x, /)\n--\n\n"
942 "Return the arc cosine (measured in radians) of x.")
Mark Dickinsonf3718592009-12-21 15:27:41 +0000943FUNC1(acosh, m_acosh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200944 "acosh($module, x, /)\n--\n\n"
945 "Return the inverse hyperbolic cosine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000946FUNC1(asin, asin, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200947 "asin($module, x, /)\n--\n\n"
948 "Return the arc sine (measured in radians) of x.")
Mark Dickinsonf3718592009-12-21 15:27:41 +0000949FUNC1(asinh, m_asinh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200950 "asinh($module, x, /)\n--\n\n"
951 "Return the inverse hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000952FUNC1(atan, atan, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200953 "atan($module, x, /)\n--\n\n"
954 "Return the arc tangent (measured in radians) of x.")
Christian Heimese57950f2008-04-21 13:08:03 +0000955FUNC2(atan2, m_atan2,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200956 "atan2($module, y, x, /)\n--\n\n"
957 "Return the arc tangent (measured in radians) of y/x.\n\n"
Tim Petersfe71f812001-08-07 22:10:00 +0000958 "Unlike atan(y/x), the signs of both x and y are considered.")
Mark Dickinsonf3718592009-12-21 15:27:41 +0000959FUNC1(atanh, m_atanh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200960 "atanh($module, x, /)\n--\n\n"
961 "Return the inverse hyperbolic tangent of x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +0000962
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200963/*[clinic input]
964math.ceil
965
966 x as number: object
967 /
968
969Return the ceiling of x as an Integral.
970
971This is the smallest integer >= x.
972[clinic start generated code]*/
973
974static PyObject *
975math_ceil(PyObject *module, PyObject *number)
976/*[clinic end generated code: output=6c3b8a78bc201c67 input=2725352806399cab]*/
977{
Benjamin Petersonce798522012-01-22 11:24:29 -0500978 _Py_IDENTIFIER(__ceil__);
Mark Dickinson6d02d9c2010-07-02 16:05:15 +0000979 PyObject *method, *result;
Guido van Rossum13e05de2007-08-23 22:56:55 +0000980
Benjamin Petersonce798522012-01-22 11:24:29 -0500981 method = _PyObject_LookupSpecial(number, &PyId___ceil__);
Benjamin Petersonf751bc92010-07-02 13:46:42 +0000982 if (method == NULL) {
983 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 return math_1_to_int(number, ceil, 0);
Benjamin Petersonf751bc92010-07-02 13:46:42 +0000986 }
Victor Stinnerf17c3de2016-12-06 18:46:19 +0100987 result = _PyObject_CallNoArg(method);
Mark Dickinson6d02d9c2010-07-02 16:05:15 +0000988 Py_DECREF(method);
989 return result;
Guido van Rossum13e05de2007-08-23 22:56:55 +0000990}
991
Christian Heimes072c0f12008-01-03 23:01:04 +0000992FUNC2(copysign, copysign,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200993 "copysign($module, x, y, /)\n--\n\n"
994 "Return a float with the magnitude (absolute value) of x but the sign of y.\n\n"
995 "On platforms that support signed zeros, copysign(1.0, -0.0)\n"
996 "returns -1.0.\n")
Christian Heimes53876d92008-04-19 00:31:39 +0000997FUNC1(cos, cos, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200998 "cos($module, x, /)\n--\n\n"
999 "Return the cosine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001000FUNC1(cosh, cosh, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001001 "cosh($module, x, /)\n--\n\n"
1002 "Return the hyperbolic cosine of x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +00001003FUNC1A(erf, m_erf,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001004 "erf($module, x, /)\n--\n\n"
1005 "Error function at x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +00001006FUNC1A(erfc, m_erfc,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001007 "erfc($module, x, /)\n--\n\n"
1008 "Complementary error function at x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001009FUNC1(exp, exp, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001010 "exp($module, x, /)\n--\n\n"
1011 "Return e raised to the power of x.")
Mark Dickinson664b5112009-12-16 20:23:42 +00001012FUNC1(expm1, m_expm1, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001013 "expm1($module, x, /)\n--\n\n"
1014 "Return exp(x)-1.\n\n"
Mark Dickinson664b5112009-12-16 20:23:42 +00001015 "This function avoids the loss of precision involved in the direct "
1016 "evaluation of exp(x)-1 for small x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001017FUNC1(fabs, fabs, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001018 "fabs($module, x, /)\n--\n\n"
1019 "Return the absolute value of the float x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +00001020
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001021/*[clinic input]
1022math.floor
1023
1024 x as number: object
1025 /
1026
1027Return the floor of x as an Integral.
1028
1029This is the largest integer <= x.
1030[clinic start generated code]*/
1031
1032static PyObject *
1033math_floor(PyObject *module, PyObject *number)
1034/*[clinic end generated code: output=c6a65c4884884b8a input=63af6b5d7ebcc3d6]*/
1035{
Benjamin Petersonce798522012-01-22 11:24:29 -05001036 _Py_IDENTIFIER(__floor__);
Benjamin Petersonb0125892010-07-02 13:35:17 +00001037 PyObject *method, *result;
Guido van Rossum13e05de2007-08-23 22:56:55 +00001038
Benjamin Petersonce798522012-01-22 11:24:29 -05001039 method = _PyObject_LookupSpecial(number, &PyId___floor__);
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001040 if (method == NULL) {
1041 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 return math_1_to_int(number, floor, 0);
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001044 }
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001045 result = _PyObject_CallNoArg(method);
Benjamin Petersonb0125892010-07-02 13:35:17 +00001046 Py_DECREF(method);
1047 return result;
Guido van Rossum13e05de2007-08-23 22:56:55 +00001048}
1049
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001050FUNC1A(gamma, m_tgamma,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001051 "gamma($module, x, /)\n--\n\n"
1052 "Gamma function at x.")
Mark Dickinson05d2e082009-12-11 20:17:17 +00001053FUNC1A(lgamma, m_lgamma,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001054 "lgamma($module, x, /)\n--\n\n"
1055 "Natural logarithm of absolute value of Gamma function at x.")
Mark Dickinsonbe64d952010-07-07 16:21:29 +00001056FUNC1(log1p, m_log1p, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001057 "log1p($module, x, /)\n--\n\n"
1058 "Return the natural logarithm of 1+x (base e).\n\n"
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001059 "The result is computed in a way which is accurate for x near zero.")
Christian Heimes53876d92008-04-19 00:31:39 +00001060FUNC1(sin, sin, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001061 "sin($module, x, /)\n--\n\n"
1062 "Return the sine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001063FUNC1(sinh, sinh, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001064 "sinh($module, x, /)\n--\n\n"
1065 "Return the hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001066FUNC1(sqrt, sqrt, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001067 "sqrt($module, x, /)\n--\n\n"
1068 "Return the square root of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001069FUNC1(tan, tan, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001070 "tan($module, x, /)\n--\n\n"
1071 "Return the tangent of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001072FUNC1(tanh, tanh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001073 "tanh($module, x, /)\n--\n\n"
1074 "Return the hyperbolic tangent of x.")
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001075
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001076/* Precision summation function as msum() by Raymond Hettinger in
1077 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
1078 enhanced with the exact partials sum and roundoff from Mark
1079 Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
1080 See those links for more details, proofs and other references.
1081
1082 Note 1: IEEE 754R floating point semantics are assumed,
1083 but the current implementation does not re-establish special
1084 value semantics across iterations (i.e. handling -Inf + Inf).
1085
1086 Note 2: No provision is made for intermediate overflow handling;
Georg Brandlf78e02b2008-06-10 17:40:04 +00001087 therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001088 sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
1089 overflow of the first partial sum.
1090
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001091 Note 3: The intermediate values lo, yr, and hi are declared volatile so
1092 aggressive compilers won't algebraically reduce lo to always be exactly 0.0.
Georg Brandlf78e02b2008-06-10 17:40:04 +00001093 Also, the volatile declaration forces the values to be stored in memory as
1094 regular doubles instead of extended long precision (80-bit) values. This
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001095 prevents double rounding because any addition or subtraction of two doubles
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 can be resolved exactly into double-sized hi and lo values. As long as the
Georg Brandlf78e02b2008-06-10 17:40:04 +00001097 hi value gets forced into a double before yr and lo are computed, the extra
1098 bits in downstream extended precision operations (x87 for example) will be
1099 exactly zero and therefore can be losslessly stored back into a double,
1100 thereby preventing double rounding.
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001101
1102 Note 4: A similar implementation is in Modules/cmathmodule.c.
1103 Be sure to update both when making changes.
1104
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001105 Note 5: The signature of math.fsum() differs from builtins.sum()
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001106 because the start argument doesn't make sense in the context of
1107 accurate summation. Since the partials table is collapsed before
1108 returning a result, sum(seq2, start=sum(seq1)) may not equal the
1109 accurate result returned by sum(itertools.chain(seq1, seq2)).
1110*/
1111
1112#define NUM_PARTIALS 32 /* initial partials array size, on stack */
1113
1114/* Extend the partials array p[] by doubling its size. */
1115static int /* non-zero on error */
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001116_fsum_realloc(double **p_ptr, Py_ssize_t n,
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001117 double *ps, Py_ssize_t *m_ptr)
1118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 void *v = NULL;
1120 Py_ssize_t m = *m_ptr;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 m += m; /* double */
Victor Stinner049e5092014-08-17 22:20:00 +02001123 if (n < m && (size_t)m < ((size_t)PY_SSIZE_T_MAX / sizeof(double))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 double *p = *p_ptr;
1125 if (p == ps) {
1126 v = PyMem_Malloc(sizeof(double) * m);
1127 if (v != NULL)
1128 memcpy(v, ps, sizeof(double) * n);
1129 }
1130 else
1131 v = PyMem_Realloc(p, sizeof(double) * m);
1132 }
1133 if (v == NULL) { /* size overflow or no memory */
1134 PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
1135 return 1;
1136 }
1137 *p_ptr = (double*) v;
1138 *m_ptr = m;
1139 return 0;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001140}
1141
1142/* Full precision summation of a sequence of floats.
1143
1144 def msum(iterable):
1145 partials = [] # sorted, non-overlapping partial sums
1146 for x in iterable:
Mark Dickinsonfdb0acc2010-06-25 20:22:24 +00001147 i = 0
1148 for y in partials:
1149 if abs(x) < abs(y):
1150 x, y = y, x
1151 hi = x + y
1152 lo = y - (hi - x)
1153 if lo:
1154 partials[i] = lo
1155 i += 1
1156 x = hi
1157 partials[i:] = [x]
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001158 return sum_exact(partials)
1159
1160 Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
1161 are exactly equal to x+y. The inner loop applies hi/lo summation to each
1162 partial so that the list of partial sums remains exact.
1163
1164 Sum_exact() adds the partial sums exactly and correctly rounds the final
1165 result (using the round-half-to-even rule). The items in partials remain
1166 non-zero, non-special, non-overlapping and strictly increasing in
1167 magnitude, but possibly not all having the same sign.
1168
1169 Depends on IEEE 754 arithmetic guarantees and half-even rounding.
1170*/
1171
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001172/*[clinic input]
1173math.fsum
1174
1175 seq: object
1176 /
1177
1178Return an accurate floating point sum of values in the iterable seq.
1179
1180Assumes IEEE-754 floating point arithmetic.
1181[clinic start generated code]*/
1182
1183static PyObject *
1184math_fsum(PyObject *module, PyObject *seq)
1185/*[clinic end generated code: output=ba5c672b87fe34fc input=c51b7d8caf6f6e82]*/
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 PyObject *item, *iter, *sum = NULL;
1188 Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
1189 double x, y, t, ps[NUM_PARTIALS], *p = ps;
1190 double xsave, special_sum = 0.0, inf_sum = 0.0;
1191 volatile double hi, yr, lo;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 iter = PyObject_GetIter(seq);
1194 if (iter == NULL)
1195 return NULL;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 for(;;) { /* for x in iterable */
1200 assert(0 <= n && n <= m);
1201 assert((m == NUM_PARTIALS && p == ps) ||
1202 (m > NUM_PARTIALS && p != NULL));
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 item = PyIter_Next(iter);
1205 if (item == NULL) {
1206 if (PyErr_Occurred())
1207 goto _fsum_error;
1208 break;
1209 }
1210 x = PyFloat_AsDouble(item);
1211 Py_DECREF(item);
1212 if (PyErr_Occurred())
1213 goto _fsum_error;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 xsave = x;
1216 for (i = j = 0; j < n; j++) { /* for y in partials */
1217 y = p[j];
1218 if (fabs(x) < fabs(y)) {
1219 t = x; x = y; y = t;
1220 }
1221 hi = x + y;
1222 yr = hi - x;
1223 lo = y - yr;
1224 if (lo != 0.0)
1225 p[i++] = lo;
1226 x = hi;
1227 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 n = i; /* ps[i:] = [x] */
1230 if (x != 0.0) {
1231 if (! Py_IS_FINITE(x)) {
1232 /* a nonfinite x could arise either as
1233 a result of intermediate overflow, or
1234 as a result of a nan or inf in the
1235 summands */
1236 if (Py_IS_FINITE(xsave)) {
1237 PyErr_SetString(PyExc_OverflowError,
1238 "intermediate overflow in fsum");
1239 goto _fsum_error;
1240 }
1241 if (Py_IS_INFINITY(xsave))
1242 inf_sum += xsave;
1243 special_sum += xsave;
1244 /* reset partials */
1245 n = 0;
1246 }
1247 else if (n >= m && _fsum_realloc(&p, n, ps, &m))
1248 goto _fsum_error;
1249 else
1250 p[n++] = x;
1251 }
1252 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 if (special_sum != 0.0) {
1255 if (Py_IS_NAN(inf_sum))
1256 PyErr_SetString(PyExc_ValueError,
1257 "-inf + inf in fsum");
1258 else
1259 sum = PyFloat_FromDouble(special_sum);
1260 goto _fsum_error;
1261 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 hi = 0.0;
1264 if (n > 0) {
1265 hi = p[--n];
1266 /* sum_exact(ps, hi) from the top, stop when the sum becomes
1267 inexact. */
1268 while (n > 0) {
1269 x = hi;
1270 y = p[--n];
1271 assert(fabs(y) < fabs(x));
1272 hi = x + y;
1273 yr = hi - x;
1274 lo = y - yr;
1275 if (lo != 0.0)
1276 break;
1277 }
1278 /* Make half-even rounding work across multiple partials.
1279 Needed so that sum([1e-16, 1, 1e16]) will round-up the last
1280 digit to two instead of down to zero (the 1e-16 makes the 1
1281 slightly closer to two). With a potential 1 ULP rounding
1282 error fixed-up, math.fsum() can guarantee commutativity. */
1283 if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
1284 (lo > 0.0 && p[n-1] > 0.0))) {
1285 y = lo * 2.0;
1286 x = hi + y;
1287 yr = x - hi;
1288 if (y == yr)
1289 hi = x;
1290 }
1291 }
1292 sum = PyFloat_FromDouble(hi);
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001293
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001294_fsum_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 PyFPE_END_PROTECT(hi)
1296 Py_DECREF(iter);
1297 if (p != ps)
1298 PyMem_Free(p);
1299 return sum;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001300}
1301
1302#undef NUM_PARTIALS
1303
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001304
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001305/* Return the smallest integer k such that n < 2**k, or 0 if n == 0.
1306 * Equivalent to floor(lg(x))+1. Also equivalent to: bitwidth_of_type -
1307 * count_leading_zero_bits(x)
1308 */
1309
1310/* XXX: This routine does more or less the same thing as
1311 * bits_in_digit() in Objects/longobject.c. Someday it would be nice to
1312 * consolidate them. On BSD, there's a library function called fls()
1313 * that we could use, and GCC provides __builtin_clz().
1314 */
1315
1316static unsigned long
1317bit_length(unsigned long n)
1318{
1319 unsigned long len = 0;
1320 while (n != 0) {
1321 ++len;
1322 n >>= 1;
1323 }
1324 return len;
1325}
1326
1327static unsigned long
1328count_set_bits(unsigned long n)
1329{
1330 unsigned long count = 0;
1331 while (n != 0) {
1332 ++count;
1333 n &= n - 1; /* clear least significant bit */
1334 }
1335 return count;
1336}
1337
1338/* Divide-and-conquer factorial algorithm
1339 *
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07001340 * Based on the formula and pseudo-code provided at:
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001341 * http://www.luschny.de/math/factorial/binarysplitfact.html
1342 *
1343 * Faster algorithms exist, but they're more complicated and depend on
Ezio Melotti9527afd2010-07-08 15:03:02 +00001344 * a fast prime factorization algorithm.
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001345 *
1346 * Notes on the algorithm
1347 * ----------------------
1348 *
1349 * factorial(n) is written in the form 2**k * m, with m odd. k and m are
1350 * computed separately, and then combined using a left shift.
1351 *
1352 * The function factorial_odd_part computes the odd part m (i.e., the greatest
1353 * odd divisor) of factorial(n), using the formula:
1354 *
1355 * factorial_odd_part(n) =
1356 *
1357 * product_{i >= 0} product_{0 < j <= n / 2**i, j odd} j
1358 *
1359 * Example: factorial_odd_part(20) =
1360 *
1361 * (1) *
1362 * (1) *
1363 * (1 * 3 * 5) *
1364 * (1 * 3 * 5 * 7 * 9)
1365 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1366 *
1367 * Here i goes from large to small: the first term corresponds to i=4 (any
1368 * larger i gives an empty product), and the last term corresponds to i=0.
1369 * Each term can be computed from the last by multiplying by the extra odd
1370 * numbers required: e.g., to get from the penultimate term to the last one,
1371 * we multiply by (11 * 13 * 15 * 17 * 19).
1372 *
1373 * To see a hint of why this formula works, here are the same numbers as above
1374 * but with the even parts (i.e., the appropriate powers of 2) included. For
1375 * each subterm in the product for i, we multiply that subterm by 2**i:
1376 *
1377 * factorial(20) =
1378 *
1379 * (16) *
1380 * (8) *
1381 * (4 * 12 * 20) *
1382 * (2 * 6 * 10 * 14 * 18) *
1383 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1384 *
1385 * The factorial_partial_product function computes the product of all odd j in
1386 * range(start, stop) for given start and stop. It's used to compute the
1387 * partial products like (11 * 13 * 15 * 17 * 19) in the example above. It
1388 * operates recursively, repeatedly splitting the range into two roughly equal
1389 * pieces until the subranges are small enough to be computed using only C
1390 * integer arithmetic.
1391 *
1392 * The two-valuation k (i.e., the exponent of the largest power of 2 dividing
1393 * the factorial) is computed independently in the main math_factorial
1394 * function. By standard results, its value is:
1395 *
1396 * two_valuation = n//2 + n//4 + n//8 + ....
1397 *
1398 * It can be shown (e.g., by complete induction on n) that two_valuation is
1399 * equal to n - count_set_bits(n), where count_set_bits(n) gives the number of
1400 * '1'-bits in the binary expansion of n.
1401 */
1402
1403/* factorial_partial_product: Compute product(range(start, stop, 2)) using
1404 * divide and conquer. Assumes start and stop are odd and stop > start.
1405 * max_bits must be >= bit_length(stop - 2). */
1406
1407static PyObject *
1408factorial_partial_product(unsigned long start, unsigned long stop,
1409 unsigned long max_bits)
1410{
1411 unsigned long midpoint, num_operands;
1412 PyObject *left = NULL, *right = NULL, *result = NULL;
1413
1414 /* If the return value will fit an unsigned long, then we can
1415 * multiply in a tight, fast loop where each multiply is O(1).
1416 * Compute an upper bound on the number of bits required to store
1417 * the answer.
1418 *
1419 * Storing some integer z requires floor(lg(z))+1 bits, which is
1420 * conveniently the value returned by bit_length(z). The
1421 * product x*y will require at most
1422 * bit_length(x) + bit_length(y) bits to store, based
1423 * on the idea that lg product = lg x + lg y.
1424 *
1425 * We know that stop - 2 is the largest number to be multiplied. From
1426 * there, we have: bit_length(answer) <= num_operands *
1427 * bit_length(stop - 2)
1428 */
1429
1430 num_operands = (stop - start) / 2;
1431 /* The "num_operands <= 8 * SIZEOF_LONG" check guards against the
1432 * unlikely case of an overflow in num_operands * max_bits. */
1433 if (num_operands <= 8 * SIZEOF_LONG &&
1434 num_operands * max_bits <= 8 * SIZEOF_LONG) {
1435 unsigned long j, total;
1436 for (total = start, j = start + 2; j < stop; j += 2)
1437 total *= j;
1438 return PyLong_FromUnsignedLong(total);
1439 }
1440
1441 /* find midpoint of range(start, stop), rounded up to next odd number. */
1442 midpoint = (start + num_operands) | 1;
1443 left = factorial_partial_product(start, midpoint,
1444 bit_length(midpoint - 2));
1445 if (left == NULL)
1446 goto error;
1447 right = factorial_partial_product(midpoint, stop, max_bits);
1448 if (right == NULL)
1449 goto error;
1450 result = PyNumber_Multiply(left, right);
1451
1452 error:
1453 Py_XDECREF(left);
1454 Py_XDECREF(right);
1455 return result;
1456}
1457
1458/* factorial_odd_part: compute the odd part of factorial(n). */
1459
1460static PyObject *
1461factorial_odd_part(unsigned long n)
1462{
1463 long i;
1464 unsigned long v, lower, upper;
1465 PyObject *partial, *tmp, *inner, *outer;
1466
1467 inner = PyLong_FromLong(1);
1468 if (inner == NULL)
1469 return NULL;
1470 outer = inner;
1471 Py_INCREF(outer);
1472
1473 upper = 3;
1474 for (i = bit_length(n) - 2; i >= 0; i--) {
1475 v = n >> i;
1476 if (v <= 2)
1477 continue;
1478 lower = upper;
1479 /* (v + 1) | 1 = least odd integer strictly larger than n / 2**i */
1480 upper = (v + 1) | 1;
1481 /* Here inner is the product of all odd integers j in the range (0,
1482 n/2**(i+1)]. The factorial_partial_product call below gives the
1483 product of all odd integers j in the range (n/2**(i+1), n/2**i]. */
1484 partial = factorial_partial_product(lower, upper, bit_length(upper-2));
1485 /* inner *= partial */
1486 if (partial == NULL)
1487 goto error;
1488 tmp = PyNumber_Multiply(inner, partial);
1489 Py_DECREF(partial);
1490 if (tmp == NULL)
1491 goto error;
1492 Py_DECREF(inner);
1493 inner = tmp;
1494 /* Now inner is the product of all odd integers j in the range (0,
1495 n/2**i], giving the inner product in the formula above. */
1496
1497 /* outer *= inner; */
1498 tmp = PyNumber_Multiply(outer, inner);
1499 if (tmp == NULL)
1500 goto error;
1501 Py_DECREF(outer);
1502 outer = tmp;
1503 }
Mark Dickinson76464492012-10-25 10:46:28 +01001504 Py_DECREF(inner);
1505 return outer;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001506
1507 error:
1508 Py_DECREF(outer);
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001509 Py_DECREF(inner);
Mark Dickinson76464492012-10-25 10:46:28 +01001510 return NULL;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001511}
1512
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001513
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001514/* Lookup table for small factorial values */
1515
1516static const unsigned long SmallFactorials[] = {
1517 1, 1, 2, 6, 24, 120, 720, 5040, 40320,
1518 362880, 3628800, 39916800, 479001600,
1519#if SIZEOF_LONG >= 8
1520 6227020800, 87178291200, 1307674368000,
1521 20922789888000, 355687428096000, 6402373705728000,
1522 121645100408832000, 2432902008176640000
1523#endif
1524};
1525
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001526/*[clinic input]
1527math.factorial
1528
1529 x as arg: object
1530 /
1531
1532Find x!.
1533
1534Raise a ValueError if x is negative or non-integral.
1535[clinic start generated code]*/
1536
Barry Warsaw8b43b191996-12-09 22:32:36 +00001537static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001538math_factorial(PyObject *module, PyObject *arg)
1539/*[clinic end generated code: output=6686f26fae00e9ca input=6d1c8105c0d91fb4]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001540{
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001541 long x;
Mark Dickinson5990d282014-04-10 09:29:39 -04001542 int overflow;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001543 PyObject *result, *odd_part, *two_valuation;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 if (PyFloat_Check(arg)) {
1546 PyObject *lx;
1547 double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
1548 if (!(Py_IS_FINITE(dx) && dx == floor(dx))) {
1549 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001550 "factorial() only accepts integral values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 return NULL;
1552 }
1553 lx = PyLong_FromDouble(dx);
1554 if (lx == NULL)
1555 return NULL;
Mark Dickinson5990d282014-04-10 09:29:39 -04001556 x = PyLong_AsLongAndOverflow(lx, &overflow);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 Py_DECREF(lx);
1558 }
1559 else
Mark Dickinson5990d282014-04-10 09:29:39 -04001560 x = PyLong_AsLongAndOverflow(arg, &overflow);
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001561
Mark Dickinson5990d282014-04-10 09:29:39 -04001562 if (x == -1 && PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 return NULL;
Mark Dickinson5990d282014-04-10 09:29:39 -04001564 }
1565 else if (overflow == 1) {
1566 PyErr_Format(PyExc_OverflowError,
1567 "factorial() argument should not exceed %ld",
1568 LONG_MAX);
1569 return NULL;
1570 }
1571 else if (overflow == -1 || x < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001573 "factorial() not defined for negative values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 return NULL;
1575 }
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001576
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001577 /* use lookup table if x is small */
Victor Stinner63941882011-09-29 00:42:28 +02001578 if (x < (long)Py_ARRAY_LENGTH(SmallFactorials))
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001579 return PyLong_FromUnsignedLong(SmallFactorials[x]);
1580
1581 /* else express in the form odd_part * 2**two_valuation, and compute as
1582 odd_part << two_valuation. */
1583 odd_part = factorial_odd_part(x);
1584 if (odd_part == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 return NULL;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001586 two_valuation = PyLong_FromLong(x - count_set_bits(x));
1587 if (two_valuation == NULL) {
1588 Py_DECREF(odd_part);
1589 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 }
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001591 result = PyNumber_Lshift(odd_part, two_valuation);
1592 Py_DECREF(two_valuation);
1593 Py_DECREF(odd_part);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 return result;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001595}
1596
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001597
1598/*[clinic input]
1599math.trunc
1600
1601 x: object
1602 /
1603
1604Truncates the Real x to the nearest Integral toward 0.
1605
1606Uses the __trunc__ magic method.
1607[clinic start generated code]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001608
1609static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001610math_trunc(PyObject *module, PyObject *x)
1611/*[clinic end generated code: output=34b9697b707e1031 input=2168b34e0a09134d]*/
Christian Heimes400adb02008-02-01 08:12:03 +00001612{
Benjamin Petersonce798522012-01-22 11:24:29 -05001613 _Py_IDENTIFIER(__trunc__);
Benjamin Petersonb0125892010-07-02 13:35:17 +00001614 PyObject *trunc, *result;
Christian Heimes400adb02008-02-01 08:12:03 +00001615
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001616 if (Py_TYPE(x)->tp_dict == NULL) {
1617 if (PyType_Ready(Py_TYPE(x)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 return NULL;
1619 }
Christian Heimes400adb02008-02-01 08:12:03 +00001620
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001621 trunc = _PyObject_LookupSpecial(x, &PyId___trunc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 if (trunc == NULL) {
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001623 if (!PyErr_Occurred())
1624 PyErr_Format(PyExc_TypeError,
1625 "type %.100s doesn't define __trunc__ method",
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001626 Py_TYPE(x)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 return NULL;
1628 }
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001629 result = _PyObject_CallNoArg(trunc);
Benjamin Petersonb0125892010-07-02 13:35:17 +00001630 Py_DECREF(trunc);
1631 return result;
Christian Heimes400adb02008-02-01 08:12:03 +00001632}
1633
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001634
1635/*[clinic input]
1636math.frexp
1637
1638 x: double
1639 /
1640
1641Return the mantissa and exponent of x, as pair (m, e).
1642
1643m is a float and e is an int, such that x = m * 2.**e.
1644If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.
1645[clinic start generated code]*/
Christian Heimes400adb02008-02-01 08:12:03 +00001646
1647static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001648math_frexp_impl(PyObject *module, double x)
1649/*[clinic end generated code: output=03e30d252a15ad4a input=96251c9e208bc6e9]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00001650{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 /* deal with special cases directly, to sidestep platform
1653 differences */
1654 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
1655 i = 0;
1656 }
1657 else {
1658 PyFPE_START_PROTECT("in math_frexp", return 0);
1659 x = frexp(x, &i);
1660 PyFPE_END_PROTECT(x);
1661 }
1662 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001663}
1664
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001665
1666/*[clinic input]
1667math.ldexp
1668
1669 x: double
1670 i: object
1671 /
1672
1673Return x * (2**i).
1674
1675This is essentially the inverse of frexp().
1676[clinic start generated code]*/
Guido van Rossumc6e22901998-12-04 19:26:43 +00001677
Barry Warsaw8b43b191996-12-09 22:32:36 +00001678static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001679math_ldexp_impl(PyObject *module, double x, PyObject *i)
1680/*[clinic end generated code: output=b6892f3c2df9cc6a input=17d5970c1a40a8c1]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00001681{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001682 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 long exp;
1684 int overflow;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001685
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001686 if (PyLong_Check(i)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 /* on overflow, replace exponent with either LONG_MAX
1688 or LONG_MIN, depending on the sign. */
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001689 exp = PyLong_AsLongAndOverflow(i, &overflow);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 if (exp == -1 && PyErr_Occurred())
1691 return NULL;
1692 if (overflow)
1693 exp = overflow < 0 ? LONG_MIN : LONG_MAX;
1694 }
1695 else {
1696 PyErr_SetString(PyExc_TypeError,
Serhiy Storchaka95949422013-08-27 19:40:23 +03001697 "Expected an int as second argument to ldexp.");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 return NULL;
1699 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 if (x == 0. || !Py_IS_FINITE(x)) {
1702 /* NaNs, zeros and infinities are returned unchanged */
1703 r = x;
1704 errno = 0;
1705 } else if (exp > INT_MAX) {
1706 /* overflow */
1707 r = copysign(Py_HUGE_VAL, x);
1708 errno = ERANGE;
1709 } else if (exp < INT_MIN) {
1710 /* underflow to +-0 */
1711 r = copysign(0., x);
1712 errno = 0;
1713 } else {
1714 errno = 0;
1715 PyFPE_START_PROTECT("in math_ldexp", return 0);
1716 r = ldexp(x, (int)exp);
1717 PyFPE_END_PROTECT(r);
1718 if (Py_IS_INFINITY(r))
1719 errno = ERANGE;
1720 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 if (errno && is_error(r))
1723 return NULL;
1724 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001725}
1726
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001727
1728/*[clinic input]
1729math.modf
1730
1731 x: double
1732 /
1733
1734Return the fractional and integer parts of x.
1735
1736Both results carry the sign of x and are floats.
1737[clinic start generated code]*/
Guido van Rossumc6e22901998-12-04 19:26:43 +00001738
Barry Warsaw8b43b191996-12-09 22:32:36 +00001739static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001740math_modf_impl(PyObject *module, double x)
1741/*[clinic end generated code: output=90cee0260014c3c0 input=b4cfb6786afd9035]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00001742{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001743 double y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 /* some platforms don't do the right thing for NaNs and
1745 infinities, so we take care of special cases directly. */
1746 if (!Py_IS_FINITE(x)) {
1747 if (Py_IS_INFINITY(x))
1748 return Py_BuildValue("(dd)", copysign(0., x), x);
1749 else if (Py_IS_NAN(x))
1750 return Py_BuildValue("(dd)", x, x);
1751 }
Christian Heimesa342c012008-04-20 21:01:16 +00001752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 errno = 0;
1754 PyFPE_START_PROTECT("in math_modf", return 0);
1755 x = modf(x, &y);
1756 PyFPE_END_PROTECT(x);
1757 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001758}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001759
Guido van Rossumc6e22901998-12-04 19:26:43 +00001760
Serhiy Storchaka95949422013-08-27 19:40:23 +03001761/* A decent logarithm is easy to compute even for huge ints, but libm can't
Tim Peters78526162001-09-05 00:53:45 +00001762 do that by itself -- loghelper can. func is log or log10, and name is
Serhiy Storchaka95949422013-08-27 19:40:23 +03001763 "log" or "log10". Note that overflow of the result isn't possible: an int
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00001764 can contain no more than INT_MAX * SHIFT bits, so has value certainly less
1765 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 +00001766 small enough to fit in an IEEE single. log and log10 are even smaller.
Serhiy Storchaka95949422013-08-27 19:40:23 +03001767 However, intermediate overflow is possible for an int if the number of bits
1768 in that int is larger than PY_SSIZE_T_MAX. */
Tim Peters78526162001-09-05 00:53:45 +00001769
1770static PyObject*
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001771loghelper(PyObject* arg, double (*func)(double), const char *funcname)
Tim Peters78526162001-09-05 00:53:45 +00001772{
Serhiy Storchaka95949422013-08-27 19:40:23 +03001773 /* If it is int, do it ourselves. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 if (PyLong_Check(arg)) {
Mark Dickinsonc6037172010-09-29 19:06:36 +00001775 double x, result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 Py_ssize_t e;
Mark Dickinsonc6037172010-09-29 19:06:36 +00001777
1778 /* Negative or zero inputs give a ValueError. */
1779 if (Py_SIZE(arg) <= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 PyErr_SetString(PyExc_ValueError,
1781 "math domain error");
1782 return NULL;
1783 }
Mark Dickinsonfa41e602010-09-28 07:22:27 +00001784
Mark Dickinsonc6037172010-09-29 19:06:36 +00001785 x = PyLong_AsDouble(arg);
1786 if (x == -1.0 && PyErr_Occurred()) {
1787 if (!PyErr_ExceptionMatches(PyExc_OverflowError))
1788 return NULL;
1789 /* Here the conversion to double overflowed, but it's possible
1790 to compute the log anyway. Clear the exception and continue. */
1791 PyErr_Clear();
1792 x = _PyLong_Frexp((PyLongObject *)arg, &e);
1793 if (x == -1.0 && PyErr_Occurred())
1794 return NULL;
1795 /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */
1796 result = func(x) + func(2.0) * e;
1797 }
1798 else
1799 /* Successfully converted x to a double. */
1800 result = func(x);
1801 return PyFloat_FromDouble(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 }
Tim Peters78526162001-09-05 00:53:45 +00001803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 /* Else let libm handle it by itself. */
1805 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +00001806}
1807
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001808
1809/*[clinic input]
1810math.log
1811
1812 x: object
1813 [
1814 base: object(c_default="NULL") = math.e
1815 ]
1816 /
1817
1818Return the logarithm of x to the given base.
1819
1820If the base not specified, returns the natural logarithm (base e) of x.
1821[clinic start generated code]*/
1822
Tim Peters78526162001-09-05 00:53:45 +00001823static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001824math_log_impl(PyObject *module, PyObject *x, int group_right_1,
1825 PyObject *base)
1826/*[clinic end generated code: output=7b5a39e526b73fc9 input=0f62d5726cbfebbd]*/
Tim Peters78526162001-09-05 00:53:45 +00001827{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 PyObject *num, *den;
1829 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001830
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001831 num = loghelper(x, m_log, "log");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 if (num == NULL || base == NULL)
1833 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 den = loghelper(base, m_log, "log");
1836 if (den == NULL) {
1837 Py_DECREF(num);
1838 return NULL;
1839 }
Raymond Hettinger866964c2002-12-14 19:51:34 +00001840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 ans = PyNumber_TrueDivide(num, den);
1842 Py_DECREF(num);
1843 Py_DECREF(den);
1844 return ans;
Tim Peters78526162001-09-05 00:53:45 +00001845}
1846
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001847
1848/*[clinic input]
1849math.log2
1850
1851 x: object
1852 /
1853
1854Return the base 2 logarithm of x.
1855[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00001856
1857static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001858math_log2(PyObject *module, PyObject *x)
1859/*[clinic end generated code: output=5425899a4d5d6acb input=08321262bae4f39b]*/
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001860{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001861 return loghelper(x, m_log2, "log2");
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001862}
1863
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001864
1865/*[clinic input]
1866math.log10
1867
1868 x: object
1869 /
1870
1871Return the base 10 logarithm of x.
1872[clinic start generated code]*/
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001873
1874static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001875math_log10(PyObject *module, PyObject *x)
1876/*[clinic end generated code: output=be72a64617df9c6f input=b2469d02c6469e53]*/
Tim Peters78526162001-09-05 00:53:45 +00001877{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001878 return loghelper(x, m_log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +00001879}
1880
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001881
1882/*[clinic input]
1883math.fmod
1884
1885 x: double
1886 y: double
1887 /
1888
1889Return fmod(x, y), according to platform C.
1890
1891x % y may differ.
1892[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00001893
Christian Heimes53876d92008-04-19 00:31:39 +00001894static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001895math_fmod_impl(PyObject *module, double x, double y)
1896/*[clinic end generated code: output=7559d794343a27b5 input=4f84caa8cfc26a03]*/
Christian Heimes53876d92008-04-19 00:31:39 +00001897{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001898 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 /* fmod(x, +/-Inf) returns x for finite x. */
1900 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
1901 return PyFloat_FromDouble(x);
1902 errno = 0;
1903 PyFPE_START_PROTECT("in math_fmod", return 0);
1904 r = fmod(x, y);
1905 PyFPE_END_PROTECT(r);
1906 if (Py_IS_NAN(r)) {
1907 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1908 errno = EDOM;
1909 else
1910 errno = 0;
1911 }
1912 if (errno && is_error(r))
1913 return NULL;
1914 else
1915 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00001916}
1917
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001918
1919/*[clinic input]
1920math.hypot
1921
1922 x: double
1923 y: double
1924 /
1925
1926Return the Euclidean distance, sqrt(x*x + y*y).
1927[clinic start generated code]*/
Christian Heimes53876d92008-04-19 00:31:39 +00001928
1929static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001930math_hypot_impl(PyObject *module, double x, double y)
1931/*[clinic end generated code: output=b7686e5be468ef87 input=7f8eea70406474aa]*/
Christian Heimes53876d92008-04-19 00:31:39 +00001932{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001933 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */
1935 if (Py_IS_INFINITY(x))
1936 return PyFloat_FromDouble(fabs(x));
1937 if (Py_IS_INFINITY(y))
1938 return PyFloat_FromDouble(fabs(y));
1939 errno = 0;
1940 PyFPE_START_PROTECT("in math_hypot", return 0);
1941 r = hypot(x, y);
1942 PyFPE_END_PROTECT(r);
1943 if (Py_IS_NAN(r)) {
1944 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1945 errno = EDOM;
1946 else
1947 errno = 0;
1948 }
1949 else if (Py_IS_INFINITY(r)) {
1950 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
1951 errno = ERANGE;
1952 else
1953 errno = 0;
1954 }
1955 if (errno && is_error(r))
1956 return NULL;
1957 else
1958 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00001959}
1960
Christian Heimes53876d92008-04-19 00:31:39 +00001961
1962/* pow can't use math_2, but needs its own wrapper: the problem is
1963 that an infinite result can arise either as a result of overflow
1964 (in which case OverflowError should be raised) or as a result of
1965 e.g. 0.**-5. (for which ValueError needs to be raised.)
1966*/
1967
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001968/*[clinic input]
1969math.pow
Christian Heimes53876d92008-04-19 00:31:39 +00001970
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001971 x: double
1972 y: double
1973 /
1974
1975Return x**y (x to the power of y).
1976[clinic start generated code]*/
1977
1978static PyObject *
1979math_pow_impl(PyObject *module, double x, double y)
1980/*[clinic end generated code: output=fff93e65abccd6b0 input=c26f1f6075088bfd]*/
1981{
1982 double r;
1983 int odd_y;
Christian Heimesa342c012008-04-20 21:01:16 +00001984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 /* deal directly with IEEE specials, to cope with problems on various
1986 platforms whose semantics don't exactly match C99 */
1987 r = 0.; /* silence compiler warning */
1988 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
1989 errno = 0;
1990 if (Py_IS_NAN(x))
1991 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
1992 else if (Py_IS_NAN(y))
1993 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
1994 else if (Py_IS_INFINITY(x)) {
1995 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
1996 if (y > 0.)
1997 r = odd_y ? x : fabs(x);
1998 else if (y == 0.)
1999 r = 1.;
2000 else /* y < 0. */
2001 r = odd_y ? copysign(0., x) : 0.;
2002 }
2003 else if (Py_IS_INFINITY(y)) {
2004 if (fabs(x) == 1.0)
2005 r = 1.;
2006 else if (y > 0. && fabs(x) > 1.0)
2007 r = y;
2008 else if (y < 0. && fabs(x) < 1.0) {
2009 r = -y; /* result is +inf */
2010 if (x == 0.) /* 0**-inf: divide-by-zero */
2011 errno = EDOM;
2012 }
2013 else
2014 r = 0.;
2015 }
2016 }
2017 else {
2018 /* let libm handle finite**finite */
2019 errno = 0;
2020 PyFPE_START_PROTECT("in math_pow", return 0);
2021 r = pow(x, y);
2022 PyFPE_END_PROTECT(r);
2023 /* a NaN result should arise only from (-ve)**(finite
2024 non-integer); in this case we want to raise ValueError. */
2025 if (!Py_IS_FINITE(r)) {
2026 if (Py_IS_NAN(r)) {
2027 errno = EDOM;
2028 }
2029 /*
2030 an infinite result here arises either from:
2031 (A) (+/-0.)**negative (-> divide-by-zero)
2032 (B) overflow of x**y with x and y finite
2033 */
2034 else if (Py_IS_INFINITY(r)) {
2035 if (x == 0.)
2036 errno = EDOM;
2037 else
2038 errno = ERANGE;
2039 }
2040 }
2041 }
Christian Heimes53876d92008-04-19 00:31:39 +00002042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 if (errno && is_error(r))
2044 return NULL;
2045 else
2046 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00002047}
2048
Christian Heimes53876d92008-04-19 00:31:39 +00002049
Christian Heimes072c0f12008-01-03 23:01:04 +00002050static const double degToRad = Py_MATH_PI / 180.0;
2051static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002052
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002053/*[clinic input]
2054math.degrees
2055
2056 x: double
2057 /
2058
2059Convert angle x from radians to degrees.
2060[clinic start generated code]*/
2061
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002062static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002063math_degrees_impl(PyObject *module, double x)
2064/*[clinic end generated code: output=7fea78b294acd12f input=81e016555d6e3660]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002065{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002067}
2068
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002069
2070/*[clinic input]
2071math.radians
2072
2073 x: double
2074 /
2075
2076Convert angle x from degrees to radians.
2077[clinic start generated code]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002078
2079static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002080math_radians_impl(PyObject *module, double x)
2081/*[clinic end generated code: output=34daa47caf9b1590 input=91626fc489fe3d63]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002082{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 return PyFloat_FromDouble(x * degToRad);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002084}
2085
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002086
2087/*[clinic input]
2088math.isfinite
2089
2090 x: double
2091 /
2092
2093Return True if x is neither an infinity nor a NaN, and False otherwise.
2094[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002095
Christian Heimes072c0f12008-01-03 23:01:04 +00002096static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002097math_isfinite_impl(PyObject *module, double x)
2098/*[clinic end generated code: output=8ba1f396440c9901 input=46967d254812e54a]*/
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002099{
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002100 return PyBool_FromLong((long)Py_IS_FINITE(x));
2101}
2102
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002103
2104/*[clinic input]
2105math.isnan
2106
2107 x: double
2108 /
2109
2110Return True if x is a NaN (not a number), and False otherwise.
2111[clinic start generated code]*/
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002112
2113static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002114math_isnan_impl(PyObject *module, double x)
2115/*[clinic end generated code: output=f537b4d6df878c3e input=935891e66083f46a]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002116{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00002118}
2119
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002120
2121/*[clinic input]
2122math.isinf
2123
2124 x: double
2125 /
2126
2127Return True if x is a positive or negative infinity, and False otherwise.
2128[clinic start generated code]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002129
2130static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002131math_isinf_impl(PyObject *module, double x)
2132/*[clinic end generated code: output=9f00cbec4de7b06b input=32630e4212cf961f]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00002135}
2136
Christian Heimes072c0f12008-01-03 23:01:04 +00002137
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002138/*[clinic input]
2139math.isclose -> bool
2140
2141 a: double
2142 b: double
2143 *
2144 rel_tol: double = 1e-09
2145 maximum difference for being considered "close", relative to the
2146 magnitude of the input values
2147 abs_tol: double = 0.0
2148 maximum difference for being considered "close", regardless of the
2149 magnitude of the input values
2150
2151Determine whether two floating point numbers are close in value.
2152
2153Return True if a is close in value to b, and False otherwise.
2154
2155For the values to be considered close, the difference between them
2156must be smaller than at least one of the tolerances.
2157
2158-inf, inf and NaN behave similarly to the IEEE 754 Standard. That
2159is, NaN is not close to anything, even itself. inf and -inf are
2160only close to themselves.
2161[clinic start generated code]*/
2162
2163static int
2164math_isclose_impl(PyObject *module, double a, double b, double rel_tol,
2165 double abs_tol)
2166/*[clinic end generated code: output=b73070207511952d input=f28671871ea5bfba]*/
Tal Einatd5519ed2015-05-31 22:05:00 +03002167{
Tal Einatd5519ed2015-05-31 22:05:00 +03002168 double diff = 0.0;
Tal Einatd5519ed2015-05-31 22:05:00 +03002169
2170 /* sanity check on the inputs */
2171 if (rel_tol < 0.0 || abs_tol < 0.0 ) {
2172 PyErr_SetString(PyExc_ValueError,
2173 "tolerances must be non-negative");
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002174 return -1;
Tal Einatd5519ed2015-05-31 22:05:00 +03002175 }
2176
2177 if ( a == b ) {
2178 /* short circuit exact equality -- needed to catch two infinities of
2179 the same sign. And perhaps speeds things up a bit sometimes.
2180 */
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002181 return 1;
Tal Einatd5519ed2015-05-31 22:05:00 +03002182 }
2183
2184 /* This catches the case of two infinities of opposite sign, or
2185 one infinity and one finite number. Two infinities of opposite
2186 sign would otherwise have an infinite relative tolerance.
2187 Two infinities of the same sign are caught by the equality check
2188 above.
2189 */
2190
2191 if (Py_IS_INFINITY(a) || Py_IS_INFINITY(b)) {
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002192 return 0;
Tal Einatd5519ed2015-05-31 22:05:00 +03002193 }
2194
2195 /* now do the regular computation
2196 this is essentially the "weak" test from the Boost library
2197 */
2198
2199 diff = fabs(b - a);
2200
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002201 return (((diff <= fabs(rel_tol * b)) ||
2202 (diff <= fabs(rel_tol * a))) ||
2203 (diff <= abs_tol));
Tal Einatd5519ed2015-05-31 22:05:00 +03002204}
2205
Tal Einatd5519ed2015-05-31 22:05:00 +03002206
Barry Warsaw8b43b191996-12-09 22:32:36 +00002207static PyMethodDef math_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002208 {"acos", math_acos, METH_O, math_acos_doc},
2209 {"acosh", math_acosh, METH_O, math_acosh_doc},
2210 {"asin", math_asin, METH_O, math_asin_doc},
2211 {"asinh", math_asinh, METH_O, math_asinh_doc},
2212 {"atan", math_atan, METH_O, math_atan_doc},
2213 {"atan2", math_atan2, METH_VARARGS, math_atan2_doc},
2214 {"atanh", math_atanh, METH_O, math_atanh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002215 MATH_CEIL_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 {"copysign", math_copysign, METH_VARARGS, math_copysign_doc},
2217 {"cos", math_cos, METH_O, math_cos_doc},
2218 {"cosh", math_cosh, METH_O, math_cosh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002219 MATH_DEGREES_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 {"erf", math_erf, METH_O, math_erf_doc},
2221 {"erfc", math_erfc, METH_O, math_erfc_doc},
2222 {"exp", math_exp, METH_O, math_exp_doc},
2223 {"expm1", math_expm1, METH_O, math_expm1_doc},
2224 {"fabs", math_fabs, METH_O, math_fabs_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002225 MATH_FACTORIAL_METHODDEF
2226 MATH_FLOOR_METHODDEF
2227 MATH_FMOD_METHODDEF
2228 MATH_FREXP_METHODDEF
2229 MATH_FSUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 {"gamma", math_gamma, METH_O, math_gamma_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002231 MATH_GCD_METHODDEF
2232 MATH_HYPOT_METHODDEF
2233 MATH_ISCLOSE_METHODDEF
2234 MATH_ISFINITE_METHODDEF
2235 MATH_ISINF_METHODDEF
2236 MATH_ISNAN_METHODDEF
2237 MATH_LDEXP_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002239 MATH_LOG_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 {"log1p", math_log1p, METH_O, math_log1p_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002241 MATH_LOG10_METHODDEF
2242 MATH_LOG2_METHODDEF
2243 MATH_MODF_METHODDEF
2244 MATH_POW_METHODDEF
2245 MATH_RADIANS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 {"sin", math_sin, METH_O, math_sin_doc},
2247 {"sinh", math_sinh, METH_O, math_sinh_doc},
2248 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
2249 {"tan", math_tan, METH_O, math_tan_doc},
2250 {"tanh", math_tanh, METH_O, math_tanh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002251 MATH_TRUNC_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002253};
2254
Guido van Rossumc6e22901998-12-04 19:26:43 +00002255
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002256PyDoc_STRVAR(module_doc,
Tim Peters63c94532001-09-04 23:17:42 +00002257"This module is always available. It provides access to the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002258"mathematical functions defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00002259
Martin v. Löwis1a214512008-06-11 05:26:20 +00002260
2261static struct PyModuleDef mathmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 PyModuleDef_HEAD_INIT,
2263 "math",
2264 module_doc,
2265 -1,
2266 math_methods,
2267 NULL,
2268 NULL,
2269 NULL,
2270 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002271};
2272
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002273PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002274PyInit_math(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 PyObject *m;
Tim Petersfe71f812001-08-07 22:10:00 +00002277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 m = PyModule_Create(&mathmodule);
2279 if (m == NULL)
2280 goto finally;
Barry Warsawfc93f751996-12-17 00:47:03 +00002281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
2283 PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
Guido van Rossum0a891d72016-08-15 09:12:52 -07002284 PyModule_AddObject(m, "tau", PyFloat_FromDouble(Py_MATH_TAU)); /* 2pi */
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +00002285 PyModule_AddObject(m, "inf", PyFloat_FromDouble(m_inf()));
2286#if !defined(PY_NO_SHORT_FLOAT_REPR) || defined(Py_NAN)
2287 PyModule_AddObject(m, "nan", PyFloat_FromDouble(m_nan()));
2288#endif
Barry Warsawfc93f751996-12-17 00:47:03 +00002289
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +00002290 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002292}