blob: bfc028edddfa83c233ed68175cabe72505f9062d [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
Serhiy Storchaka97553fd2017-03-11 23:37:16 +020077#ifndef __APPLE__
78# ifdef HAVE_TGAMMA
79# define USE_TGAMMA
80# endif
81# ifdef HAVE_LGAMMA
82# define USE_LGAMMA
83# endif
84#endif
85
86#if !defined(USE_TGAMMA) || !defined(USE_LGAMMA)
87
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000088static double
89sinpi(double x)
90{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 double y, r;
92 int n;
93 /* this function should only ever be called for finite arguments */
94 assert(Py_IS_FINITE(x));
95 y = fmod(fabs(x), 2.0);
96 n = (int)round(2.0*y);
97 assert(0 <= n && n <= 4);
98 switch (n) {
99 case 0:
100 r = sin(pi*y);
101 break;
102 case 1:
103 r = cos(pi*(y-0.5));
104 break;
105 case 2:
106 /* N.B. -sin(pi*(y-1.0)) is *not* equivalent: it would give
107 -0.0 instead of 0.0 when y == 1.0. */
108 r = sin(pi*(1.0-y));
109 break;
110 case 3:
111 r = -cos(pi*(y-1.5));
112 break;
113 case 4:
114 r = sin(pi*(y-2.0));
115 break;
116 default:
117 assert(0); /* should never get here */
118 r = -1.23e200; /* silence gcc warning */
119 }
120 return copysign(1.0, x)*r;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000121}
122
123/* Implementation of the real gamma function. In extensive but non-exhaustive
124 random tests, this function proved accurate to within <= 10 ulps across the
125 entire float domain. Note that accuracy may depend on the quality of the
126 system math functions, the pow function in particular. Special cases
127 follow C99 annex F. The parameters and method are tailored to platforms
128 whose double format is the IEEE 754 binary64 format.
129
130 Method: for x > 0.0 we use the Lanczos approximation with parameters N=13
131 and g=6.024680040776729583740234375; these parameters are amongst those
132 used by the Boost library. Following Boost (again), we re-express the
133 Lanczos sum as a rational function, and compute it that way. The
134 coefficients below were computed independently using MPFR, and have been
135 double-checked against the coefficients in the Boost source code.
136
137 For x < 0.0 we use the reflection formula.
138
139 There's one minor tweak that deserves explanation: Lanczos' formula for
140 Gamma(x) involves computing pow(x+g-0.5, x-0.5) / exp(x+g-0.5). For many x
141 values, x+g-0.5 can be represented exactly. However, in cases where it
142 can't be represented exactly the small error in x+g-0.5 can be magnified
143 significantly by the pow and exp calls, especially for large x. A cheap
144 correction is to multiply by (1 + e*g/(x+g-0.5)), where e is the error
145 involved in the computation of x+g-0.5 (that is, e = computed value of
146 x+g-0.5 - exact value of x+g-0.5). Here's the proof:
147
148 Correction factor
149 -----------------
150 Write x+g-0.5 = y-e, where y is exactly representable as an IEEE 754
151 double, and e is tiny. Then:
152
153 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) = pow(y-e, x-0.5)/exp(y-e)
154 = pow(y, x-0.5)/exp(y) * C,
155
156 where the correction_factor C is given by
157
158 C = pow(1-e/y, x-0.5) * exp(e)
159
160 Since e is tiny, pow(1-e/y, x-0.5) ~ 1-(x-0.5)*e/y, and exp(x) ~ 1+e, so:
161
162 C ~ (1-(x-0.5)*e/y) * (1+e) ~ 1 + e*(y-(x-0.5))/y
163
164 But y-(x-0.5) = g+e, and g+e ~ g. So we get C ~ 1 + e*g/y, and
165
166 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) ~ pow(y, x-0.5)/exp(y) * (1 + e*g/y),
167
168 Note that for accuracy, when computing r*C it's better to do
169
170 r + e*g/y*r;
171
172 than
173
174 r * (1 + e*g/y);
175
176 since the addition in the latter throws away most of the bits of
177 information in e*g/y.
178*/
179
180#define LANCZOS_N 13
181static const double lanczos_g = 6.024680040776729583740234375;
182static const double lanczos_g_minus_half = 5.524680040776729583740234375;
183static const double lanczos_num_coeffs[LANCZOS_N] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 23531376880.410759688572007674451636754734846804940,
185 42919803642.649098768957899047001988850926355848959,
186 35711959237.355668049440185451547166705960488635843,
187 17921034426.037209699919755754458931112671403265390,
188 6039542586.3520280050642916443072979210699388420708,
189 1439720407.3117216736632230727949123939715485786772,
190 248874557.86205415651146038641322942321632125127801,
191 31426415.585400194380614231628318205362874684987640,
192 2876370.6289353724412254090516208496135991145378768,
193 186056.26539522349504029498971604569928220784236328,
194 8071.6720023658162106380029022722506138218516325024,
195 210.82427775157934587250973392071336271166969580291,
196 2.5066282746310002701649081771338373386264310793408
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000197};
198
199/* denominator is x*(x+1)*...*(x+LANCZOS_N-2) */
200static const double lanczos_den_coeffs[LANCZOS_N] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 0.0, 39916800.0, 120543840.0, 150917976.0, 105258076.0, 45995730.0,
202 13339535.0, 2637558.0, 357423.0, 32670.0, 1925.0, 66.0, 1.0};
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000203
204/* gamma values for small positive integers, 1 though NGAMMA_INTEGRAL */
205#define NGAMMA_INTEGRAL 23
206static const double gamma_integral[NGAMMA_INTEGRAL] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0,
208 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0,
209 1307674368000.0, 20922789888000.0, 355687428096000.0,
210 6402373705728000.0, 121645100408832000.0, 2432902008176640000.0,
211 51090942171709440000.0, 1124000727777607680000.0,
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000212};
213
214/* Lanczos' sum L_g(x), for positive x */
215
216static double
217lanczos_sum(double x)
218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 double num = 0.0, den = 0.0;
220 int i;
221 assert(x > 0.0);
222 /* evaluate the rational function lanczos_sum(x). For large
223 x, the obvious algorithm risks overflow, so we instead
224 rescale the denominator and numerator of the rational
225 function by x**(1-LANCZOS_N) and treat this as a
226 rational function in 1/x. This also reduces the error for
227 larger x values. The choice of cutoff point (5.0 below) is
228 somewhat arbitrary; in tests, smaller cutoff values than
229 this resulted in lower accuracy. */
230 if (x < 5.0) {
231 for (i = LANCZOS_N; --i >= 0; ) {
232 num = num * x + lanczos_num_coeffs[i];
233 den = den * x + lanczos_den_coeffs[i];
234 }
235 }
236 else {
237 for (i = 0; i < LANCZOS_N; i++) {
238 num = num / x + lanczos_num_coeffs[i];
239 den = den / x + lanczos_den_coeffs[i];
240 }
241 }
242 return num/den;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000243}
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200244#endif /* !defined(USE_TGAMMA) || !defined(USE_LGAMMA) */
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000245
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +0000246/* Constant for +infinity, generated in the same way as float('inf'). */
247
248static double
249m_inf(void)
250{
251#ifndef PY_NO_SHORT_FLOAT_REPR
252 return _Py_dg_infinity(0);
253#else
254 return Py_HUGE_VAL;
255#endif
256}
257
258/* Constant nan value, generated in the same way as float('nan'). */
259/* We don't currently assume that Py_NAN is defined everywhere. */
260
261#if !defined(PY_NO_SHORT_FLOAT_REPR) || defined(Py_NAN)
262
263static double
264m_nan(void)
265{
266#ifndef PY_NO_SHORT_FLOAT_REPR
267 return _Py_dg_stdnan(0);
268#else
269 return Py_NAN;
270#endif
271}
272
273#endif
274
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000275static double
276m_tgamma(double x)
277{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200278#ifdef USE_TGAMMA
279 if (x == 0.0) {
280 errno = EDOM;
281 /* tgamma(+-0.0) = +-inf, divide-by-zero */
282 return copysign(Py_HUGE_VAL, x);
283 }
284 return tgamma(x);
285#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 double absx, r, y, z, sqrtpow;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 /* special cases */
289 if (!Py_IS_FINITE(x)) {
290 if (Py_IS_NAN(x) || x > 0.0)
291 return x; /* tgamma(nan) = nan, tgamma(inf) = inf */
292 else {
293 errno = EDOM;
294 return Py_NAN; /* tgamma(-inf) = nan, invalid */
295 }
296 }
297 if (x == 0.0) {
298 errno = EDOM;
Mark Dickinson50203a62011-09-25 15:26:43 +0100299 /* tgamma(+-0.0) = +-inf, divide-by-zero */
300 return copysign(Py_HUGE_VAL, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 /* integer arguments */
304 if (x == floor(x)) {
305 if (x < 0.0) {
306 errno = EDOM; /* tgamma(n) = nan, invalid for */
307 return Py_NAN; /* negative integers n */
308 }
309 if (x <= NGAMMA_INTEGRAL)
310 return gamma_integral[(int)x - 1];
311 }
312 absx = fabs(x);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 /* tiny arguments: tgamma(x) ~ 1/x for x near 0 */
315 if (absx < 1e-20) {
316 r = 1.0/x;
317 if (Py_IS_INFINITY(r))
318 errno = ERANGE;
319 return r;
320 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 /* large arguments: assuming IEEE 754 doubles, tgamma(x) overflows for
323 x > 200, and underflows to +-0.0 for x < -200, not a negative
324 integer. */
325 if (absx > 200.0) {
326 if (x < 0.0) {
327 return 0.0/sinpi(x);
328 }
329 else {
330 errno = ERANGE;
331 return Py_HUGE_VAL;
332 }
333 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 y = absx + lanczos_g_minus_half;
336 /* compute error in sum */
337 if (absx > lanczos_g_minus_half) {
338 /* note: the correction can be foiled by an optimizing
339 compiler that (incorrectly) thinks that an expression like
340 a + b - a - b can be optimized to 0.0. This shouldn't
341 happen in a standards-conforming compiler. */
342 double q = y - absx;
343 z = q - lanczos_g_minus_half;
344 }
345 else {
346 double q = y - lanczos_g_minus_half;
347 z = q - absx;
348 }
349 z = z * lanczos_g / y;
350 if (x < 0.0) {
351 r = -pi / sinpi(absx) / absx * exp(y) / lanczos_sum(absx);
352 r -= z * r;
353 if (absx < 140.0) {
354 r /= pow(y, absx - 0.5);
355 }
356 else {
357 sqrtpow = pow(y, absx / 2.0 - 0.25);
358 r /= sqrtpow;
359 r /= sqrtpow;
360 }
361 }
362 else {
363 r = lanczos_sum(absx) / exp(y);
364 r += z * r;
365 if (absx < 140.0) {
366 r *= pow(y, absx - 0.5);
367 }
368 else {
369 sqrtpow = pow(y, absx / 2.0 - 0.25);
370 r *= sqrtpow;
371 r *= sqrtpow;
372 }
373 }
374 if (Py_IS_INFINITY(r))
375 errno = ERANGE;
376 return r;
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200377#endif
Guido van Rossum8832b621991-12-16 15:44:24 +0000378}
379
Christian Heimes53876d92008-04-19 00:31:39 +0000380/*
Mark Dickinson05d2e082009-12-11 20:17:17 +0000381 lgamma: natural log of the absolute value of the Gamma function.
382 For large arguments, Lanczos' formula works extremely well here.
383*/
384
385static double
386m_lgamma(double x)
387{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200388 double r;
389
390#ifdef USE_LGAMMA
391 r = lgamma(x);
392 if (errno == ERANGE && x == floor(x) && x <= 0.0) {
393 errno = EDOM; /* lgamma(n) = inf, divide-by-zero for */
394 return Py_HUGE_VAL; /* integers n <= 0 */
395 }
396 return r;
397#else
398 double absx;
Mark Dickinson05d2e082009-12-11 20:17:17 +0000399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 /* special cases */
401 if (!Py_IS_FINITE(x)) {
402 if (Py_IS_NAN(x))
403 return x; /* lgamma(nan) = nan */
404 else
405 return Py_HUGE_VAL; /* lgamma(+-inf) = +inf */
406 }
Mark Dickinson05d2e082009-12-11 20:17:17 +0000407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 /* integer arguments */
409 if (x == floor(x) && x <= 2.0) {
410 if (x <= 0.0) {
411 errno = EDOM; /* lgamma(n) = inf, divide-by-zero for */
412 return Py_HUGE_VAL; /* integers n <= 0 */
413 }
414 else {
415 return 0.0; /* lgamma(1) = lgamma(2) = 0.0 */
416 }
417 }
Mark Dickinson05d2e082009-12-11 20:17:17 +0000418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 absx = fabs(x);
420 /* tiny arguments: lgamma(x) ~ -log(fabs(x)) for small x */
421 if (absx < 1e-20)
422 return -log(absx);
Mark Dickinson05d2e082009-12-11 20:17:17 +0000423
Mark Dickinson9c91eb82010-07-07 16:17:31 +0000424 /* Lanczos' formula. We could save a fraction of a ulp in accuracy by
425 having a second set of numerator coefficients for lanczos_sum that
426 absorbed the exp(-lanczos_g) term, and throwing out the lanczos_g
427 subtraction below; it's probably not worth it. */
428 r = log(lanczos_sum(absx)) - lanczos_g;
429 r += (absx - 0.5) * (log(absx + lanczos_g - 0.5) - 1);
430 if (x < 0.0)
431 /* Use reflection formula to get value for negative x. */
432 r = logpi - log(fabs(sinpi(absx))) - log(absx) - r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 if (Py_IS_INFINITY(r))
434 errno = ERANGE;
435 return r;
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200436#endif
Mark Dickinson05d2e082009-12-11 20:17:17 +0000437}
438
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200439#if !defined(HAVE_ERF) || !defined(HAVE_ERFC)
440
Mark Dickinson45f992a2009-12-19 11:20:49 +0000441/*
442 Implementations of the error function erf(x) and the complementary error
443 function erfc(x).
444
Brett Cannon45adb312016-01-15 09:38:24 -0800445 Method: we use a series approximation for erf for small x, and a continued
446 fraction approximation for erfc(x) for larger x;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000447 combined with the relations erf(-x) = -erf(x) and erfc(x) = 1.0 - erf(x),
448 this gives us erf(x) and erfc(x) for all x.
449
450 The series expansion used is:
451
452 erf(x) = x*exp(-x*x)/sqrt(pi) * [
453 2/1 + 4/3 x**2 + 8/15 x**4 + 16/105 x**6 + ...]
454
455 The coefficient of x**(2k-2) here is 4**k*factorial(k)/factorial(2*k).
456 This series converges well for smallish x, but slowly for larger x.
457
458 The continued fraction expansion used is:
459
460 erfc(x) = x*exp(-x*x)/sqrt(pi) * [1/(0.5 + x**2 -) 0.5/(2.5 + x**2 - )
461 3.0/(4.5 + x**2 - ) 7.5/(6.5 + x**2 - ) ...]
462
463 after the first term, the general term has the form:
464
465 k*(k-0.5)/(2*k+0.5 + x**2 - ...).
466
467 This expansion converges fast for larger x, but convergence becomes
468 infinitely slow as x approaches 0.0. The (somewhat naive) continued
469 fraction evaluation algorithm used below also risks overflow for large x;
470 but for large x, erfc(x) == 0.0 to within machine precision. (For
471 example, erfc(30.0) is approximately 2.56e-393).
472
473 Parameters: use series expansion for abs(x) < ERF_SERIES_CUTOFF and
474 continued fraction expansion for ERF_SERIES_CUTOFF <= abs(x) <
475 ERFC_CONTFRAC_CUTOFF. ERFC_SERIES_TERMS and ERFC_CONTFRAC_TERMS are the
476 numbers of terms to use for the relevant expansions. */
477
478#define ERF_SERIES_CUTOFF 1.5
479#define ERF_SERIES_TERMS 25
480#define ERFC_CONTFRAC_CUTOFF 30.0
481#define ERFC_CONTFRAC_TERMS 50
482
483/*
484 Error function, via power series.
485
486 Given a finite float x, return an approximation to erf(x).
487 Converges reasonably fast for small x.
488*/
489
490static double
491m_erf_series(double x)
492{
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000493 double x2, acc, fk, result;
494 int i, saved_errno;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 x2 = x * x;
497 acc = 0.0;
498 fk = (double)ERF_SERIES_TERMS + 0.5;
499 for (i = 0; i < ERF_SERIES_TERMS; i++) {
500 acc = 2.0 + x2 * acc / fk;
501 fk -= 1.0;
502 }
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000503 /* Make sure the exp call doesn't affect errno;
504 see m_erfc_contfrac for more. */
505 saved_errno = errno;
506 result = acc * x * exp(-x2) / sqrtpi;
507 errno = saved_errno;
508 return result;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000509}
510
511/*
512 Complementary error function, via continued fraction expansion.
513
514 Given a positive float x, return an approximation to erfc(x). Converges
515 reasonably fast for x large (say, x > 2.0), and should be safe from
516 overflow if x and nterms are not too large. On an IEEE 754 machine, with x
517 <= 30.0, we're safe up to nterms = 100. For x >= 30.0, erfc(x) is smaller
518 than the smallest representable nonzero float. */
519
520static double
521m_erfc_contfrac(double x)
522{
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000523 double x2, a, da, p, p_last, q, q_last, b, result;
524 int i, saved_errno;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 if (x >= ERFC_CONTFRAC_CUTOFF)
527 return 0.0;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 x2 = x*x;
530 a = 0.0;
531 da = 0.5;
532 p = 1.0; p_last = 0.0;
533 q = da + x2; q_last = 1.0;
534 for (i = 0; i < ERFC_CONTFRAC_TERMS; i++) {
535 double temp;
536 a += da;
537 da += 2.0;
538 b = da + x2;
539 temp = p; p = b*p - a*p_last; p_last = temp;
540 temp = q; q = b*q - a*q_last; q_last = temp;
541 }
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000542 /* Issue #8986: On some platforms, exp sets errno on underflow to zero;
543 save the current errno value so that we can restore it later. */
544 saved_errno = errno;
545 result = p / q * x * exp(-x2) / sqrtpi;
546 errno = saved_errno;
547 return result;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000548}
549
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200550#endif /* !defined(HAVE_ERF) || !defined(HAVE_ERFC) */
551
Mark Dickinson45f992a2009-12-19 11:20:49 +0000552/* Error function erf(x), for general x */
553
554static double
555m_erf(double x)
556{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200557#ifdef HAVE_ERF
558 return erf(x);
559#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 double absx, cf;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 if (Py_IS_NAN(x))
563 return x;
564 absx = fabs(x);
565 if (absx < ERF_SERIES_CUTOFF)
566 return m_erf_series(x);
567 else {
568 cf = m_erfc_contfrac(absx);
569 return x > 0.0 ? 1.0 - cf : cf - 1.0;
570 }
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200571#endif
Mark Dickinson45f992a2009-12-19 11:20:49 +0000572}
573
574/* Complementary error function erfc(x), for general x. */
575
576static double
577m_erfc(double x)
578{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200579#ifdef HAVE_ERFC
580 return erfc(x);
581#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 double absx, cf;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 if (Py_IS_NAN(x))
585 return x;
586 absx = fabs(x);
587 if (absx < ERF_SERIES_CUTOFF)
588 return 1.0 - m_erf_series(x);
589 else {
590 cf = m_erfc_contfrac(absx);
591 return x > 0.0 ? cf : 2.0 - cf;
592 }
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200593#endif
Mark Dickinson45f992a2009-12-19 11:20:49 +0000594}
Mark Dickinson05d2e082009-12-11 20:17:17 +0000595
596/*
Christian Heimese57950f2008-04-21 13:08:03 +0000597 wrapper for atan2 that deals directly with special cases before
598 delegating to the platform libm for the remaining cases. This
599 is necessary to get consistent behaviour across platforms.
600 Windows, FreeBSD and alpha Tru64 are amongst platforms that don't
601 always follow C99.
602*/
603
604static double
605m_atan2(double y, double x)
606{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 if (Py_IS_NAN(x) || Py_IS_NAN(y))
608 return Py_NAN;
609 if (Py_IS_INFINITY(y)) {
610 if (Py_IS_INFINITY(x)) {
611 if (copysign(1., x) == 1.)
612 /* atan2(+-inf, +inf) == +-pi/4 */
613 return copysign(0.25*Py_MATH_PI, y);
614 else
615 /* atan2(+-inf, -inf) == +-pi*3/4 */
616 return copysign(0.75*Py_MATH_PI, y);
617 }
618 /* atan2(+-inf, x) == +-pi/2 for finite x */
619 return copysign(0.5*Py_MATH_PI, y);
620 }
621 if (Py_IS_INFINITY(x) || y == 0.) {
622 if (copysign(1., x) == 1.)
623 /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */
624 return copysign(0., y);
625 else
626 /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */
627 return copysign(Py_MATH_PI, y);
628 }
629 return atan2(y, x);
Christian Heimese57950f2008-04-21 13:08:03 +0000630}
631
632/*
Mark Dickinsone675f082008-12-11 21:56:00 +0000633 Various platforms (Solaris, OpenBSD) do nonstandard things for log(0),
634 log(-ve), log(NaN). Here are wrappers for log and log10 that deal with
635 special values directly, passing positive non-special values through to
636 the system log/log10.
637 */
638
639static double
640m_log(double x)
641{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 if (Py_IS_FINITE(x)) {
643 if (x > 0.0)
644 return log(x);
645 errno = EDOM;
646 if (x == 0.0)
647 return -Py_HUGE_VAL; /* log(0) = -inf */
648 else
649 return Py_NAN; /* log(-ve) = nan */
650 }
651 else if (Py_IS_NAN(x))
652 return x; /* log(nan) = nan */
653 else if (x > 0.0)
654 return x; /* log(inf) = inf */
655 else {
656 errno = EDOM;
657 return Py_NAN; /* log(-inf) = nan */
658 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000659}
660
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200661/*
662 log2: log to base 2.
663
664 Uses an algorithm that should:
Mark Dickinson83b8c0b2011-05-09 08:40:20 +0100665
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200666 (a) produce exact results for powers of 2, and
Mark Dickinson83b8c0b2011-05-09 08:40:20 +0100667 (b) give a monotonic log2 (for positive finite floats),
668 assuming that the system log is monotonic.
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200669*/
670
671static double
672m_log2(double x)
673{
674 if (!Py_IS_FINITE(x)) {
675 if (Py_IS_NAN(x))
676 return x; /* log2(nan) = nan */
677 else if (x > 0.0)
678 return x; /* log2(+inf) = +inf */
679 else {
680 errno = EDOM;
681 return Py_NAN; /* log2(-inf) = nan, invalid-operation */
682 }
683 }
684
685 if (x > 0.0) {
Victor Stinner8f9f8d62011-05-09 12:45:41 +0200686#ifdef HAVE_LOG2
687 return log2(x);
688#else
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200689 double m;
690 int e;
691 m = frexp(x, &e);
692 /* We want log2(m * 2**e) == log(m) / log(2) + e. Care is needed when
693 * x is just greater than 1.0: in that case e is 1, log(m) is negative,
694 * and we get significant cancellation error from the addition of
695 * log(m) / log(2) to e. The slight rewrite of the expression below
696 * avoids this problem.
697 */
698 if (x >= 1.0) {
699 return log(2.0 * m) / log(2.0) + (e - 1);
700 }
701 else {
702 return log(m) / log(2.0) + e;
703 }
Victor Stinner8f9f8d62011-05-09 12:45:41 +0200704#endif
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200705 }
706 else if (x == 0.0) {
707 errno = EDOM;
708 return -Py_HUGE_VAL; /* log2(0) = -inf, divide-by-zero */
709 }
710 else {
711 errno = EDOM;
Mark Dickinson23442582011-05-09 08:05:00 +0100712 return Py_NAN; /* log2(-inf) = nan, invalid-operation */
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200713 }
714}
715
Mark Dickinsone675f082008-12-11 21:56:00 +0000716static double
717m_log10(double x)
718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 if (Py_IS_FINITE(x)) {
720 if (x > 0.0)
721 return log10(x);
722 errno = EDOM;
723 if (x == 0.0)
724 return -Py_HUGE_VAL; /* log10(0) = -inf */
725 else
726 return Py_NAN; /* log10(-ve) = nan */
727 }
728 else if (Py_IS_NAN(x))
729 return x; /* log10(nan) = nan */
730 else if (x > 0.0)
731 return x; /* log10(inf) = inf */
732 else {
733 errno = EDOM;
734 return Py_NAN; /* log10(-inf) = nan */
735 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000736}
737
738
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200739/*[clinic input]
740math.gcd
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300741
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200742 x as a: object
743 y as b: object
744 /
745
746greatest common divisor of x and y
747[clinic start generated code]*/
748
749static PyObject *
750math_gcd_impl(PyObject *module, PyObject *a, PyObject *b)
751/*[clinic end generated code: output=7b2e0c151bd7a5d8 input=c2691e57fb2a98fa]*/
752{
753 PyObject *g;
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300754
755 a = PyNumber_Index(a);
756 if (a == NULL)
757 return NULL;
758 b = PyNumber_Index(b);
759 if (b == NULL) {
760 Py_DECREF(a);
761 return NULL;
762 }
763 g = _PyLong_GCD(a, b);
764 Py_DECREF(a);
765 Py_DECREF(b);
766 return g;
767}
768
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300769
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000770/* Call is_error when errno != 0, and where x is the result libm
771 * returned. is_error will usually set up an exception and return
772 * true (1), but may return false (0) without setting up an exception.
773 */
774static int
775is_error(double x)
776{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 int result = 1; /* presumption of guilt */
778 assert(errno); /* non-zero errno is a precondition for calling */
779 if (errno == EDOM)
780 PyErr_SetString(PyExc_ValueError, "math domain error");
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 else if (errno == ERANGE) {
783 /* ANSI C generally requires libm functions to set ERANGE
784 * on overflow, but also generally *allows* them to set
785 * ERANGE on underflow too. There's no consistency about
786 * the latter across platforms.
787 * Alas, C99 never requires that errno be set.
788 * Here we suppress the underflow errors (libm functions
789 * should return a zero on underflow, and +- HUGE_VAL on
790 * overflow, so testing the result for zero suffices to
791 * distinguish the cases).
792 *
793 * On some platforms (Ubuntu/ia64) it seems that errno can be
794 * set to ERANGE for subnormal results that do *not* underflow
795 * to zero. So to be safe, we'll ignore ERANGE whenever the
796 * function result is less than one in absolute value.
797 */
798 if (fabs(x) < 1.0)
799 result = 0;
800 else
801 PyErr_SetString(PyExc_OverflowError,
802 "math range error");
803 }
804 else
805 /* Unexpected math error */
806 PyErr_SetFromErrno(PyExc_ValueError);
807 return result;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000808}
809
Mark Dickinsone675f082008-12-11 21:56:00 +0000810/*
Christian Heimes53876d92008-04-19 00:31:39 +0000811 math_1 is used to wrap a libm function f that takes a double
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200812 argument and returns a double.
Christian Heimes53876d92008-04-19 00:31:39 +0000813
814 The error reporting follows these rules, which are designed to do
815 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
816 platforms.
817
818 - a NaN result from non-NaN inputs causes ValueError to be raised
819 - an infinite result from finite inputs causes OverflowError to be
820 raised if can_overflow is 1, or raises ValueError if can_overflow
821 is 0.
822 - if the result is finite and errno == EDOM then ValueError is
823 raised
824 - if the result is finite and nonzero and errno == ERANGE then
825 OverflowError is raised
826
827 The last rule is used to catch overflow on platforms which follow
828 C89 but for which HUGE_VAL is not an infinity.
829
830 For the majority of one-argument functions these rules are enough
831 to ensure that Python's functions behave as specified in 'Annex F'
832 of the C99 standard, with the 'invalid' and 'divide-by-zero'
833 floating-point exceptions mapping to Python's ValueError and the
834 'overflow' floating-point exception mapping to OverflowError.
835 math_1 only works for functions that don't have singularities *and*
836 the possibility of overflow; fortunately, that covers everything we
837 care about right now.
838*/
839
Barry Warsaw8b43b191996-12-09 22:32:36 +0000840static PyObject *
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000841math_1_to_whatever(PyObject *arg, double (*func) (double),
Christian Heimes53876d92008-04-19 00:31:39 +0000842 PyObject *(*from_double_func) (double),
843 int can_overflow)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000844{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 double x, r;
846 x = PyFloat_AsDouble(arg);
847 if (x == -1.0 && PyErr_Occurred())
848 return NULL;
849 errno = 0;
850 PyFPE_START_PROTECT("in math_1", return 0);
851 r = (*func)(x);
852 PyFPE_END_PROTECT(r);
853 if (Py_IS_NAN(r) && !Py_IS_NAN(x)) {
854 PyErr_SetString(PyExc_ValueError,
855 "math domain error"); /* invalid arg */
856 return NULL;
857 }
858 if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) {
Benjamin Peterson2354a752012-03-13 16:13:09 -0500859 if (can_overflow)
860 PyErr_SetString(PyExc_OverflowError,
861 "math range error"); /* overflow */
862 else
863 PyErr_SetString(PyExc_ValueError,
864 "math domain error"); /* singularity */
865 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 }
867 if (Py_IS_FINITE(r) && errno && is_error(r))
868 /* this branch unnecessary on most platforms */
869 return NULL;
Mark Dickinsonde429622008-05-01 00:19:23 +0000870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 return (*from_double_func)(r);
Christian Heimes53876d92008-04-19 00:31:39 +0000872}
873
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000874/* variant of math_1, to be used when the function being wrapped is known to
875 set errno properly (that is, errno = EDOM for invalid or divide-by-zero,
876 errno = ERANGE for overflow). */
877
878static PyObject *
879math_1a(PyObject *arg, double (*func) (double))
880{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 double x, r;
882 x = PyFloat_AsDouble(arg);
883 if (x == -1.0 && PyErr_Occurred())
884 return NULL;
885 errno = 0;
886 PyFPE_START_PROTECT("in math_1a", return 0);
887 r = (*func)(x);
888 PyFPE_END_PROTECT(r);
889 if (errno && is_error(r))
890 return NULL;
891 return PyFloat_FromDouble(r);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000892}
893
Christian Heimes53876d92008-04-19 00:31:39 +0000894/*
895 math_2 is used to wrap a libm function f that takes two double
896 arguments and returns a double.
897
898 The error reporting follows these rules, which are designed to do
899 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
900 platforms.
901
902 - a NaN result from non-NaN inputs causes ValueError to be raised
903 - an infinite result from finite inputs causes OverflowError to be
904 raised.
905 - if the result is finite and errno == EDOM then ValueError is
906 raised
907 - if the result is finite and nonzero and errno == ERANGE then
908 OverflowError is raised
909
910 The last rule is used to catch overflow on platforms which follow
911 C89 but for which HUGE_VAL is not an infinity.
912
913 For most two-argument functions (copysign, fmod, hypot, atan2)
914 these rules are enough to ensure that Python's functions behave as
915 specified in 'Annex F' of the C99 standard, with the 'invalid' and
916 'divide-by-zero' floating-point exceptions mapping to Python's
917 ValueError and the 'overflow' floating-point exception mapping to
918 OverflowError.
919*/
920
921static PyObject *
922math_1(PyObject *arg, double (*func) (double), int can_overflow)
923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow);
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000925}
926
927static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000928math_1_to_int(PyObject *arg, double (*func) (double), int can_overflow)
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000929{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 return math_1_to_whatever(arg, func, PyLong_FromDouble, can_overflow);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000931}
932
Barry Warsaw8b43b191996-12-09 22:32:36 +0000933static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200934math_2(PyObject *args, double (*func) (double, double), const char *funcname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000935{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 PyObject *ox, *oy;
937 double x, y, r;
938 if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy))
939 return NULL;
940 x = PyFloat_AsDouble(ox);
941 y = PyFloat_AsDouble(oy);
942 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
943 return NULL;
944 errno = 0;
945 PyFPE_START_PROTECT("in math_2", return 0);
946 r = (*func)(x, y);
947 PyFPE_END_PROTECT(r);
948 if (Py_IS_NAN(r)) {
949 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
950 errno = EDOM;
951 else
952 errno = 0;
953 }
954 else if (Py_IS_INFINITY(r)) {
955 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
956 errno = ERANGE;
957 else
958 errno = 0;
959 }
960 if (errno && is_error(r))
961 return NULL;
962 else
963 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000964}
965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966#define FUNC1(funcname, func, can_overflow, docstring) \
967 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
968 return math_1(args, func, can_overflow); \
969 }\
970 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972#define FUNC1A(funcname, func, docstring) \
973 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
974 return math_1a(args, func); \
975 }\
976 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000977
Fred Drake40c48682000-07-03 18:11:56 +0000978#define FUNC2(funcname, func, docstring) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
980 return math_2(args, func, #funcname); \
981 }\
982 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000983
Christian Heimes53876d92008-04-19 00:31:39 +0000984FUNC1(acos, acos, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200985 "acos($module, x, /)\n--\n\n"
986 "Return the arc cosine (measured in radians) of x.")
Mark Dickinsonf3718592009-12-21 15:27:41 +0000987FUNC1(acosh, m_acosh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200988 "acosh($module, x, /)\n--\n\n"
989 "Return the inverse hyperbolic cosine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000990FUNC1(asin, asin, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200991 "asin($module, x, /)\n--\n\n"
992 "Return the arc sine (measured in radians) of x.")
Mark Dickinsonf3718592009-12-21 15:27:41 +0000993FUNC1(asinh, m_asinh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200994 "asinh($module, x, /)\n--\n\n"
995 "Return the inverse hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +0000996FUNC1(atan, atan, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200997 "atan($module, x, /)\n--\n\n"
998 "Return the arc tangent (measured in radians) of x.")
Christian Heimese57950f2008-04-21 13:08:03 +0000999FUNC2(atan2, m_atan2,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001000 "atan2($module, y, x, /)\n--\n\n"
1001 "Return the arc tangent (measured in radians) of y/x.\n\n"
Tim Petersfe71f812001-08-07 22:10:00 +00001002 "Unlike atan(y/x), the signs of both x and y are considered.")
Mark Dickinsonf3718592009-12-21 15:27:41 +00001003FUNC1(atanh, m_atanh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001004 "atanh($module, x, /)\n--\n\n"
1005 "Return the inverse hyperbolic tangent of x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +00001006
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001007/*[clinic input]
1008math.ceil
1009
1010 x as number: object
1011 /
1012
1013Return the ceiling of x as an Integral.
1014
1015This is the smallest integer >= x.
1016[clinic start generated code]*/
1017
1018static PyObject *
1019math_ceil(PyObject *module, PyObject *number)
1020/*[clinic end generated code: output=6c3b8a78bc201c67 input=2725352806399cab]*/
1021{
Benjamin Petersonce798522012-01-22 11:24:29 -05001022 _Py_IDENTIFIER(__ceil__);
Mark Dickinson6d02d9c2010-07-02 16:05:15 +00001023 PyObject *method, *result;
Guido van Rossum13e05de2007-08-23 22:56:55 +00001024
Benjamin Petersonce798522012-01-22 11:24:29 -05001025 method = _PyObject_LookupSpecial(number, &PyId___ceil__);
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001026 if (method == NULL) {
1027 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 return math_1_to_int(number, ceil, 0);
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001030 }
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001031 result = _PyObject_CallNoArg(method);
Mark Dickinson6d02d9c2010-07-02 16:05:15 +00001032 Py_DECREF(method);
1033 return result;
Guido van Rossum13e05de2007-08-23 22:56:55 +00001034}
1035
Christian Heimes072c0f12008-01-03 23:01:04 +00001036FUNC2(copysign, copysign,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001037 "copysign($module, x, y, /)\n--\n\n"
1038 "Return a float with the magnitude (absolute value) of x but the sign of y.\n\n"
1039 "On platforms that support signed zeros, copysign(1.0, -0.0)\n"
1040 "returns -1.0.\n")
Christian Heimes53876d92008-04-19 00:31:39 +00001041FUNC1(cos, cos, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001042 "cos($module, x, /)\n--\n\n"
1043 "Return the cosine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001044FUNC1(cosh, cosh, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001045 "cosh($module, x, /)\n--\n\n"
1046 "Return the hyperbolic cosine of x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +00001047FUNC1A(erf, m_erf,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001048 "erf($module, x, /)\n--\n\n"
1049 "Error function at x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +00001050FUNC1A(erfc, m_erfc,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001051 "erfc($module, x, /)\n--\n\n"
1052 "Complementary error function at x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001053FUNC1(exp, exp, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001054 "exp($module, x, /)\n--\n\n"
1055 "Return e raised to the power of x.")
Mark Dickinson664b5112009-12-16 20:23:42 +00001056FUNC1(expm1, m_expm1, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001057 "expm1($module, x, /)\n--\n\n"
1058 "Return exp(x)-1.\n\n"
Mark Dickinson664b5112009-12-16 20:23:42 +00001059 "This function avoids the loss of precision involved in the direct "
1060 "evaluation of exp(x)-1 for small x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001061FUNC1(fabs, fabs, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001062 "fabs($module, x, /)\n--\n\n"
1063 "Return the absolute value of the float x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +00001064
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001065/*[clinic input]
1066math.floor
1067
1068 x as number: object
1069 /
1070
1071Return the floor of x as an Integral.
1072
1073This is the largest integer <= x.
1074[clinic start generated code]*/
1075
1076static PyObject *
1077math_floor(PyObject *module, PyObject *number)
1078/*[clinic end generated code: output=c6a65c4884884b8a input=63af6b5d7ebcc3d6]*/
1079{
Benjamin Petersonce798522012-01-22 11:24:29 -05001080 _Py_IDENTIFIER(__floor__);
Benjamin Petersonb0125892010-07-02 13:35:17 +00001081 PyObject *method, *result;
Guido van Rossum13e05de2007-08-23 22:56:55 +00001082
Benjamin Petersonce798522012-01-22 11:24:29 -05001083 method = _PyObject_LookupSpecial(number, &PyId___floor__);
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001084 if (method == NULL) {
1085 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 return math_1_to_int(number, floor, 0);
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001088 }
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001089 result = _PyObject_CallNoArg(method);
Benjamin Petersonb0125892010-07-02 13:35:17 +00001090 Py_DECREF(method);
1091 return result;
Guido van Rossum13e05de2007-08-23 22:56:55 +00001092}
1093
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001094FUNC1A(gamma, m_tgamma,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001095 "gamma($module, x, /)\n--\n\n"
1096 "Gamma function at x.")
Mark Dickinson05d2e082009-12-11 20:17:17 +00001097FUNC1A(lgamma, m_lgamma,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001098 "lgamma($module, x, /)\n--\n\n"
1099 "Natural logarithm of absolute value of Gamma function at x.")
Mark Dickinsonbe64d952010-07-07 16:21:29 +00001100FUNC1(log1p, m_log1p, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001101 "log1p($module, x, /)\n--\n\n"
1102 "Return the natural logarithm of 1+x (base e).\n\n"
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001103 "The result is computed in a way which is accurate for x near zero.")
Christian Heimes53876d92008-04-19 00:31:39 +00001104FUNC1(sin, sin, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001105 "sin($module, x, /)\n--\n\n"
1106 "Return the sine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001107FUNC1(sinh, sinh, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001108 "sinh($module, x, /)\n--\n\n"
1109 "Return the hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001110FUNC1(sqrt, sqrt, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001111 "sqrt($module, x, /)\n--\n\n"
1112 "Return the square root of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001113FUNC1(tan, tan, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001114 "tan($module, x, /)\n--\n\n"
1115 "Return the tangent of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001116FUNC1(tanh, tanh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001117 "tanh($module, x, /)\n--\n\n"
1118 "Return the hyperbolic tangent of x.")
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001119
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001120/* Precision summation function as msum() by Raymond Hettinger in
1121 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
1122 enhanced with the exact partials sum and roundoff from Mark
1123 Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
1124 See those links for more details, proofs and other references.
1125
1126 Note 1: IEEE 754R floating point semantics are assumed,
1127 but the current implementation does not re-establish special
1128 value semantics across iterations (i.e. handling -Inf + Inf).
1129
1130 Note 2: No provision is made for intermediate overflow handling;
Georg Brandlf78e02b2008-06-10 17:40:04 +00001131 therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001132 sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
1133 overflow of the first partial sum.
1134
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001135 Note 3: The intermediate values lo, yr, and hi are declared volatile so
1136 aggressive compilers won't algebraically reduce lo to always be exactly 0.0.
Georg Brandlf78e02b2008-06-10 17:40:04 +00001137 Also, the volatile declaration forces the values to be stored in memory as
1138 regular doubles instead of extended long precision (80-bit) values. This
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001139 prevents double rounding because any addition or subtraction of two doubles
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 can be resolved exactly into double-sized hi and lo values. As long as the
Georg Brandlf78e02b2008-06-10 17:40:04 +00001141 hi value gets forced into a double before yr and lo are computed, the extra
1142 bits in downstream extended precision operations (x87 for example) will be
1143 exactly zero and therefore can be losslessly stored back into a double,
1144 thereby preventing double rounding.
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001145
1146 Note 4: A similar implementation is in Modules/cmathmodule.c.
1147 Be sure to update both when making changes.
1148
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001149 Note 5: The signature of math.fsum() differs from builtins.sum()
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001150 because the start argument doesn't make sense in the context of
1151 accurate summation. Since the partials table is collapsed before
1152 returning a result, sum(seq2, start=sum(seq1)) may not equal the
1153 accurate result returned by sum(itertools.chain(seq1, seq2)).
1154*/
1155
1156#define NUM_PARTIALS 32 /* initial partials array size, on stack */
1157
1158/* Extend the partials array p[] by doubling its size. */
1159static int /* non-zero on error */
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001160_fsum_realloc(double **p_ptr, Py_ssize_t n,
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001161 double *ps, Py_ssize_t *m_ptr)
1162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 void *v = NULL;
1164 Py_ssize_t m = *m_ptr;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 m += m; /* double */
Victor Stinner049e5092014-08-17 22:20:00 +02001167 if (n < m && (size_t)m < ((size_t)PY_SSIZE_T_MAX / sizeof(double))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 double *p = *p_ptr;
1169 if (p == ps) {
1170 v = PyMem_Malloc(sizeof(double) * m);
1171 if (v != NULL)
1172 memcpy(v, ps, sizeof(double) * n);
1173 }
1174 else
1175 v = PyMem_Realloc(p, sizeof(double) * m);
1176 }
1177 if (v == NULL) { /* size overflow or no memory */
1178 PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
1179 return 1;
1180 }
1181 *p_ptr = (double*) v;
1182 *m_ptr = m;
1183 return 0;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001184}
1185
1186/* Full precision summation of a sequence of floats.
1187
1188 def msum(iterable):
1189 partials = [] # sorted, non-overlapping partial sums
1190 for x in iterable:
Mark Dickinsonfdb0acc2010-06-25 20:22:24 +00001191 i = 0
1192 for y in partials:
1193 if abs(x) < abs(y):
1194 x, y = y, x
1195 hi = x + y
1196 lo = y - (hi - x)
1197 if lo:
1198 partials[i] = lo
1199 i += 1
1200 x = hi
1201 partials[i:] = [x]
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001202 return sum_exact(partials)
1203
1204 Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
1205 are exactly equal to x+y. The inner loop applies hi/lo summation to each
1206 partial so that the list of partial sums remains exact.
1207
1208 Sum_exact() adds the partial sums exactly and correctly rounds the final
1209 result (using the round-half-to-even rule). The items in partials remain
1210 non-zero, non-special, non-overlapping and strictly increasing in
1211 magnitude, but possibly not all having the same sign.
1212
1213 Depends on IEEE 754 arithmetic guarantees and half-even rounding.
1214*/
1215
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001216/*[clinic input]
1217math.fsum
1218
1219 seq: object
1220 /
1221
1222Return an accurate floating point sum of values in the iterable seq.
1223
1224Assumes IEEE-754 floating point arithmetic.
1225[clinic start generated code]*/
1226
1227static PyObject *
1228math_fsum(PyObject *module, PyObject *seq)
1229/*[clinic end generated code: output=ba5c672b87fe34fc input=c51b7d8caf6f6e82]*/
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 PyObject *item, *iter, *sum = NULL;
1232 Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
1233 double x, y, t, ps[NUM_PARTIALS], *p = ps;
1234 double xsave, special_sum = 0.0, inf_sum = 0.0;
1235 volatile double hi, yr, lo;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 iter = PyObject_GetIter(seq);
1238 if (iter == NULL)
1239 return NULL;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 for(;;) { /* for x in iterable */
1244 assert(0 <= n && n <= m);
1245 assert((m == NUM_PARTIALS && p == ps) ||
1246 (m > NUM_PARTIALS && p != NULL));
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 item = PyIter_Next(iter);
1249 if (item == NULL) {
1250 if (PyErr_Occurred())
1251 goto _fsum_error;
1252 break;
1253 }
1254 x = PyFloat_AsDouble(item);
1255 Py_DECREF(item);
1256 if (PyErr_Occurred())
1257 goto _fsum_error;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 xsave = x;
1260 for (i = j = 0; j < n; j++) { /* for y in partials */
1261 y = p[j];
1262 if (fabs(x) < fabs(y)) {
1263 t = x; x = y; y = t;
1264 }
1265 hi = x + y;
1266 yr = hi - x;
1267 lo = y - yr;
1268 if (lo != 0.0)
1269 p[i++] = lo;
1270 x = hi;
1271 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 n = i; /* ps[i:] = [x] */
1274 if (x != 0.0) {
1275 if (! Py_IS_FINITE(x)) {
1276 /* a nonfinite x could arise either as
1277 a result of intermediate overflow, or
1278 as a result of a nan or inf in the
1279 summands */
1280 if (Py_IS_FINITE(xsave)) {
1281 PyErr_SetString(PyExc_OverflowError,
1282 "intermediate overflow in fsum");
1283 goto _fsum_error;
1284 }
1285 if (Py_IS_INFINITY(xsave))
1286 inf_sum += xsave;
1287 special_sum += xsave;
1288 /* reset partials */
1289 n = 0;
1290 }
1291 else if (n >= m && _fsum_realloc(&p, n, ps, &m))
1292 goto _fsum_error;
1293 else
1294 p[n++] = x;
1295 }
1296 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 if (special_sum != 0.0) {
1299 if (Py_IS_NAN(inf_sum))
1300 PyErr_SetString(PyExc_ValueError,
1301 "-inf + inf in fsum");
1302 else
1303 sum = PyFloat_FromDouble(special_sum);
1304 goto _fsum_error;
1305 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 hi = 0.0;
1308 if (n > 0) {
1309 hi = p[--n];
1310 /* sum_exact(ps, hi) from the top, stop when the sum becomes
1311 inexact. */
1312 while (n > 0) {
1313 x = hi;
1314 y = p[--n];
1315 assert(fabs(y) < fabs(x));
1316 hi = x + y;
1317 yr = hi - x;
1318 lo = y - yr;
1319 if (lo != 0.0)
1320 break;
1321 }
1322 /* Make half-even rounding work across multiple partials.
1323 Needed so that sum([1e-16, 1, 1e16]) will round-up the last
1324 digit to two instead of down to zero (the 1e-16 makes the 1
1325 slightly closer to two). With a potential 1 ULP rounding
1326 error fixed-up, math.fsum() can guarantee commutativity. */
1327 if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
1328 (lo > 0.0 && p[n-1] > 0.0))) {
1329 y = lo * 2.0;
1330 x = hi + y;
1331 yr = x - hi;
1332 if (y == yr)
1333 hi = x;
1334 }
1335 }
1336 sum = PyFloat_FromDouble(hi);
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001337
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001338_fsum_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 PyFPE_END_PROTECT(hi)
1340 Py_DECREF(iter);
1341 if (p != ps)
1342 PyMem_Free(p);
1343 return sum;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001344}
1345
1346#undef NUM_PARTIALS
1347
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001348
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001349/* Return the smallest integer k such that n < 2**k, or 0 if n == 0.
1350 * Equivalent to floor(lg(x))+1. Also equivalent to: bitwidth_of_type -
1351 * count_leading_zero_bits(x)
1352 */
1353
1354/* XXX: This routine does more or less the same thing as
1355 * bits_in_digit() in Objects/longobject.c. Someday it would be nice to
1356 * consolidate them. On BSD, there's a library function called fls()
1357 * that we could use, and GCC provides __builtin_clz().
1358 */
1359
1360static unsigned long
1361bit_length(unsigned long n)
1362{
1363 unsigned long len = 0;
1364 while (n != 0) {
1365 ++len;
1366 n >>= 1;
1367 }
1368 return len;
1369}
1370
1371static unsigned long
1372count_set_bits(unsigned long n)
1373{
1374 unsigned long count = 0;
1375 while (n != 0) {
1376 ++count;
1377 n &= n - 1; /* clear least significant bit */
1378 }
1379 return count;
1380}
1381
1382/* Divide-and-conquer factorial algorithm
1383 *
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07001384 * Based on the formula and pseudo-code provided at:
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001385 * http://www.luschny.de/math/factorial/binarysplitfact.html
1386 *
1387 * Faster algorithms exist, but they're more complicated and depend on
Ezio Melotti9527afd2010-07-08 15:03:02 +00001388 * a fast prime factorization algorithm.
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001389 *
1390 * Notes on the algorithm
1391 * ----------------------
1392 *
1393 * factorial(n) is written in the form 2**k * m, with m odd. k and m are
1394 * computed separately, and then combined using a left shift.
1395 *
1396 * The function factorial_odd_part computes the odd part m (i.e., the greatest
1397 * odd divisor) of factorial(n), using the formula:
1398 *
1399 * factorial_odd_part(n) =
1400 *
1401 * product_{i >= 0} product_{0 < j <= n / 2**i, j odd} j
1402 *
1403 * Example: factorial_odd_part(20) =
1404 *
1405 * (1) *
1406 * (1) *
1407 * (1 * 3 * 5) *
1408 * (1 * 3 * 5 * 7 * 9)
1409 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1410 *
1411 * Here i goes from large to small: the first term corresponds to i=4 (any
1412 * larger i gives an empty product), and the last term corresponds to i=0.
1413 * Each term can be computed from the last by multiplying by the extra odd
1414 * numbers required: e.g., to get from the penultimate term to the last one,
1415 * we multiply by (11 * 13 * 15 * 17 * 19).
1416 *
1417 * To see a hint of why this formula works, here are the same numbers as above
1418 * but with the even parts (i.e., the appropriate powers of 2) included. For
1419 * each subterm in the product for i, we multiply that subterm by 2**i:
1420 *
1421 * factorial(20) =
1422 *
1423 * (16) *
1424 * (8) *
1425 * (4 * 12 * 20) *
1426 * (2 * 6 * 10 * 14 * 18) *
1427 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1428 *
1429 * The factorial_partial_product function computes the product of all odd j in
1430 * range(start, stop) for given start and stop. It's used to compute the
1431 * partial products like (11 * 13 * 15 * 17 * 19) in the example above. It
1432 * operates recursively, repeatedly splitting the range into two roughly equal
1433 * pieces until the subranges are small enough to be computed using only C
1434 * integer arithmetic.
1435 *
1436 * The two-valuation k (i.e., the exponent of the largest power of 2 dividing
1437 * the factorial) is computed independently in the main math_factorial
1438 * function. By standard results, its value is:
1439 *
1440 * two_valuation = n//2 + n//4 + n//8 + ....
1441 *
1442 * It can be shown (e.g., by complete induction on n) that two_valuation is
1443 * equal to n - count_set_bits(n), where count_set_bits(n) gives the number of
1444 * '1'-bits in the binary expansion of n.
1445 */
1446
1447/* factorial_partial_product: Compute product(range(start, stop, 2)) using
1448 * divide and conquer. Assumes start and stop are odd and stop > start.
1449 * max_bits must be >= bit_length(stop - 2). */
1450
1451static PyObject *
1452factorial_partial_product(unsigned long start, unsigned long stop,
1453 unsigned long max_bits)
1454{
1455 unsigned long midpoint, num_operands;
1456 PyObject *left = NULL, *right = NULL, *result = NULL;
1457
1458 /* If the return value will fit an unsigned long, then we can
1459 * multiply in a tight, fast loop where each multiply is O(1).
1460 * Compute an upper bound on the number of bits required to store
1461 * the answer.
1462 *
1463 * Storing some integer z requires floor(lg(z))+1 bits, which is
1464 * conveniently the value returned by bit_length(z). The
1465 * product x*y will require at most
1466 * bit_length(x) + bit_length(y) bits to store, based
1467 * on the idea that lg product = lg x + lg y.
1468 *
1469 * We know that stop - 2 is the largest number to be multiplied. From
1470 * there, we have: bit_length(answer) <= num_operands *
1471 * bit_length(stop - 2)
1472 */
1473
1474 num_operands = (stop - start) / 2;
1475 /* The "num_operands <= 8 * SIZEOF_LONG" check guards against the
1476 * unlikely case of an overflow in num_operands * max_bits. */
1477 if (num_operands <= 8 * SIZEOF_LONG &&
1478 num_operands * max_bits <= 8 * SIZEOF_LONG) {
1479 unsigned long j, total;
1480 for (total = start, j = start + 2; j < stop; j += 2)
1481 total *= j;
1482 return PyLong_FromUnsignedLong(total);
1483 }
1484
1485 /* find midpoint of range(start, stop), rounded up to next odd number. */
1486 midpoint = (start + num_operands) | 1;
1487 left = factorial_partial_product(start, midpoint,
1488 bit_length(midpoint - 2));
1489 if (left == NULL)
1490 goto error;
1491 right = factorial_partial_product(midpoint, stop, max_bits);
1492 if (right == NULL)
1493 goto error;
1494 result = PyNumber_Multiply(left, right);
1495
1496 error:
1497 Py_XDECREF(left);
1498 Py_XDECREF(right);
1499 return result;
1500}
1501
1502/* factorial_odd_part: compute the odd part of factorial(n). */
1503
1504static PyObject *
1505factorial_odd_part(unsigned long n)
1506{
1507 long i;
1508 unsigned long v, lower, upper;
1509 PyObject *partial, *tmp, *inner, *outer;
1510
1511 inner = PyLong_FromLong(1);
1512 if (inner == NULL)
1513 return NULL;
1514 outer = inner;
1515 Py_INCREF(outer);
1516
1517 upper = 3;
1518 for (i = bit_length(n) - 2; i >= 0; i--) {
1519 v = n >> i;
1520 if (v <= 2)
1521 continue;
1522 lower = upper;
1523 /* (v + 1) | 1 = least odd integer strictly larger than n / 2**i */
1524 upper = (v + 1) | 1;
1525 /* Here inner is the product of all odd integers j in the range (0,
1526 n/2**(i+1)]. The factorial_partial_product call below gives the
1527 product of all odd integers j in the range (n/2**(i+1), n/2**i]. */
1528 partial = factorial_partial_product(lower, upper, bit_length(upper-2));
1529 /* inner *= partial */
1530 if (partial == NULL)
1531 goto error;
1532 tmp = PyNumber_Multiply(inner, partial);
1533 Py_DECREF(partial);
1534 if (tmp == NULL)
1535 goto error;
1536 Py_DECREF(inner);
1537 inner = tmp;
1538 /* Now inner is the product of all odd integers j in the range (0,
1539 n/2**i], giving the inner product in the formula above. */
1540
1541 /* outer *= inner; */
1542 tmp = PyNumber_Multiply(outer, inner);
1543 if (tmp == NULL)
1544 goto error;
1545 Py_DECREF(outer);
1546 outer = tmp;
1547 }
Mark Dickinson76464492012-10-25 10:46:28 +01001548 Py_DECREF(inner);
1549 return outer;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001550
1551 error:
1552 Py_DECREF(outer);
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001553 Py_DECREF(inner);
Mark Dickinson76464492012-10-25 10:46:28 +01001554 return NULL;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001555}
1556
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001557
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001558/* Lookup table for small factorial values */
1559
1560static const unsigned long SmallFactorials[] = {
1561 1, 1, 2, 6, 24, 120, 720, 5040, 40320,
1562 362880, 3628800, 39916800, 479001600,
1563#if SIZEOF_LONG >= 8
1564 6227020800, 87178291200, 1307674368000,
1565 20922789888000, 355687428096000, 6402373705728000,
1566 121645100408832000, 2432902008176640000
1567#endif
1568};
1569
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001570/*[clinic input]
1571math.factorial
1572
1573 x as arg: object
1574 /
1575
1576Find x!.
1577
1578Raise a ValueError if x is negative or non-integral.
1579[clinic start generated code]*/
1580
Barry Warsaw8b43b191996-12-09 22:32:36 +00001581static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001582math_factorial(PyObject *module, PyObject *arg)
1583/*[clinic end generated code: output=6686f26fae00e9ca input=6d1c8105c0d91fb4]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001584{
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001585 long x;
Mark Dickinson5990d282014-04-10 09:29:39 -04001586 int overflow;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001587 PyObject *result, *odd_part, *two_valuation;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 if (PyFloat_Check(arg)) {
1590 PyObject *lx;
1591 double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
1592 if (!(Py_IS_FINITE(dx) && dx == floor(dx))) {
1593 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001594 "factorial() only accepts integral values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 return NULL;
1596 }
1597 lx = PyLong_FromDouble(dx);
1598 if (lx == NULL)
1599 return NULL;
Mark Dickinson5990d282014-04-10 09:29:39 -04001600 x = PyLong_AsLongAndOverflow(lx, &overflow);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 Py_DECREF(lx);
1602 }
1603 else
Mark Dickinson5990d282014-04-10 09:29:39 -04001604 x = PyLong_AsLongAndOverflow(arg, &overflow);
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001605
Mark Dickinson5990d282014-04-10 09:29:39 -04001606 if (x == -1 && PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 return NULL;
Mark Dickinson5990d282014-04-10 09:29:39 -04001608 }
1609 else if (overflow == 1) {
1610 PyErr_Format(PyExc_OverflowError,
1611 "factorial() argument should not exceed %ld",
1612 LONG_MAX);
1613 return NULL;
1614 }
1615 else if (overflow == -1 || x < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001617 "factorial() not defined for negative values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 return NULL;
1619 }
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001620
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001621 /* use lookup table if x is small */
Victor Stinner63941882011-09-29 00:42:28 +02001622 if (x < (long)Py_ARRAY_LENGTH(SmallFactorials))
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001623 return PyLong_FromUnsignedLong(SmallFactorials[x]);
1624
1625 /* else express in the form odd_part * 2**two_valuation, and compute as
1626 odd_part << two_valuation. */
1627 odd_part = factorial_odd_part(x);
1628 if (odd_part == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 return NULL;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001630 two_valuation = PyLong_FromLong(x - count_set_bits(x));
1631 if (two_valuation == NULL) {
1632 Py_DECREF(odd_part);
1633 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 }
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001635 result = PyNumber_Lshift(odd_part, two_valuation);
1636 Py_DECREF(two_valuation);
1637 Py_DECREF(odd_part);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 return result;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001639}
1640
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001641
1642/*[clinic input]
1643math.trunc
1644
1645 x: object
1646 /
1647
1648Truncates the Real x to the nearest Integral toward 0.
1649
1650Uses the __trunc__ magic method.
1651[clinic start generated code]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001652
1653static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001654math_trunc(PyObject *module, PyObject *x)
1655/*[clinic end generated code: output=34b9697b707e1031 input=2168b34e0a09134d]*/
Christian Heimes400adb02008-02-01 08:12:03 +00001656{
Benjamin Petersonce798522012-01-22 11:24:29 -05001657 _Py_IDENTIFIER(__trunc__);
Benjamin Petersonb0125892010-07-02 13:35:17 +00001658 PyObject *trunc, *result;
Christian Heimes400adb02008-02-01 08:12:03 +00001659
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001660 if (Py_TYPE(x)->tp_dict == NULL) {
1661 if (PyType_Ready(Py_TYPE(x)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 return NULL;
1663 }
Christian Heimes400adb02008-02-01 08:12:03 +00001664
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001665 trunc = _PyObject_LookupSpecial(x, &PyId___trunc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 if (trunc == NULL) {
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001667 if (!PyErr_Occurred())
1668 PyErr_Format(PyExc_TypeError,
1669 "type %.100s doesn't define __trunc__ method",
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001670 Py_TYPE(x)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 return NULL;
1672 }
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001673 result = _PyObject_CallNoArg(trunc);
Benjamin Petersonb0125892010-07-02 13:35:17 +00001674 Py_DECREF(trunc);
1675 return result;
Christian Heimes400adb02008-02-01 08:12:03 +00001676}
1677
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001678
1679/*[clinic input]
1680math.frexp
1681
1682 x: double
1683 /
1684
1685Return the mantissa and exponent of x, as pair (m, e).
1686
1687m is a float and e is an int, such that x = m * 2.**e.
1688If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.
1689[clinic start generated code]*/
Christian Heimes400adb02008-02-01 08:12:03 +00001690
1691static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001692math_frexp_impl(PyObject *module, double x)
1693/*[clinic end generated code: output=03e30d252a15ad4a input=96251c9e208bc6e9]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00001694{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 /* deal with special cases directly, to sidestep platform
1697 differences */
1698 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
1699 i = 0;
1700 }
1701 else {
1702 PyFPE_START_PROTECT("in math_frexp", return 0);
1703 x = frexp(x, &i);
1704 PyFPE_END_PROTECT(x);
1705 }
1706 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001707}
1708
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001709
1710/*[clinic input]
1711math.ldexp
1712
1713 x: double
1714 i: object
1715 /
1716
1717Return x * (2**i).
1718
1719This is essentially the inverse of frexp().
1720[clinic start generated code]*/
Guido van Rossumc6e22901998-12-04 19:26:43 +00001721
Barry Warsaw8b43b191996-12-09 22:32:36 +00001722static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001723math_ldexp_impl(PyObject *module, double x, PyObject *i)
1724/*[clinic end generated code: output=b6892f3c2df9cc6a input=17d5970c1a40a8c1]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00001725{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001726 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 long exp;
1728 int overflow;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001729
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001730 if (PyLong_Check(i)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 /* on overflow, replace exponent with either LONG_MAX
1732 or LONG_MIN, depending on the sign. */
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001733 exp = PyLong_AsLongAndOverflow(i, &overflow);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 if (exp == -1 && PyErr_Occurred())
1735 return NULL;
1736 if (overflow)
1737 exp = overflow < 0 ? LONG_MIN : LONG_MAX;
1738 }
1739 else {
1740 PyErr_SetString(PyExc_TypeError,
Serhiy Storchaka95949422013-08-27 19:40:23 +03001741 "Expected an int as second argument to ldexp.");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 return NULL;
1743 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 if (x == 0. || !Py_IS_FINITE(x)) {
1746 /* NaNs, zeros and infinities are returned unchanged */
1747 r = x;
1748 errno = 0;
1749 } else if (exp > INT_MAX) {
1750 /* overflow */
1751 r = copysign(Py_HUGE_VAL, x);
1752 errno = ERANGE;
1753 } else if (exp < INT_MIN) {
1754 /* underflow to +-0 */
1755 r = copysign(0., x);
1756 errno = 0;
1757 } else {
1758 errno = 0;
1759 PyFPE_START_PROTECT("in math_ldexp", return 0);
1760 r = ldexp(x, (int)exp);
1761 PyFPE_END_PROTECT(r);
1762 if (Py_IS_INFINITY(r))
1763 errno = ERANGE;
1764 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 if (errno && is_error(r))
1767 return NULL;
1768 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001769}
1770
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001771
1772/*[clinic input]
1773math.modf
1774
1775 x: double
1776 /
1777
1778Return the fractional and integer parts of x.
1779
1780Both results carry the sign of x and are floats.
1781[clinic start generated code]*/
Guido van Rossumc6e22901998-12-04 19:26:43 +00001782
Barry Warsaw8b43b191996-12-09 22:32:36 +00001783static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001784math_modf_impl(PyObject *module, double x)
1785/*[clinic end generated code: output=90cee0260014c3c0 input=b4cfb6786afd9035]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00001786{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001787 double y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 /* some platforms don't do the right thing for NaNs and
1789 infinities, so we take care of special cases directly. */
1790 if (!Py_IS_FINITE(x)) {
1791 if (Py_IS_INFINITY(x))
1792 return Py_BuildValue("(dd)", copysign(0., x), x);
1793 else if (Py_IS_NAN(x))
1794 return Py_BuildValue("(dd)", x, x);
1795 }
Christian Heimesa342c012008-04-20 21:01:16 +00001796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 errno = 0;
1798 PyFPE_START_PROTECT("in math_modf", return 0);
1799 x = modf(x, &y);
1800 PyFPE_END_PROTECT(x);
1801 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001802}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001803
Guido van Rossumc6e22901998-12-04 19:26:43 +00001804
Serhiy Storchaka95949422013-08-27 19:40:23 +03001805/* A decent logarithm is easy to compute even for huge ints, but libm can't
Tim Peters78526162001-09-05 00:53:45 +00001806 do that by itself -- loghelper can. func is log or log10, and name is
Serhiy Storchaka95949422013-08-27 19:40:23 +03001807 "log" or "log10". Note that overflow of the result isn't possible: an int
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00001808 can contain no more than INT_MAX * SHIFT bits, so has value certainly less
1809 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 +00001810 small enough to fit in an IEEE single. log and log10 are even smaller.
Serhiy Storchaka95949422013-08-27 19:40:23 +03001811 However, intermediate overflow is possible for an int if the number of bits
1812 in that int is larger than PY_SSIZE_T_MAX. */
Tim Peters78526162001-09-05 00:53:45 +00001813
1814static PyObject*
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001815loghelper(PyObject* arg, double (*func)(double), const char *funcname)
Tim Peters78526162001-09-05 00:53:45 +00001816{
Serhiy Storchaka95949422013-08-27 19:40:23 +03001817 /* If it is int, do it ourselves. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 if (PyLong_Check(arg)) {
Mark Dickinsonc6037172010-09-29 19:06:36 +00001819 double x, result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 Py_ssize_t e;
Mark Dickinsonc6037172010-09-29 19:06:36 +00001821
1822 /* Negative or zero inputs give a ValueError. */
1823 if (Py_SIZE(arg) <= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 PyErr_SetString(PyExc_ValueError,
1825 "math domain error");
1826 return NULL;
1827 }
Mark Dickinsonfa41e602010-09-28 07:22:27 +00001828
Mark Dickinsonc6037172010-09-29 19:06:36 +00001829 x = PyLong_AsDouble(arg);
1830 if (x == -1.0 && PyErr_Occurred()) {
1831 if (!PyErr_ExceptionMatches(PyExc_OverflowError))
1832 return NULL;
1833 /* Here the conversion to double overflowed, but it's possible
1834 to compute the log anyway. Clear the exception and continue. */
1835 PyErr_Clear();
1836 x = _PyLong_Frexp((PyLongObject *)arg, &e);
1837 if (x == -1.0 && PyErr_Occurred())
1838 return NULL;
1839 /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */
1840 result = func(x) + func(2.0) * e;
1841 }
1842 else
1843 /* Successfully converted x to a double. */
1844 result = func(x);
1845 return PyFloat_FromDouble(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 }
Tim Peters78526162001-09-05 00:53:45 +00001847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 /* Else let libm handle it by itself. */
1849 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +00001850}
1851
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001852
1853/*[clinic input]
1854math.log
1855
1856 x: object
1857 [
1858 base: object(c_default="NULL") = math.e
1859 ]
1860 /
1861
1862Return the logarithm of x to the given base.
1863
1864If the base not specified, returns the natural logarithm (base e) of x.
1865[clinic start generated code]*/
1866
Tim Peters78526162001-09-05 00:53:45 +00001867static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001868math_log_impl(PyObject *module, PyObject *x, int group_right_1,
1869 PyObject *base)
1870/*[clinic end generated code: output=7b5a39e526b73fc9 input=0f62d5726cbfebbd]*/
Tim Peters78526162001-09-05 00:53:45 +00001871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 PyObject *num, *den;
1873 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001874
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001875 num = loghelper(x, m_log, "log");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 if (num == NULL || base == NULL)
1877 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 den = loghelper(base, m_log, "log");
1880 if (den == NULL) {
1881 Py_DECREF(num);
1882 return NULL;
1883 }
Raymond Hettinger866964c2002-12-14 19:51:34 +00001884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 ans = PyNumber_TrueDivide(num, den);
1886 Py_DECREF(num);
1887 Py_DECREF(den);
1888 return ans;
Tim Peters78526162001-09-05 00:53:45 +00001889}
1890
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001891
1892/*[clinic input]
1893math.log2
1894
1895 x: object
1896 /
1897
1898Return the base 2 logarithm of x.
1899[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00001900
1901static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001902math_log2(PyObject *module, PyObject *x)
1903/*[clinic end generated code: output=5425899a4d5d6acb input=08321262bae4f39b]*/
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001904{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001905 return loghelper(x, m_log2, "log2");
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001906}
1907
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001908
1909/*[clinic input]
1910math.log10
1911
1912 x: object
1913 /
1914
1915Return the base 10 logarithm of x.
1916[clinic start generated code]*/
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001917
1918static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001919math_log10(PyObject *module, PyObject *x)
1920/*[clinic end generated code: output=be72a64617df9c6f input=b2469d02c6469e53]*/
Tim Peters78526162001-09-05 00:53:45 +00001921{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001922 return loghelper(x, m_log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +00001923}
1924
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001925
1926/*[clinic input]
1927math.fmod
1928
1929 x: double
1930 y: double
1931 /
1932
1933Return fmod(x, y), according to platform C.
1934
1935x % y may differ.
1936[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00001937
Christian Heimes53876d92008-04-19 00:31:39 +00001938static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001939math_fmod_impl(PyObject *module, double x, double y)
1940/*[clinic end generated code: output=7559d794343a27b5 input=4f84caa8cfc26a03]*/
Christian Heimes53876d92008-04-19 00:31:39 +00001941{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001942 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 /* fmod(x, +/-Inf) returns x for finite x. */
1944 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
1945 return PyFloat_FromDouble(x);
1946 errno = 0;
1947 PyFPE_START_PROTECT("in math_fmod", return 0);
1948 r = fmod(x, y);
1949 PyFPE_END_PROTECT(r);
1950 if (Py_IS_NAN(r)) {
1951 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1952 errno = EDOM;
1953 else
1954 errno = 0;
1955 }
1956 if (errno && is_error(r))
1957 return NULL;
1958 else
1959 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00001960}
1961
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001962
1963/*[clinic input]
1964math.hypot
1965
1966 x: double
1967 y: double
1968 /
1969
1970Return the Euclidean distance, sqrt(x*x + y*y).
1971[clinic start generated code]*/
Christian Heimes53876d92008-04-19 00:31:39 +00001972
1973static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001974math_hypot_impl(PyObject *module, double x, double y)
1975/*[clinic end generated code: output=b7686e5be468ef87 input=7f8eea70406474aa]*/
Christian Heimes53876d92008-04-19 00:31:39 +00001976{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001977 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */
1979 if (Py_IS_INFINITY(x))
1980 return PyFloat_FromDouble(fabs(x));
1981 if (Py_IS_INFINITY(y))
1982 return PyFloat_FromDouble(fabs(y));
1983 errno = 0;
1984 PyFPE_START_PROTECT("in math_hypot", return 0);
1985 r = hypot(x, y);
1986 PyFPE_END_PROTECT(r);
1987 if (Py_IS_NAN(r)) {
1988 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1989 errno = EDOM;
1990 else
1991 errno = 0;
1992 }
1993 else if (Py_IS_INFINITY(r)) {
1994 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
1995 errno = ERANGE;
1996 else
1997 errno = 0;
1998 }
1999 if (errno && is_error(r))
2000 return NULL;
2001 else
2002 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00002003}
2004
Christian Heimes53876d92008-04-19 00:31:39 +00002005
2006/* pow can't use math_2, but needs its own wrapper: the problem is
2007 that an infinite result can arise either as a result of overflow
2008 (in which case OverflowError should be raised) or as a result of
2009 e.g. 0.**-5. (for which ValueError needs to be raised.)
2010*/
2011
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002012/*[clinic input]
2013math.pow
Christian Heimes53876d92008-04-19 00:31:39 +00002014
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002015 x: double
2016 y: double
2017 /
2018
2019Return x**y (x to the power of y).
2020[clinic start generated code]*/
2021
2022static PyObject *
2023math_pow_impl(PyObject *module, double x, double y)
2024/*[clinic end generated code: output=fff93e65abccd6b0 input=c26f1f6075088bfd]*/
2025{
2026 double r;
2027 int odd_y;
Christian Heimesa342c012008-04-20 21:01:16 +00002028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 /* deal directly with IEEE specials, to cope with problems on various
2030 platforms whose semantics don't exactly match C99 */
2031 r = 0.; /* silence compiler warning */
2032 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
2033 errno = 0;
2034 if (Py_IS_NAN(x))
2035 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
2036 else if (Py_IS_NAN(y))
2037 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
2038 else if (Py_IS_INFINITY(x)) {
2039 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
2040 if (y > 0.)
2041 r = odd_y ? x : fabs(x);
2042 else if (y == 0.)
2043 r = 1.;
2044 else /* y < 0. */
2045 r = odd_y ? copysign(0., x) : 0.;
2046 }
2047 else if (Py_IS_INFINITY(y)) {
2048 if (fabs(x) == 1.0)
2049 r = 1.;
2050 else if (y > 0. && fabs(x) > 1.0)
2051 r = y;
2052 else if (y < 0. && fabs(x) < 1.0) {
2053 r = -y; /* result is +inf */
2054 if (x == 0.) /* 0**-inf: divide-by-zero */
2055 errno = EDOM;
2056 }
2057 else
2058 r = 0.;
2059 }
2060 }
2061 else {
2062 /* let libm handle finite**finite */
2063 errno = 0;
2064 PyFPE_START_PROTECT("in math_pow", return 0);
2065 r = pow(x, y);
2066 PyFPE_END_PROTECT(r);
2067 /* a NaN result should arise only from (-ve)**(finite
2068 non-integer); in this case we want to raise ValueError. */
2069 if (!Py_IS_FINITE(r)) {
2070 if (Py_IS_NAN(r)) {
2071 errno = EDOM;
2072 }
2073 /*
2074 an infinite result here arises either from:
2075 (A) (+/-0.)**negative (-> divide-by-zero)
2076 (B) overflow of x**y with x and y finite
2077 */
2078 else if (Py_IS_INFINITY(r)) {
2079 if (x == 0.)
2080 errno = EDOM;
2081 else
2082 errno = ERANGE;
2083 }
2084 }
2085 }
Christian Heimes53876d92008-04-19 00:31:39 +00002086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 if (errno && is_error(r))
2088 return NULL;
2089 else
2090 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00002091}
2092
Christian Heimes53876d92008-04-19 00:31:39 +00002093
Christian Heimes072c0f12008-01-03 23:01:04 +00002094static const double degToRad = Py_MATH_PI / 180.0;
2095static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002096
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002097/*[clinic input]
2098math.degrees
2099
2100 x: double
2101 /
2102
2103Convert angle x from radians to degrees.
2104[clinic start generated code]*/
2105
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002106static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002107math_degrees_impl(PyObject *module, double x)
2108/*[clinic end generated code: output=7fea78b294acd12f input=81e016555d6e3660]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002111}
2112
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002113
2114/*[clinic input]
2115math.radians
2116
2117 x: double
2118 /
2119
2120Convert angle x from degrees to radians.
2121[clinic start generated code]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002122
2123static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002124math_radians_impl(PyObject *module, double x)
2125/*[clinic end generated code: output=34daa47caf9b1590 input=91626fc489fe3d63]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002126{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 return PyFloat_FromDouble(x * degToRad);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002128}
2129
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002130
2131/*[clinic input]
2132math.isfinite
2133
2134 x: double
2135 /
2136
2137Return True if x is neither an infinity nor a NaN, and False otherwise.
2138[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002139
Christian Heimes072c0f12008-01-03 23:01:04 +00002140static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002141math_isfinite_impl(PyObject *module, double x)
2142/*[clinic end generated code: output=8ba1f396440c9901 input=46967d254812e54a]*/
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002143{
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002144 return PyBool_FromLong((long)Py_IS_FINITE(x));
2145}
2146
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002147
2148/*[clinic input]
2149math.isnan
2150
2151 x: double
2152 /
2153
2154Return True if x is a NaN (not a number), and False otherwise.
2155[clinic start generated code]*/
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002156
2157static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002158math_isnan_impl(PyObject *module, double x)
2159/*[clinic end generated code: output=f537b4d6df878c3e input=935891e66083f46a]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00002162}
2163
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002164
2165/*[clinic input]
2166math.isinf
2167
2168 x: double
2169 /
2170
2171Return True if x is a positive or negative infinity, and False otherwise.
2172[clinic start generated code]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002173
2174static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002175math_isinf_impl(PyObject *module, double x)
2176/*[clinic end generated code: output=9f00cbec4de7b06b input=32630e4212cf961f]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002177{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00002179}
2180
Christian Heimes072c0f12008-01-03 23:01:04 +00002181
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002182/*[clinic input]
2183math.isclose -> bool
2184
2185 a: double
2186 b: double
2187 *
2188 rel_tol: double = 1e-09
2189 maximum difference for being considered "close", relative to the
2190 magnitude of the input values
2191 abs_tol: double = 0.0
2192 maximum difference for being considered "close", regardless of the
2193 magnitude of the input values
2194
2195Determine whether two floating point numbers are close in value.
2196
2197Return True if a is close in value to b, and False otherwise.
2198
2199For the values to be considered close, the difference between them
2200must be smaller than at least one of the tolerances.
2201
2202-inf, inf and NaN behave similarly to the IEEE 754 Standard. That
2203is, NaN is not close to anything, even itself. inf and -inf are
2204only close to themselves.
2205[clinic start generated code]*/
2206
2207static int
2208math_isclose_impl(PyObject *module, double a, double b, double rel_tol,
2209 double abs_tol)
2210/*[clinic end generated code: output=b73070207511952d input=f28671871ea5bfba]*/
Tal Einatd5519ed2015-05-31 22:05:00 +03002211{
Tal Einatd5519ed2015-05-31 22:05:00 +03002212 double diff = 0.0;
Tal Einatd5519ed2015-05-31 22:05:00 +03002213
2214 /* sanity check on the inputs */
2215 if (rel_tol < 0.0 || abs_tol < 0.0 ) {
2216 PyErr_SetString(PyExc_ValueError,
2217 "tolerances must be non-negative");
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002218 return -1;
Tal Einatd5519ed2015-05-31 22:05:00 +03002219 }
2220
2221 if ( a == b ) {
2222 /* short circuit exact equality -- needed to catch two infinities of
2223 the same sign. And perhaps speeds things up a bit sometimes.
2224 */
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002225 return 1;
Tal Einatd5519ed2015-05-31 22:05:00 +03002226 }
2227
2228 /* This catches the case of two infinities of opposite sign, or
2229 one infinity and one finite number. Two infinities of opposite
2230 sign would otherwise have an infinite relative tolerance.
2231 Two infinities of the same sign are caught by the equality check
2232 above.
2233 */
2234
2235 if (Py_IS_INFINITY(a) || Py_IS_INFINITY(b)) {
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002236 return 0;
Tal Einatd5519ed2015-05-31 22:05:00 +03002237 }
2238
2239 /* now do the regular computation
2240 this is essentially the "weak" test from the Boost library
2241 */
2242
2243 diff = fabs(b - a);
2244
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002245 return (((diff <= fabs(rel_tol * b)) ||
2246 (diff <= fabs(rel_tol * a))) ||
2247 (diff <= abs_tol));
Tal Einatd5519ed2015-05-31 22:05:00 +03002248}
2249
Tal Einatd5519ed2015-05-31 22:05:00 +03002250
Barry Warsaw8b43b191996-12-09 22:32:36 +00002251static PyMethodDef math_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 {"acos", math_acos, METH_O, math_acos_doc},
2253 {"acosh", math_acosh, METH_O, math_acosh_doc},
2254 {"asin", math_asin, METH_O, math_asin_doc},
2255 {"asinh", math_asinh, METH_O, math_asinh_doc},
2256 {"atan", math_atan, METH_O, math_atan_doc},
2257 {"atan2", math_atan2, METH_VARARGS, math_atan2_doc},
2258 {"atanh", math_atanh, METH_O, math_atanh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002259 MATH_CEIL_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 {"copysign", math_copysign, METH_VARARGS, math_copysign_doc},
2261 {"cos", math_cos, METH_O, math_cos_doc},
2262 {"cosh", math_cosh, METH_O, math_cosh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002263 MATH_DEGREES_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 {"erf", math_erf, METH_O, math_erf_doc},
2265 {"erfc", math_erfc, METH_O, math_erfc_doc},
2266 {"exp", math_exp, METH_O, math_exp_doc},
2267 {"expm1", math_expm1, METH_O, math_expm1_doc},
2268 {"fabs", math_fabs, METH_O, math_fabs_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002269 MATH_FACTORIAL_METHODDEF
2270 MATH_FLOOR_METHODDEF
2271 MATH_FMOD_METHODDEF
2272 MATH_FREXP_METHODDEF
2273 MATH_FSUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 {"gamma", math_gamma, METH_O, math_gamma_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002275 MATH_GCD_METHODDEF
2276 MATH_HYPOT_METHODDEF
2277 MATH_ISCLOSE_METHODDEF
2278 MATH_ISFINITE_METHODDEF
2279 MATH_ISINF_METHODDEF
2280 MATH_ISNAN_METHODDEF
2281 MATH_LDEXP_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002283 MATH_LOG_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 {"log1p", math_log1p, METH_O, math_log1p_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002285 MATH_LOG10_METHODDEF
2286 MATH_LOG2_METHODDEF
2287 MATH_MODF_METHODDEF
2288 MATH_POW_METHODDEF
2289 MATH_RADIANS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 {"sin", math_sin, METH_O, math_sin_doc},
2291 {"sinh", math_sinh, METH_O, math_sinh_doc},
2292 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
2293 {"tan", math_tan, METH_O, math_tan_doc},
2294 {"tanh", math_tanh, METH_O, math_tanh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002295 MATH_TRUNC_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002297};
2298
Guido van Rossumc6e22901998-12-04 19:26:43 +00002299
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002300PyDoc_STRVAR(module_doc,
Tim Peters63c94532001-09-04 23:17:42 +00002301"This module is always available. It provides access to the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002302"mathematical functions defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00002303
Martin v. Löwis1a214512008-06-11 05:26:20 +00002304
2305static struct PyModuleDef mathmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 PyModuleDef_HEAD_INIT,
2307 "math",
2308 module_doc,
2309 -1,
2310 math_methods,
2311 NULL,
2312 NULL,
2313 NULL,
2314 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002315};
2316
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002317PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002318PyInit_math(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 PyObject *m;
Tim Petersfe71f812001-08-07 22:10:00 +00002321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 m = PyModule_Create(&mathmodule);
2323 if (m == NULL)
2324 goto finally;
Barry Warsawfc93f751996-12-17 00:47:03 +00002325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
2327 PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
Guido van Rossum0a891d72016-08-15 09:12:52 -07002328 PyModule_AddObject(m, "tau", PyFloat_FromDouble(Py_MATH_TAU)); /* 2pi */
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +00002329 PyModule_AddObject(m, "inf", PyFloat_FromDouble(m_inf()));
2330#if !defined(PY_NO_SHORT_FLOAT_REPR) || defined(Py_NAN)
2331 PyModule_AddObject(m, "nan", PyFloat_FromDouble(m_nan()));
2332#endif
Barry Warsawfc93f751996-12-17 00:47:03 +00002333
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +00002334 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002336}