blob: c19620d6bdc3f717db6247bd07464f03b6852e1f [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 Dickinson9c91eb82010-07-07 16:17:31 +000074static const double logpi = 1.144729885849400174143427351353058711647;
Louie Lu7a264642017-03-31 01:05:10 +080075#if !defined(HAVE_ERF) || !defined(HAVE_ERFC)
76static const double sqrtpi = 1.772453850905516027298167483341145182798;
77#endif /* !defined(HAVE_ERF) || !defined(HAVE_ERFC) */
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000078
79static double
80sinpi(double x)
81{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000082 double y, r;
83 int n;
84 /* this function should only ever be called for finite arguments */
85 assert(Py_IS_FINITE(x));
86 y = fmod(fabs(x), 2.0);
87 n = (int)round(2.0*y);
88 assert(0 <= n && n <= 4);
89 switch (n) {
90 case 0:
91 r = sin(pi*y);
92 break;
93 case 1:
94 r = cos(pi*(y-0.5));
95 break;
96 case 2:
97 /* N.B. -sin(pi*(y-1.0)) is *not* equivalent: it would give
98 -0.0 instead of 0.0 when y == 1.0. */
99 r = sin(pi*(1.0-y));
100 break;
101 case 3:
102 r = -cos(pi*(y-1.5));
103 break;
104 case 4:
105 r = sin(pi*(y-2.0));
106 break;
107 default:
108 assert(0); /* should never get here */
109 r = -1.23e200; /* silence gcc warning */
110 }
111 return copysign(1.0, x)*r;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000112}
113
114/* Implementation of the real gamma function. In extensive but non-exhaustive
115 random tests, this function proved accurate to within <= 10 ulps across the
116 entire float domain. Note that accuracy may depend on the quality of the
117 system math functions, the pow function in particular. Special cases
118 follow C99 annex F. The parameters and method are tailored to platforms
119 whose double format is the IEEE 754 binary64 format.
120
121 Method: for x > 0.0 we use the Lanczos approximation with parameters N=13
122 and g=6.024680040776729583740234375; these parameters are amongst those
123 used by the Boost library. Following Boost (again), we re-express the
124 Lanczos sum as a rational function, and compute it that way. The
125 coefficients below were computed independently using MPFR, and have been
126 double-checked against the coefficients in the Boost source code.
127
128 For x < 0.0 we use the reflection formula.
129
130 There's one minor tweak that deserves explanation: Lanczos' formula for
131 Gamma(x) involves computing pow(x+g-0.5, x-0.5) / exp(x+g-0.5). For many x
132 values, x+g-0.5 can be represented exactly. However, in cases where it
133 can't be represented exactly the small error in x+g-0.5 can be magnified
134 significantly by the pow and exp calls, especially for large x. A cheap
135 correction is to multiply by (1 + e*g/(x+g-0.5)), where e is the error
136 involved in the computation of x+g-0.5 (that is, e = computed value of
137 x+g-0.5 - exact value of x+g-0.5). Here's the proof:
138
139 Correction factor
140 -----------------
141 Write x+g-0.5 = y-e, where y is exactly representable as an IEEE 754
142 double, and e is tiny. Then:
143
144 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) = pow(y-e, x-0.5)/exp(y-e)
145 = pow(y, x-0.5)/exp(y) * C,
146
147 where the correction_factor C is given by
148
149 C = pow(1-e/y, x-0.5) * exp(e)
150
151 Since e is tiny, pow(1-e/y, x-0.5) ~ 1-(x-0.5)*e/y, and exp(x) ~ 1+e, so:
152
153 C ~ (1-(x-0.5)*e/y) * (1+e) ~ 1 + e*(y-(x-0.5))/y
154
155 But y-(x-0.5) = g+e, and g+e ~ g. So we get C ~ 1 + e*g/y, and
156
157 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) ~ pow(y, x-0.5)/exp(y) * (1 + e*g/y),
158
159 Note that for accuracy, when computing r*C it's better to do
160
161 r + e*g/y*r;
162
163 than
164
165 r * (1 + e*g/y);
166
167 since the addition in the latter throws away most of the bits of
168 information in e*g/y.
169*/
170
171#define LANCZOS_N 13
172static const double lanczos_g = 6.024680040776729583740234375;
173static const double lanczos_g_minus_half = 5.524680040776729583740234375;
174static const double lanczos_num_coeffs[LANCZOS_N] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 23531376880.410759688572007674451636754734846804940,
176 42919803642.649098768957899047001988850926355848959,
177 35711959237.355668049440185451547166705960488635843,
178 17921034426.037209699919755754458931112671403265390,
179 6039542586.3520280050642916443072979210699388420708,
180 1439720407.3117216736632230727949123939715485786772,
181 248874557.86205415651146038641322942321632125127801,
182 31426415.585400194380614231628318205362874684987640,
183 2876370.6289353724412254090516208496135991145378768,
184 186056.26539522349504029498971604569928220784236328,
185 8071.6720023658162106380029022722506138218516325024,
186 210.82427775157934587250973392071336271166969580291,
187 2.5066282746310002701649081771338373386264310793408
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000188};
189
190/* denominator is x*(x+1)*...*(x+LANCZOS_N-2) */
191static const double lanczos_den_coeffs[LANCZOS_N] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 0.0, 39916800.0, 120543840.0, 150917976.0, 105258076.0, 45995730.0,
193 13339535.0, 2637558.0, 357423.0, 32670.0, 1925.0, 66.0, 1.0};
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000194
195/* gamma values for small positive integers, 1 though NGAMMA_INTEGRAL */
196#define NGAMMA_INTEGRAL 23
197static const double gamma_integral[NGAMMA_INTEGRAL] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0,
199 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0,
200 1307674368000.0, 20922789888000.0, 355687428096000.0,
201 6402373705728000.0, 121645100408832000.0, 2432902008176640000.0,
202 51090942171709440000.0, 1124000727777607680000.0,
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000203};
204
205/* Lanczos' sum L_g(x), for positive x */
206
207static double
208lanczos_sum(double x)
209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 double num = 0.0, den = 0.0;
211 int i;
212 assert(x > 0.0);
213 /* evaluate the rational function lanczos_sum(x). For large
214 x, the obvious algorithm risks overflow, so we instead
215 rescale the denominator and numerator of the rational
216 function by x**(1-LANCZOS_N) and treat this as a
217 rational function in 1/x. This also reduces the error for
218 larger x values. The choice of cutoff point (5.0 below) is
219 somewhat arbitrary; in tests, smaller cutoff values than
220 this resulted in lower accuracy. */
221 if (x < 5.0) {
222 for (i = LANCZOS_N; --i >= 0; ) {
223 num = num * x + lanczos_num_coeffs[i];
224 den = den * x + lanczos_den_coeffs[i];
225 }
226 }
227 else {
228 for (i = 0; i < LANCZOS_N; i++) {
229 num = num / x + lanczos_num_coeffs[i];
230 den = den / x + lanczos_den_coeffs[i];
231 }
232 }
233 return num/den;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000234}
235
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +0000236/* Constant for +infinity, generated in the same way as float('inf'). */
237
238static double
239m_inf(void)
240{
241#ifndef PY_NO_SHORT_FLOAT_REPR
242 return _Py_dg_infinity(0);
243#else
244 return Py_HUGE_VAL;
245#endif
246}
247
248/* Constant nan value, generated in the same way as float('nan'). */
249/* We don't currently assume that Py_NAN is defined everywhere. */
250
251#if !defined(PY_NO_SHORT_FLOAT_REPR) || defined(Py_NAN)
252
253static double
254m_nan(void)
255{
256#ifndef PY_NO_SHORT_FLOAT_REPR
257 return _Py_dg_stdnan(0);
258#else
259 return Py_NAN;
260#endif
261}
262
263#endif
264
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000265static double
266m_tgamma(double x)
267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 double absx, r, y, z, sqrtpow;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 /* special cases */
271 if (!Py_IS_FINITE(x)) {
272 if (Py_IS_NAN(x) || x > 0.0)
273 return x; /* tgamma(nan) = nan, tgamma(inf) = inf */
274 else {
275 errno = EDOM;
276 return Py_NAN; /* tgamma(-inf) = nan, invalid */
277 }
278 }
279 if (x == 0.0) {
280 errno = EDOM;
Mark Dickinson50203a62011-09-25 15:26:43 +0100281 /* tgamma(+-0.0) = +-inf, divide-by-zero */
282 return copysign(Py_HUGE_VAL, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 /* integer arguments */
286 if (x == floor(x)) {
287 if (x < 0.0) {
288 errno = EDOM; /* tgamma(n) = nan, invalid for */
289 return Py_NAN; /* negative integers n */
290 }
291 if (x <= NGAMMA_INTEGRAL)
292 return gamma_integral[(int)x - 1];
293 }
294 absx = fabs(x);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 /* tiny arguments: tgamma(x) ~ 1/x for x near 0 */
297 if (absx < 1e-20) {
298 r = 1.0/x;
299 if (Py_IS_INFINITY(r))
300 errno = ERANGE;
301 return r;
302 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 /* large arguments: assuming IEEE 754 doubles, tgamma(x) overflows for
305 x > 200, and underflows to +-0.0 for x < -200, not a negative
306 integer. */
307 if (absx > 200.0) {
308 if (x < 0.0) {
309 return 0.0/sinpi(x);
310 }
311 else {
312 errno = ERANGE;
313 return Py_HUGE_VAL;
314 }
315 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 y = absx + lanczos_g_minus_half;
318 /* compute error in sum */
319 if (absx > lanczos_g_minus_half) {
320 /* note: the correction can be foiled by an optimizing
321 compiler that (incorrectly) thinks that an expression like
322 a + b - a - b can be optimized to 0.0. This shouldn't
323 happen in a standards-conforming compiler. */
324 double q = y - absx;
325 z = q - lanczos_g_minus_half;
326 }
327 else {
328 double q = y - lanczos_g_minus_half;
329 z = q - absx;
330 }
331 z = z * lanczos_g / y;
332 if (x < 0.0) {
333 r = -pi / sinpi(absx) / absx * exp(y) / lanczos_sum(absx);
334 r -= z * r;
335 if (absx < 140.0) {
336 r /= pow(y, absx - 0.5);
337 }
338 else {
339 sqrtpow = pow(y, absx / 2.0 - 0.25);
340 r /= sqrtpow;
341 r /= sqrtpow;
342 }
343 }
344 else {
345 r = lanczos_sum(absx) / exp(y);
346 r += z * r;
347 if (absx < 140.0) {
348 r *= pow(y, absx - 0.5);
349 }
350 else {
351 sqrtpow = pow(y, absx / 2.0 - 0.25);
352 r *= sqrtpow;
353 r *= sqrtpow;
354 }
355 }
356 if (Py_IS_INFINITY(r))
357 errno = ERANGE;
358 return r;
Guido van Rossum8832b621991-12-16 15:44:24 +0000359}
360
Christian Heimes53876d92008-04-19 00:31:39 +0000361/*
Mark Dickinson05d2e082009-12-11 20:17:17 +0000362 lgamma: natural log of the absolute value of the Gamma function.
363 For large arguments, Lanczos' formula works extremely well here.
364*/
365
366static double
367m_lgamma(double x)
368{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200369 double r;
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200370 double absx;
Mark Dickinson05d2e082009-12-11 20:17:17 +0000371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 /* special cases */
373 if (!Py_IS_FINITE(x)) {
374 if (Py_IS_NAN(x))
375 return x; /* lgamma(nan) = nan */
376 else
377 return Py_HUGE_VAL; /* lgamma(+-inf) = +inf */
378 }
Mark Dickinson05d2e082009-12-11 20:17:17 +0000379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 /* integer arguments */
381 if (x == floor(x) && x <= 2.0) {
382 if (x <= 0.0) {
383 errno = EDOM; /* lgamma(n) = inf, divide-by-zero for */
384 return Py_HUGE_VAL; /* integers n <= 0 */
385 }
386 else {
387 return 0.0; /* lgamma(1) = lgamma(2) = 0.0 */
388 }
389 }
Mark Dickinson05d2e082009-12-11 20:17:17 +0000390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 absx = fabs(x);
392 /* tiny arguments: lgamma(x) ~ -log(fabs(x)) for small x */
393 if (absx < 1e-20)
394 return -log(absx);
Mark Dickinson05d2e082009-12-11 20:17:17 +0000395
Mark Dickinson9c91eb82010-07-07 16:17:31 +0000396 /* Lanczos' formula. We could save a fraction of a ulp in accuracy by
397 having a second set of numerator coefficients for lanczos_sum that
398 absorbed the exp(-lanczos_g) term, and throwing out the lanczos_g
399 subtraction below; it's probably not worth it. */
400 r = log(lanczos_sum(absx)) - lanczos_g;
401 r += (absx - 0.5) * (log(absx + lanczos_g - 0.5) - 1);
402 if (x < 0.0)
403 /* Use reflection formula to get value for negative x. */
404 r = logpi - log(fabs(sinpi(absx))) - log(absx) - r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 if (Py_IS_INFINITY(r))
406 errno = ERANGE;
407 return r;
Mark Dickinson05d2e082009-12-11 20:17:17 +0000408}
409
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200410#if !defined(HAVE_ERF) || !defined(HAVE_ERFC)
411
Mark Dickinson45f992a2009-12-19 11:20:49 +0000412/*
413 Implementations of the error function erf(x) and the complementary error
414 function erfc(x).
415
Brett Cannon45adb312016-01-15 09:38:24 -0800416 Method: we use a series approximation for erf for small x, and a continued
417 fraction approximation for erfc(x) for larger x;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000418 combined with the relations erf(-x) = -erf(x) and erfc(x) = 1.0 - erf(x),
419 this gives us erf(x) and erfc(x) for all x.
420
421 The series expansion used is:
422
423 erf(x) = x*exp(-x*x)/sqrt(pi) * [
424 2/1 + 4/3 x**2 + 8/15 x**4 + 16/105 x**6 + ...]
425
426 The coefficient of x**(2k-2) here is 4**k*factorial(k)/factorial(2*k).
427 This series converges well for smallish x, but slowly for larger x.
428
429 The continued fraction expansion used is:
430
431 erfc(x) = x*exp(-x*x)/sqrt(pi) * [1/(0.5 + x**2 -) 0.5/(2.5 + x**2 - )
432 3.0/(4.5 + x**2 - ) 7.5/(6.5 + x**2 - ) ...]
433
434 after the first term, the general term has the form:
435
436 k*(k-0.5)/(2*k+0.5 + x**2 - ...).
437
438 This expansion converges fast for larger x, but convergence becomes
439 infinitely slow as x approaches 0.0. The (somewhat naive) continued
440 fraction evaluation algorithm used below also risks overflow for large x;
441 but for large x, erfc(x) == 0.0 to within machine precision. (For
442 example, erfc(30.0) is approximately 2.56e-393).
443
444 Parameters: use series expansion for abs(x) < ERF_SERIES_CUTOFF and
445 continued fraction expansion for ERF_SERIES_CUTOFF <= abs(x) <
446 ERFC_CONTFRAC_CUTOFF. ERFC_SERIES_TERMS and ERFC_CONTFRAC_TERMS are the
447 numbers of terms to use for the relevant expansions. */
448
449#define ERF_SERIES_CUTOFF 1.5
450#define ERF_SERIES_TERMS 25
451#define ERFC_CONTFRAC_CUTOFF 30.0
452#define ERFC_CONTFRAC_TERMS 50
453
454/*
455 Error function, via power series.
456
457 Given a finite float x, return an approximation to erf(x).
458 Converges reasonably fast for small x.
459*/
460
461static double
462m_erf_series(double x)
463{
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000464 double x2, acc, fk, result;
465 int i, saved_errno;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 x2 = x * x;
468 acc = 0.0;
469 fk = (double)ERF_SERIES_TERMS + 0.5;
470 for (i = 0; i < ERF_SERIES_TERMS; i++) {
471 acc = 2.0 + x2 * acc / fk;
472 fk -= 1.0;
473 }
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000474 /* Make sure the exp call doesn't affect errno;
475 see m_erfc_contfrac for more. */
476 saved_errno = errno;
477 result = acc * x * exp(-x2) / sqrtpi;
478 errno = saved_errno;
479 return result;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000480}
481
482/*
483 Complementary error function, via continued fraction expansion.
484
485 Given a positive float x, return an approximation to erfc(x). Converges
486 reasonably fast for x large (say, x > 2.0), and should be safe from
487 overflow if x and nterms are not too large. On an IEEE 754 machine, with x
488 <= 30.0, we're safe up to nterms = 100. For x >= 30.0, erfc(x) is smaller
489 than the smallest representable nonzero float. */
490
491static double
492m_erfc_contfrac(double x)
493{
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000494 double x2, a, da, p, p_last, q, q_last, b, result;
495 int i, saved_errno;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 if (x >= ERFC_CONTFRAC_CUTOFF)
498 return 0.0;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 x2 = x*x;
501 a = 0.0;
502 da = 0.5;
503 p = 1.0; p_last = 0.0;
504 q = da + x2; q_last = 1.0;
505 for (i = 0; i < ERFC_CONTFRAC_TERMS; i++) {
506 double temp;
507 a += da;
508 da += 2.0;
509 b = da + x2;
510 temp = p; p = b*p - a*p_last; p_last = temp;
511 temp = q; q = b*q - a*q_last; q_last = temp;
512 }
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000513 /* Issue #8986: On some platforms, exp sets errno on underflow to zero;
514 save the current errno value so that we can restore it later. */
515 saved_errno = errno;
516 result = p / q * x * exp(-x2) / sqrtpi;
517 errno = saved_errno;
518 return result;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000519}
520
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200521#endif /* !defined(HAVE_ERF) || !defined(HAVE_ERFC) */
522
Mark Dickinson45f992a2009-12-19 11:20:49 +0000523/* Error function erf(x), for general x */
524
525static double
526m_erf(double x)
527{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200528#ifdef HAVE_ERF
529 return erf(x);
530#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 double absx, cf;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 if (Py_IS_NAN(x))
534 return x;
535 absx = fabs(x);
536 if (absx < ERF_SERIES_CUTOFF)
537 return m_erf_series(x);
538 else {
539 cf = m_erfc_contfrac(absx);
540 return x > 0.0 ? 1.0 - cf : cf - 1.0;
541 }
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200542#endif
Mark Dickinson45f992a2009-12-19 11:20:49 +0000543}
544
545/* Complementary error function erfc(x), for general x. */
546
547static double
548m_erfc(double x)
549{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200550#ifdef HAVE_ERFC
551 return erfc(x);
552#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 double absx, cf;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 if (Py_IS_NAN(x))
556 return x;
557 absx = fabs(x);
558 if (absx < ERF_SERIES_CUTOFF)
559 return 1.0 - m_erf_series(x);
560 else {
561 cf = m_erfc_contfrac(absx);
562 return x > 0.0 ? cf : 2.0 - cf;
563 }
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200564#endif
Mark Dickinson45f992a2009-12-19 11:20:49 +0000565}
Mark Dickinson05d2e082009-12-11 20:17:17 +0000566
567/*
Christian Heimese57950f2008-04-21 13:08:03 +0000568 wrapper for atan2 that deals directly with special cases before
569 delegating to the platform libm for the remaining cases. This
570 is necessary to get consistent behaviour across platforms.
571 Windows, FreeBSD and alpha Tru64 are amongst platforms that don't
572 always follow C99.
573*/
574
575static double
576m_atan2(double y, double x)
577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 if (Py_IS_NAN(x) || Py_IS_NAN(y))
579 return Py_NAN;
580 if (Py_IS_INFINITY(y)) {
581 if (Py_IS_INFINITY(x)) {
582 if (copysign(1., x) == 1.)
583 /* atan2(+-inf, +inf) == +-pi/4 */
584 return copysign(0.25*Py_MATH_PI, y);
585 else
586 /* atan2(+-inf, -inf) == +-pi*3/4 */
587 return copysign(0.75*Py_MATH_PI, y);
588 }
589 /* atan2(+-inf, x) == +-pi/2 for finite x */
590 return copysign(0.5*Py_MATH_PI, y);
591 }
592 if (Py_IS_INFINITY(x) || y == 0.) {
593 if (copysign(1., x) == 1.)
594 /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */
595 return copysign(0., y);
596 else
597 /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */
598 return copysign(Py_MATH_PI, y);
599 }
600 return atan2(y, x);
Christian Heimese57950f2008-04-21 13:08:03 +0000601}
602
Mark Dickinsona0ce3752017-04-05 18:34:27 +0100603
604/* IEEE 754-style remainder operation: x - n*y where n*y is the nearest
605 multiple of y to x, taking n even in the case of a tie. Assuming an IEEE 754
606 binary floating-point format, the result is always exact. */
607
608static double
609m_remainder(double x, double y)
610{
611 /* Deal with most common case first. */
612 if (Py_IS_FINITE(x) && Py_IS_FINITE(y)) {
613 double absx, absy, c, m, r;
614
615 if (y == 0.0) {
616 return Py_NAN;
617 }
618
619 absx = fabs(x);
620 absy = fabs(y);
621 m = fmod(absx, absy);
622
623 /*
624 Warning: some subtlety here. What we *want* to know at this point is
625 whether the remainder m is less than, equal to, or greater than half
626 of absy. However, we can't do that comparison directly because we
627 can't be sure that 0.5*absy is representable (the mutiplication
628 might incur precision loss due to underflow). So instead we compare
629 m with the complement c = absy - m: m < 0.5*absy if and only if m <
630 c, and so on. The catch is that absy - m might also not be
631 representable, but it turns out that it doesn't matter:
632
633 - if m > 0.5*absy then absy - m is exactly representable, by
634 Sterbenz's lemma, so m > c
635 - if m == 0.5*absy then again absy - m is exactly representable
636 and m == c
637 - if m < 0.5*absy then either (i) 0.5*absy is exactly representable,
638 in which case 0.5*absy < absy - m, so 0.5*absy <= c and hence m <
639 c, or (ii) absy is tiny, either subnormal or in the lowest normal
640 binade. Then absy - m is exactly representable and again m < c.
641 */
642
643 c = absy - m;
644 if (m < c) {
645 r = m;
646 }
647 else if (m > c) {
648 r = -c;
649 }
650 else {
651 /*
652 Here absx is exactly halfway between two multiples of absy,
653 and we need to choose the even multiple. x now has the form
654
655 absx = n * absy + m
656
657 for some integer n (recalling that m = 0.5*absy at this point).
658 If n is even we want to return m; if n is odd, we need to
659 return -m.
660
661 So
662
663 0.5 * (absx - m) = (n/2) * absy
664
665 and now reducing modulo absy gives us:
666
667 | m, if n is odd
668 fmod(0.5 * (absx - m), absy) = |
669 | 0, if n is even
670
671 Now m - 2.0 * fmod(...) gives the desired result: m
672 if n is even, -m if m is odd.
673
674 Note that all steps in fmod(0.5 * (absx - m), absy)
675 will be computed exactly, with no rounding error
676 introduced.
677 */
678 assert(m == c);
679 r = m - 2.0 * fmod(0.5 * (absx - m), absy);
680 }
681 return copysign(1.0, x) * r;
682 }
683
684 /* Special values. */
685 if (Py_IS_NAN(x)) {
686 return x;
687 }
688 if (Py_IS_NAN(y)) {
689 return y;
690 }
691 if (Py_IS_INFINITY(x)) {
692 return Py_NAN;
693 }
694 assert(Py_IS_INFINITY(y));
695 return x;
696}
697
698
Christian Heimese57950f2008-04-21 13:08:03 +0000699/*
Mark Dickinsone675f082008-12-11 21:56:00 +0000700 Various platforms (Solaris, OpenBSD) do nonstandard things for log(0),
701 log(-ve), log(NaN). Here are wrappers for log and log10 that deal with
702 special values directly, passing positive non-special values through to
703 the system log/log10.
704 */
705
706static double
707m_log(double x)
708{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 if (Py_IS_FINITE(x)) {
710 if (x > 0.0)
711 return log(x);
712 errno = EDOM;
713 if (x == 0.0)
714 return -Py_HUGE_VAL; /* log(0) = -inf */
715 else
716 return Py_NAN; /* log(-ve) = nan */
717 }
718 else if (Py_IS_NAN(x))
719 return x; /* log(nan) = nan */
720 else if (x > 0.0)
721 return x; /* log(inf) = inf */
722 else {
723 errno = EDOM;
724 return Py_NAN; /* log(-inf) = nan */
725 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000726}
727
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200728/*
729 log2: log to base 2.
730
731 Uses an algorithm that should:
Mark Dickinson83b8c0b2011-05-09 08:40:20 +0100732
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200733 (a) produce exact results for powers of 2, and
Mark Dickinson83b8c0b2011-05-09 08:40:20 +0100734 (b) give a monotonic log2 (for positive finite floats),
735 assuming that the system log is monotonic.
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200736*/
737
738static double
739m_log2(double x)
740{
741 if (!Py_IS_FINITE(x)) {
742 if (Py_IS_NAN(x))
743 return x; /* log2(nan) = nan */
744 else if (x > 0.0)
745 return x; /* log2(+inf) = +inf */
746 else {
747 errno = EDOM;
748 return Py_NAN; /* log2(-inf) = nan, invalid-operation */
749 }
750 }
751
752 if (x > 0.0) {
Victor Stinner8f9f8d62011-05-09 12:45:41 +0200753#ifdef HAVE_LOG2
754 return log2(x);
755#else
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200756 double m;
757 int e;
758 m = frexp(x, &e);
759 /* We want log2(m * 2**e) == log(m) / log(2) + e. Care is needed when
760 * x is just greater than 1.0: in that case e is 1, log(m) is negative,
761 * and we get significant cancellation error from the addition of
762 * log(m) / log(2) to e. The slight rewrite of the expression below
763 * avoids this problem.
764 */
765 if (x >= 1.0) {
766 return log(2.0 * m) / log(2.0) + (e - 1);
767 }
768 else {
769 return log(m) / log(2.0) + e;
770 }
Victor Stinner8f9f8d62011-05-09 12:45:41 +0200771#endif
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200772 }
773 else if (x == 0.0) {
774 errno = EDOM;
775 return -Py_HUGE_VAL; /* log2(0) = -inf, divide-by-zero */
776 }
777 else {
778 errno = EDOM;
Mark Dickinson23442582011-05-09 08:05:00 +0100779 return Py_NAN; /* log2(-inf) = nan, invalid-operation */
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200780 }
781}
782
Mark Dickinsone675f082008-12-11 21:56:00 +0000783static double
784m_log10(double x)
785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 if (Py_IS_FINITE(x)) {
787 if (x > 0.0)
788 return log10(x);
789 errno = EDOM;
790 if (x == 0.0)
791 return -Py_HUGE_VAL; /* log10(0) = -inf */
792 else
793 return Py_NAN; /* log10(-ve) = nan */
794 }
795 else if (Py_IS_NAN(x))
796 return x; /* log10(nan) = nan */
797 else if (x > 0.0)
798 return x; /* log10(inf) = inf */
799 else {
800 errno = EDOM;
801 return Py_NAN; /* log10(-inf) = nan */
802 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000803}
804
805
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200806/*[clinic input]
807math.gcd
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300808
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200809 x as a: object
810 y as b: object
811 /
812
813greatest common divisor of x and y
814[clinic start generated code]*/
815
816static PyObject *
817math_gcd_impl(PyObject *module, PyObject *a, PyObject *b)
818/*[clinic end generated code: output=7b2e0c151bd7a5d8 input=c2691e57fb2a98fa]*/
819{
820 PyObject *g;
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300821
822 a = PyNumber_Index(a);
823 if (a == NULL)
824 return NULL;
825 b = PyNumber_Index(b);
826 if (b == NULL) {
827 Py_DECREF(a);
828 return NULL;
829 }
830 g = _PyLong_GCD(a, b);
831 Py_DECREF(a);
832 Py_DECREF(b);
833 return g;
834}
835
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300836
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000837/* Call is_error when errno != 0, and where x is the result libm
838 * returned. is_error will usually set up an exception and return
839 * true (1), but may return false (0) without setting up an exception.
840 */
841static int
842is_error(double x)
843{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 int result = 1; /* presumption of guilt */
845 assert(errno); /* non-zero errno is a precondition for calling */
846 if (errno == EDOM)
847 PyErr_SetString(PyExc_ValueError, "math domain error");
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 else if (errno == ERANGE) {
850 /* ANSI C generally requires libm functions to set ERANGE
851 * on overflow, but also generally *allows* them to set
852 * ERANGE on underflow too. There's no consistency about
853 * the latter across platforms.
854 * Alas, C99 never requires that errno be set.
855 * Here we suppress the underflow errors (libm functions
856 * should return a zero on underflow, and +- HUGE_VAL on
857 * overflow, so testing the result for zero suffices to
858 * distinguish the cases).
859 *
860 * On some platforms (Ubuntu/ia64) it seems that errno can be
861 * set to ERANGE for subnormal results that do *not* underflow
862 * to zero. So to be safe, we'll ignore ERANGE whenever the
863 * function result is less than one in absolute value.
864 */
865 if (fabs(x) < 1.0)
866 result = 0;
867 else
868 PyErr_SetString(PyExc_OverflowError,
869 "math range error");
870 }
871 else
872 /* Unexpected math error */
873 PyErr_SetFromErrno(PyExc_ValueError);
874 return result;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000875}
876
Mark Dickinsone675f082008-12-11 21:56:00 +0000877/*
Christian Heimes53876d92008-04-19 00:31:39 +0000878 math_1 is used to wrap a libm function f that takes a double
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200879 argument and returns a double.
Christian Heimes53876d92008-04-19 00:31:39 +0000880
881 The error reporting follows these rules, which are designed to do
882 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
883 platforms.
884
885 - a NaN result from non-NaN inputs causes ValueError to be raised
886 - an infinite result from finite inputs causes OverflowError to be
887 raised if can_overflow is 1, or raises ValueError if can_overflow
888 is 0.
889 - if the result is finite and errno == EDOM then ValueError is
890 raised
891 - if the result is finite and nonzero and errno == ERANGE then
892 OverflowError is raised
893
894 The last rule is used to catch overflow on platforms which follow
895 C89 but for which HUGE_VAL is not an infinity.
896
897 For the majority of one-argument functions these rules are enough
898 to ensure that Python's functions behave as specified in 'Annex F'
899 of the C99 standard, with the 'invalid' and 'divide-by-zero'
900 floating-point exceptions mapping to Python's ValueError and the
901 'overflow' floating-point exception mapping to OverflowError.
902 math_1 only works for functions that don't have singularities *and*
903 the possibility of overflow; fortunately, that covers everything we
904 care about right now.
905*/
906
Barry Warsaw8b43b191996-12-09 22:32:36 +0000907static PyObject *
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000908math_1_to_whatever(PyObject *arg, double (*func) (double),
Christian Heimes53876d92008-04-19 00:31:39 +0000909 PyObject *(*from_double_func) (double),
910 int can_overflow)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000911{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 double x, r;
913 x = PyFloat_AsDouble(arg);
914 if (x == -1.0 && PyErr_Occurred())
915 return NULL;
916 errno = 0;
917 PyFPE_START_PROTECT("in math_1", return 0);
918 r = (*func)(x);
919 PyFPE_END_PROTECT(r);
920 if (Py_IS_NAN(r) && !Py_IS_NAN(x)) {
921 PyErr_SetString(PyExc_ValueError,
922 "math domain error"); /* invalid arg */
923 return NULL;
924 }
925 if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) {
Benjamin Peterson2354a752012-03-13 16:13:09 -0500926 if (can_overflow)
927 PyErr_SetString(PyExc_OverflowError,
928 "math range error"); /* overflow */
929 else
930 PyErr_SetString(PyExc_ValueError,
931 "math domain error"); /* singularity */
932 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 }
934 if (Py_IS_FINITE(r) && errno && is_error(r))
935 /* this branch unnecessary on most platforms */
936 return NULL;
Mark Dickinsonde429622008-05-01 00:19:23 +0000937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 return (*from_double_func)(r);
Christian Heimes53876d92008-04-19 00:31:39 +0000939}
940
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000941/* variant of math_1, to be used when the function being wrapped is known to
942 set errno properly (that is, errno = EDOM for invalid or divide-by-zero,
943 errno = ERANGE for overflow). */
944
945static PyObject *
946math_1a(PyObject *arg, double (*func) (double))
947{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 double x, r;
949 x = PyFloat_AsDouble(arg);
950 if (x == -1.0 && PyErr_Occurred())
951 return NULL;
952 errno = 0;
953 PyFPE_START_PROTECT("in math_1a", return 0);
954 r = (*func)(x);
955 PyFPE_END_PROTECT(r);
956 if (errno && is_error(r))
957 return NULL;
958 return PyFloat_FromDouble(r);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000959}
960
Christian Heimes53876d92008-04-19 00:31:39 +0000961/*
962 math_2 is used to wrap a libm function f that takes two double
963 arguments and returns a double.
964
965 The error reporting follows these rules, which are designed to do
966 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
967 platforms.
968
969 - a NaN result from non-NaN inputs causes ValueError to be raised
970 - an infinite result from finite inputs causes OverflowError to be
971 raised.
972 - if the result is finite and errno == EDOM then ValueError is
973 raised
974 - if the result is finite and nonzero and errno == ERANGE then
975 OverflowError is raised
976
977 The last rule is used to catch overflow on platforms which follow
978 C89 but for which HUGE_VAL is not an infinity.
979
980 For most two-argument functions (copysign, fmod, hypot, atan2)
981 these rules are enough to ensure that Python's functions behave as
982 specified in 'Annex F' of the C99 standard, with the 'invalid' and
983 'divide-by-zero' floating-point exceptions mapping to Python's
984 ValueError and the 'overflow' floating-point exception mapping to
985 OverflowError.
986*/
987
988static PyObject *
989math_1(PyObject *arg, double (*func) (double), int can_overflow)
990{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow);
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000992}
993
994static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000995math_1_to_int(PyObject *arg, double (*func) (double), int can_overflow)
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000996{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 return math_1_to_whatever(arg, func, PyLong_FromDouble, can_overflow);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000998}
999
Barry Warsaw8b43b191996-12-09 22:32:36 +00001000static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001001math_2(PyObject *args, double (*func) (double, double), const char *funcname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001002{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 PyObject *ox, *oy;
1004 double x, y, r;
1005 if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy))
1006 return NULL;
1007 x = PyFloat_AsDouble(ox);
1008 y = PyFloat_AsDouble(oy);
1009 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1010 return NULL;
1011 errno = 0;
1012 PyFPE_START_PROTECT("in math_2", return 0);
1013 r = (*func)(x, y);
1014 PyFPE_END_PROTECT(r);
1015 if (Py_IS_NAN(r)) {
1016 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1017 errno = EDOM;
1018 else
1019 errno = 0;
1020 }
1021 else if (Py_IS_INFINITY(r)) {
1022 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
1023 errno = ERANGE;
1024 else
1025 errno = 0;
1026 }
1027 if (errno && is_error(r))
1028 return NULL;
1029 else
1030 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001031}
1032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033#define FUNC1(funcname, func, can_overflow, docstring) \
1034 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
1035 return math_1(args, func, can_overflow); \
1036 }\
1037 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039#define FUNC1A(funcname, func, docstring) \
1040 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
1041 return math_1a(args, func); \
1042 }\
1043 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001044
Fred Drake40c48682000-07-03 18:11:56 +00001045#define FUNC2(funcname, func, docstring) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
1047 return math_2(args, func, #funcname); \
1048 }\
1049 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001050
Christian Heimes53876d92008-04-19 00:31:39 +00001051FUNC1(acos, acos, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001052 "acos($module, x, /)\n--\n\n"
1053 "Return the arc cosine (measured in radians) of x.")
Mark Dickinsonf3718592009-12-21 15:27:41 +00001054FUNC1(acosh, m_acosh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001055 "acosh($module, x, /)\n--\n\n"
1056 "Return the inverse hyperbolic cosine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001057FUNC1(asin, asin, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001058 "asin($module, x, /)\n--\n\n"
1059 "Return the arc sine (measured in radians) of x.")
Mark Dickinsonf3718592009-12-21 15:27:41 +00001060FUNC1(asinh, m_asinh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001061 "asinh($module, x, /)\n--\n\n"
1062 "Return the inverse hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001063FUNC1(atan, atan, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001064 "atan($module, x, /)\n--\n\n"
1065 "Return the arc tangent (measured in radians) of x.")
Christian Heimese57950f2008-04-21 13:08:03 +00001066FUNC2(atan2, m_atan2,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001067 "atan2($module, y, x, /)\n--\n\n"
1068 "Return the arc tangent (measured in radians) of y/x.\n\n"
Tim Petersfe71f812001-08-07 22:10:00 +00001069 "Unlike atan(y/x), the signs of both x and y are considered.")
Mark Dickinsonf3718592009-12-21 15:27:41 +00001070FUNC1(atanh, m_atanh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001071 "atanh($module, x, /)\n--\n\n"
1072 "Return the inverse hyperbolic tangent of x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +00001073
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001074/*[clinic input]
1075math.ceil
1076
1077 x as number: object
1078 /
1079
1080Return the ceiling of x as an Integral.
1081
1082This is the smallest integer >= x.
1083[clinic start generated code]*/
1084
1085static PyObject *
1086math_ceil(PyObject *module, PyObject *number)
1087/*[clinic end generated code: output=6c3b8a78bc201c67 input=2725352806399cab]*/
1088{
Benjamin Petersonce798522012-01-22 11:24:29 -05001089 _Py_IDENTIFIER(__ceil__);
Mark Dickinson6d02d9c2010-07-02 16:05:15 +00001090 PyObject *method, *result;
Guido van Rossum13e05de2007-08-23 22:56:55 +00001091
Benjamin Petersonce798522012-01-22 11:24:29 -05001092 method = _PyObject_LookupSpecial(number, &PyId___ceil__);
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001093 if (method == NULL) {
1094 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 return math_1_to_int(number, ceil, 0);
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001097 }
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001098 result = _PyObject_CallNoArg(method);
Mark Dickinson6d02d9c2010-07-02 16:05:15 +00001099 Py_DECREF(method);
1100 return result;
Guido van Rossum13e05de2007-08-23 22:56:55 +00001101}
1102
Christian Heimes072c0f12008-01-03 23:01:04 +00001103FUNC2(copysign, copysign,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001104 "copysign($module, x, y, /)\n--\n\n"
1105 "Return a float with the magnitude (absolute value) of x but the sign of y.\n\n"
1106 "On platforms that support signed zeros, copysign(1.0, -0.0)\n"
1107 "returns -1.0.\n")
Christian Heimes53876d92008-04-19 00:31:39 +00001108FUNC1(cos, cos, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001109 "cos($module, x, /)\n--\n\n"
1110 "Return the cosine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001111FUNC1(cosh, cosh, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001112 "cosh($module, x, /)\n--\n\n"
1113 "Return the hyperbolic cosine of x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +00001114FUNC1A(erf, m_erf,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001115 "erf($module, x, /)\n--\n\n"
1116 "Error function at x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +00001117FUNC1A(erfc, m_erfc,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001118 "erfc($module, x, /)\n--\n\n"
1119 "Complementary error function at x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001120FUNC1(exp, exp, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001121 "exp($module, x, /)\n--\n\n"
1122 "Return e raised to the power of x.")
Mark Dickinson664b5112009-12-16 20:23:42 +00001123FUNC1(expm1, m_expm1, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001124 "expm1($module, x, /)\n--\n\n"
1125 "Return exp(x)-1.\n\n"
Mark Dickinson664b5112009-12-16 20:23:42 +00001126 "This function avoids the loss of precision involved in the direct "
1127 "evaluation of exp(x)-1 for small x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001128FUNC1(fabs, fabs, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001129 "fabs($module, x, /)\n--\n\n"
1130 "Return the absolute value of the float x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +00001131
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001132/*[clinic input]
1133math.floor
1134
1135 x as number: object
1136 /
1137
1138Return the floor of x as an Integral.
1139
1140This is the largest integer <= x.
1141[clinic start generated code]*/
1142
1143static PyObject *
1144math_floor(PyObject *module, PyObject *number)
1145/*[clinic end generated code: output=c6a65c4884884b8a input=63af6b5d7ebcc3d6]*/
1146{
Benjamin Petersonce798522012-01-22 11:24:29 -05001147 _Py_IDENTIFIER(__floor__);
Benjamin Petersonb0125892010-07-02 13:35:17 +00001148 PyObject *method, *result;
Guido van Rossum13e05de2007-08-23 22:56:55 +00001149
Benjamin Petersonce798522012-01-22 11:24:29 -05001150 method = _PyObject_LookupSpecial(number, &PyId___floor__);
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001151 if (method == NULL) {
1152 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 return math_1_to_int(number, floor, 0);
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001155 }
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001156 result = _PyObject_CallNoArg(method);
Benjamin Petersonb0125892010-07-02 13:35:17 +00001157 Py_DECREF(method);
1158 return result;
Guido van Rossum13e05de2007-08-23 22:56:55 +00001159}
1160
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001161FUNC1A(gamma, m_tgamma,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001162 "gamma($module, x, /)\n--\n\n"
1163 "Gamma function at x.")
Mark Dickinson05d2e082009-12-11 20:17:17 +00001164FUNC1A(lgamma, m_lgamma,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001165 "lgamma($module, x, /)\n--\n\n"
1166 "Natural logarithm of absolute value of Gamma function at x.")
Mark Dickinsonbe64d952010-07-07 16:21:29 +00001167FUNC1(log1p, m_log1p, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001168 "log1p($module, x, /)\n--\n\n"
1169 "Return the natural logarithm of 1+x (base e).\n\n"
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001170 "The result is computed in a way which is accurate for x near zero.")
Mark Dickinsona0ce3752017-04-05 18:34:27 +01001171FUNC2(remainder, m_remainder,
1172 "remainder($module, x, y, /)\n--\n\n"
1173 "Difference between x and the closest integer multiple of y.\n\n"
1174 "Return x - n*y where n*y is the closest integer multiple of y.\n"
1175 "In the case where x is exactly halfway between two multiples of\n"
1176 "y, the nearest even value of n is used. The result is always exact.")
Christian Heimes53876d92008-04-19 00:31:39 +00001177FUNC1(sin, sin, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001178 "sin($module, x, /)\n--\n\n"
1179 "Return the sine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001180FUNC1(sinh, sinh, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001181 "sinh($module, x, /)\n--\n\n"
1182 "Return the hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001183FUNC1(sqrt, sqrt, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001184 "sqrt($module, x, /)\n--\n\n"
1185 "Return the square root of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001186FUNC1(tan, tan, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001187 "tan($module, x, /)\n--\n\n"
1188 "Return the tangent of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001189FUNC1(tanh, tanh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001190 "tanh($module, x, /)\n--\n\n"
1191 "Return the hyperbolic tangent of x.")
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001192
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001193/* Precision summation function as msum() by Raymond Hettinger in
1194 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
1195 enhanced with the exact partials sum and roundoff from Mark
1196 Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
1197 See those links for more details, proofs and other references.
1198
1199 Note 1: IEEE 754R floating point semantics are assumed,
1200 but the current implementation does not re-establish special
1201 value semantics across iterations (i.e. handling -Inf + Inf).
1202
1203 Note 2: No provision is made for intermediate overflow handling;
Georg Brandlf78e02b2008-06-10 17:40:04 +00001204 therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001205 sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
1206 overflow of the first partial sum.
1207
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001208 Note 3: The intermediate values lo, yr, and hi are declared volatile so
1209 aggressive compilers won't algebraically reduce lo to always be exactly 0.0.
Georg Brandlf78e02b2008-06-10 17:40:04 +00001210 Also, the volatile declaration forces the values to be stored in memory as
1211 regular doubles instead of extended long precision (80-bit) values. This
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001212 prevents double rounding because any addition or subtraction of two doubles
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 can be resolved exactly into double-sized hi and lo values. As long as the
Georg Brandlf78e02b2008-06-10 17:40:04 +00001214 hi value gets forced into a double before yr and lo are computed, the extra
1215 bits in downstream extended precision operations (x87 for example) will be
1216 exactly zero and therefore can be losslessly stored back into a double,
1217 thereby preventing double rounding.
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001218
1219 Note 4: A similar implementation is in Modules/cmathmodule.c.
1220 Be sure to update both when making changes.
1221
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001222 Note 5: The signature of math.fsum() differs from builtins.sum()
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001223 because the start argument doesn't make sense in the context of
1224 accurate summation. Since the partials table is collapsed before
1225 returning a result, sum(seq2, start=sum(seq1)) may not equal the
1226 accurate result returned by sum(itertools.chain(seq1, seq2)).
1227*/
1228
1229#define NUM_PARTIALS 32 /* initial partials array size, on stack */
1230
1231/* Extend the partials array p[] by doubling its size. */
1232static int /* non-zero on error */
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001233_fsum_realloc(double **p_ptr, Py_ssize_t n,
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001234 double *ps, Py_ssize_t *m_ptr)
1235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 void *v = NULL;
1237 Py_ssize_t m = *m_ptr;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 m += m; /* double */
Victor Stinner049e5092014-08-17 22:20:00 +02001240 if (n < m && (size_t)m < ((size_t)PY_SSIZE_T_MAX / sizeof(double))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 double *p = *p_ptr;
1242 if (p == ps) {
1243 v = PyMem_Malloc(sizeof(double) * m);
1244 if (v != NULL)
1245 memcpy(v, ps, sizeof(double) * n);
1246 }
1247 else
1248 v = PyMem_Realloc(p, sizeof(double) * m);
1249 }
1250 if (v == NULL) { /* size overflow or no memory */
1251 PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
1252 return 1;
1253 }
1254 *p_ptr = (double*) v;
1255 *m_ptr = m;
1256 return 0;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001257}
1258
1259/* Full precision summation of a sequence of floats.
1260
1261 def msum(iterable):
1262 partials = [] # sorted, non-overlapping partial sums
1263 for x in iterable:
Mark Dickinsonfdb0acc2010-06-25 20:22:24 +00001264 i = 0
1265 for y in partials:
1266 if abs(x) < abs(y):
1267 x, y = y, x
1268 hi = x + y
1269 lo = y - (hi - x)
1270 if lo:
1271 partials[i] = lo
1272 i += 1
1273 x = hi
1274 partials[i:] = [x]
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001275 return sum_exact(partials)
1276
1277 Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
1278 are exactly equal to x+y. The inner loop applies hi/lo summation to each
1279 partial so that the list of partial sums remains exact.
1280
1281 Sum_exact() adds the partial sums exactly and correctly rounds the final
1282 result (using the round-half-to-even rule). The items in partials remain
1283 non-zero, non-special, non-overlapping and strictly increasing in
1284 magnitude, but possibly not all having the same sign.
1285
1286 Depends on IEEE 754 arithmetic guarantees and half-even rounding.
1287*/
1288
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001289/*[clinic input]
1290math.fsum
1291
1292 seq: object
1293 /
1294
1295Return an accurate floating point sum of values in the iterable seq.
1296
1297Assumes IEEE-754 floating point arithmetic.
1298[clinic start generated code]*/
1299
1300static PyObject *
1301math_fsum(PyObject *module, PyObject *seq)
1302/*[clinic end generated code: output=ba5c672b87fe34fc input=c51b7d8caf6f6e82]*/
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 PyObject *item, *iter, *sum = NULL;
1305 Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
1306 double x, y, t, ps[NUM_PARTIALS], *p = ps;
1307 double xsave, special_sum = 0.0, inf_sum = 0.0;
1308 volatile double hi, yr, lo;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 iter = PyObject_GetIter(seq);
1311 if (iter == NULL)
1312 return NULL;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 for(;;) { /* for x in iterable */
1317 assert(0 <= n && n <= m);
1318 assert((m == NUM_PARTIALS && p == ps) ||
1319 (m > NUM_PARTIALS && p != NULL));
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 item = PyIter_Next(iter);
1322 if (item == NULL) {
1323 if (PyErr_Occurred())
1324 goto _fsum_error;
1325 break;
1326 }
1327 x = PyFloat_AsDouble(item);
1328 Py_DECREF(item);
1329 if (PyErr_Occurred())
1330 goto _fsum_error;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 xsave = x;
1333 for (i = j = 0; j < n; j++) { /* for y in partials */
1334 y = p[j];
1335 if (fabs(x) < fabs(y)) {
1336 t = x; x = y; y = t;
1337 }
1338 hi = x + y;
1339 yr = hi - x;
1340 lo = y - yr;
1341 if (lo != 0.0)
1342 p[i++] = lo;
1343 x = hi;
1344 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 n = i; /* ps[i:] = [x] */
1347 if (x != 0.0) {
1348 if (! Py_IS_FINITE(x)) {
1349 /* a nonfinite x could arise either as
1350 a result of intermediate overflow, or
1351 as a result of a nan or inf in the
1352 summands */
1353 if (Py_IS_FINITE(xsave)) {
1354 PyErr_SetString(PyExc_OverflowError,
1355 "intermediate overflow in fsum");
1356 goto _fsum_error;
1357 }
1358 if (Py_IS_INFINITY(xsave))
1359 inf_sum += xsave;
1360 special_sum += xsave;
1361 /* reset partials */
1362 n = 0;
1363 }
1364 else if (n >= m && _fsum_realloc(&p, n, ps, &m))
1365 goto _fsum_error;
1366 else
1367 p[n++] = x;
1368 }
1369 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 if (special_sum != 0.0) {
1372 if (Py_IS_NAN(inf_sum))
1373 PyErr_SetString(PyExc_ValueError,
1374 "-inf + inf in fsum");
1375 else
1376 sum = PyFloat_FromDouble(special_sum);
1377 goto _fsum_error;
1378 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 hi = 0.0;
1381 if (n > 0) {
1382 hi = p[--n];
1383 /* sum_exact(ps, hi) from the top, stop when the sum becomes
1384 inexact. */
1385 while (n > 0) {
1386 x = hi;
1387 y = p[--n];
1388 assert(fabs(y) < fabs(x));
1389 hi = x + y;
1390 yr = hi - x;
1391 lo = y - yr;
1392 if (lo != 0.0)
1393 break;
1394 }
1395 /* Make half-even rounding work across multiple partials.
1396 Needed so that sum([1e-16, 1, 1e16]) will round-up the last
1397 digit to two instead of down to zero (the 1e-16 makes the 1
1398 slightly closer to two). With a potential 1 ULP rounding
1399 error fixed-up, math.fsum() can guarantee commutativity. */
1400 if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
1401 (lo > 0.0 && p[n-1] > 0.0))) {
1402 y = lo * 2.0;
1403 x = hi + y;
1404 yr = x - hi;
1405 if (y == yr)
1406 hi = x;
1407 }
1408 }
1409 sum = PyFloat_FromDouble(hi);
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001410
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001411_fsum_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 PyFPE_END_PROTECT(hi)
1413 Py_DECREF(iter);
1414 if (p != ps)
1415 PyMem_Free(p);
1416 return sum;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001417}
1418
1419#undef NUM_PARTIALS
1420
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001421
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001422/* Return the smallest integer k such that n < 2**k, or 0 if n == 0.
1423 * Equivalent to floor(lg(x))+1. Also equivalent to: bitwidth_of_type -
1424 * count_leading_zero_bits(x)
1425 */
1426
1427/* XXX: This routine does more or less the same thing as
1428 * bits_in_digit() in Objects/longobject.c. Someday it would be nice to
1429 * consolidate them. On BSD, there's a library function called fls()
1430 * that we could use, and GCC provides __builtin_clz().
1431 */
1432
1433static unsigned long
1434bit_length(unsigned long n)
1435{
1436 unsigned long len = 0;
1437 while (n != 0) {
1438 ++len;
1439 n >>= 1;
1440 }
1441 return len;
1442}
1443
1444static unsigned long
1445count_set_bits(unsigned long n)
1446{
1447 unsigned long count = 0;
1448 while (n != 0) {
1449 ++count;
1450 n &= n - 1; /* clear least significant bit */
1451 }
1452 return count;
1453}
1454
1455/* Divide-and-conquer factorial algorithm
1456 *
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07001457 * Based on the formula and pseudo-code provided at:
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001458 * http://www.luschny.de/math/factorial/binarysplitfact.html
1459 *
1460 * Faster algorithms exist, but they're more complicated and depend on
Ezio Melotti9527afd2010-07-08 15:03:02 +00001461 * a fast prime factorization algorithm.
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001462 *
1463 * Notes on the algorithm
1464 * ----------------------
1465 *
1466 * factorial(n) is written in the form 2**k * m, with m odd. k and m are
1467 * computed separately, and then combined using a left shift.
1468 *
1469 * The function factorial_odd_part computes the odd part m (i.e., the greatest
1470 * odd divisor) of factorial(n), using the formula:
1471 *
1472 * factorial_odd_part(n) =
1473 *
1474 * product_{i >= 0} product_{0 < j <= n / 2**i, j odd} j
1475 *
1476 * Example: factorial_odd_part(20) =
1477 *
1478 * (1) *
1479 * (1) *
1480 * (1 * 3 * 5) *
1481 * (1 * 3 * 5 * 7 * 9)
1482 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1483 *
1484 * Here i goes from large to small: the first term corresponds to i=4 (any
1485 * larger i gives an empty product), and the last term corresponds to i=0.
1486 * Each term can be computed from the last by multiplying by the extra odd
1487 * numbers required: e.g., to get from the penultimate term to the last one,
1488 * we multiply by (11 * 13 * 15 * 17 * 19).
1489 *
1490 * To see a hint of why this formula works, here are the same numbers as above
1491 * but with the even parts (i.e., the appropriate powers of 2) included. For
1492 * each subterm in the product for i, we multiply that subterm by 2**i:
1493 *
1494 * factorial(20) =
1495 *
1496 * (16) *
1497 * (8) *
1498 * (4 * 12 * 20) *
1499 * (2 * 6 * 10 * 14 * 18) *
1500 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1501 *
1502 * The factorial_partial_product function computes the product of all odd j in
1503 * range(start, stop) for given start and stop. It's used to compute the
1504 * partial products like (11 * 13 * 15 * 17 * 19) in the example above. It
1505 * operates recursively, repeatedly splitting the range into two roughly equal
1506 * pieces until the subranges are small enough to be computed using only C
1507 * integer arithmetic.
1508 *
1509 * The two-valuation k (i.e., the exponent of the largest power of 2 dividing
1510 * the factorial) is computed independently in the main math_factorial
1511 * function. By standard results, its value is:
1512 *
1513 * two_valuation = n//2 + n//4 + n//8 + ....
1514 *
1515 * It can be shown (e.g., by complete induction on n) that two_valuation is
1516 * equal to n - count_set_bits(n), where count_set_bits(n) gives the number of
1517 * '1'-bits in the binary expansion of n.
1518 */
1519
1520/* factorial_partial_product: Compute product(range(start, stop, 2)) using
1521 * divide and conquer. Assumes start and stop are odd and stop > start.
1522 * max_bits must be >= bit_length(stop - 2). */
1523
1524static PyObject *
1525factorial_partial_product(unsigned long start, unsigned long stop,
1526 unsigned long max_bits)
1527{
1528 unsigned long midpoint, num_operands;
1529 PyObject *left = NULL, *right = NULL, *result = NULL;
1530
1531 /* If the return value will fit an unsigned long, then we can
1532 * multiply in a tight, fast loop where each multiply is O(1).
1533 * Compute an upper bound on the number of bits required to store
1534 * the answer.
1535 *
1536 * Storing some integer z requires floor(lg(z))+1 bits, which is
1537 * conveniently the value returned by bit_length(z). The
1538 * product x*y will require at most
1539 * bit_length(x) + bit_length(y) bits to store, based
1540 * on the idea that lg product = lg x + lg y.
1541 *
1542 * We know that stop - 2 is the largest number to be multiplied. From
1543 * there, we have: bit_length(answer) <= num_operands *
1544 * bit_length(stop - 2)
1545 */
1546
1547 num_operands = (stop - start) / 2;
1548 /* The "num_operands <= 8 * SIZEOF_LONG" check guards against the
1549 * unlikely case of an overflow in num_operands * max_bits. */
1550 if (num_operands <= 8 * SIZEOF_LONG &&
1551 num_operands * max_bits <= 8 * SIZEOF_LONG) {
1552 unsigned long j, total;
1553 for (total = start, j = start + 2; j < stop; j += 2)
1554 total *= j;
1555 return PyLong_FromUnsignedLong(total);
1556 }
1557
1558 /* find midpoint of range(start, stop), rounded up to next odd number. */
1559 midpoint = (start + num_operands) | 1;
1560 left = factorial_partial_product(start, midpoint,
1561 bit_length(midpoint - 2));
1562 if (left == NULL)
1563 goto error;
1564 right = factorial_partial_product(midpoint, stop, max_bits);
1565 if (right == NULL)
1566 goto error;
1567 result = PyNumber_Multiply(left, right);
1568
1569 error:
1570 Py_XDECREF(left);
1571 Py_XDECREF(right);
1572 return result;
1573}
1574
1575/* factorial_odd_part: compute the odd part of factorial(n). */
1576
1577static PyObject *
1578factorial_odd_part(unsigned long n)
1579{
1580 long i;
1581 unsigned long v, lower, upper;
1582 PyObject *partial, *tmp, *inner, *outer;
1583
1584 inner = PyLong_FromLong(1);
1585 if (inner == NULL)
1586 return NULL;
1587 outer = inner;
1588 Py_INCREF(outer);
1589
1590 upper = 3;
1591 for (i = bit_length(n) - 2; i >= 0; i--) {
1592 v = n >> i;
1593 if (v <= 2)
1594 continue;
1595 lower = upper;
1596 /* (v + 1) | 1 = least odd integer strictly larger than n / 2**i */
1597 upper = (v + 1) | 1;
1598 /* Here inner is the product of all odd integers j in the range (0,
1599 n/2**(i+1)]. The factorial_partial_product call below gives the
1600 product of all odd integers j in the range (n/2**(i+1), n/2**i]. */
1601 partial = factorial_partial_product(lower, upper, bit_length(upper-2));
1602 /* inner *= partial */
1603 if (partial == NULL)
1604 goto error;
1605 tmp = PyNumber_Multiply(inner, partial);
1606 Py_DECREF(partial);
1607 if (tmp == NULL)
1608 goto error;
1609 Py_DECREF(inner);
1610 inner = tmp;
1611 /* Now inner is the product of all odd integers j in the range (0,
1612 n/2**i], giving the inner product in the formula above. */
1613
1614 /* outer *= inner; */
1615 tmp = PyNumber_Multiply(outer, inner);
1616 if (tmp == NULL)
1617 goto error;
1618 Py_DECREF(outer);
1619 outer = tmp;
1620 }
Mark Dickinson76464492012-10-25 10:46:28 +01001621 Py_DECREF(inner);
1622 return outer;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001623
1624 error:
1625 Py_DECREF(outer);
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001626 Py_DECREF(inner);
Mark Dickinson76464492012-10-25 10:46:28 +01001627 return NULL;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001628}
1629
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001630
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001631/* Lookup table for small factorial values */
1632
1633static const unsigned long SmallFactorials[] = {
1634 1, 1, 2, 6, 24, 120, 720, 5040, 40320,
1635 362880, 3628800, 39916800, 479001600,
1636#if SIZEOF_LONG >= 8
1637 6227020800, 87178291200, 1307674368000,
1638 20922789888000, 355687428096000, 6402373705728000,
1639 121645100408832000, 2432902008176640000
1640#endif
1641};
1642
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001643/*[clinic input]
1644math.factorial
1645
1646 x as arg: object
1647 /
1648
1649Find x!.
1650
1651Raise a ValueError if x is negative or non-integral.
1652[clinic start generated code]*/
1653
Barry Warsaw8b43b191996-12-09 22:32:36 +00001654static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001655math_factorial(PyObject *module, PyObject *arg)
1656/*[clinic end generated code: output=6686f26fae00e9ca input=6d1c8105c0d91fb4]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001657{
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001658 long x;
Mark Dickinson5990d282014-04-10 09:29:39 -04001659 int overflow;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001660 PyObject *result, *odd_part, *two_valuation;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 if (PyFloat_Check(arg)) {
1663 PyObject *lx;
1664 double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
1665 if (!(Py_IS_FINITE(dx) && dx == floor(dx))) {
1666 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001667 "factorial() only accepts integral values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 return NULL;
1669 }
1670 lx = PyLong_FromDouble(dx);
1671 if (lx == NULL)
1672 return NULL;
Mark Dickinson5990d282014-04-10 09:29:39 -04001673 x = PyLong_AsLongAndOverflow(lx, &overflow);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 Py_DECREF(lx);
1675 }
1676 else
Mark Dickinson5990d282014-04-10 09:29:39 -04001677 x = PyLong_AsLongAndOverflow(arg, &overflow);
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001678
Mark Dickinson5990d282014-04-10 09:29:39 -04001679 if (x == -1 && PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 return NULL;
Mark Dickinson5990d282014-04-10 09:29:39 -04001681 }
1682 else if (overflow == 1) {
1683 PyErr_Format(PyExc_OverflowError,
1684 "factorial() argument should not exceed %ld",
1685 LONG_MAX);
1686 return NULL;
1687 }
1688 else if (overflow == -1 || x < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001690 "factorial() not defined for negative values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 return NULL;
1692 }
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001693
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001694 /* use lookup table if x is small */
Victor Stinner63941882011-09-29 00:42:28 +02001695 if (x < (long)Py_ARRAY_LENGTH(SmallFactorials))
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001696 return PyLong_FromUnsignedLong(SmallFactorials[x]);
1697
1698 /* else express in the form odd_part * 2**two_valuation, and compute as
1699 odd_part << two_valuation. */
1700 odd_part = factorial_odd_part(x);
1701 if (odd_part == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 return NULL;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001703 two_valuation = PyLong_FromLong(x - count_set_bits(x));
1704 if (two_valuation == NULL) {
1705 Py_DECREF(odd_part);
1706 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 }
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001708 result = PyNumber_Lshift(odd_part, two_valuation);
1709 Py_DECREF(two_valuation);
1710 Py_DECREF(odd_part);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 return result;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001712}
1713
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001714
1715/*[clinic input]
1716math.trunc
1717
1718 x: object
1719 /
1720
1721Truncates the Real x to the nearest Integral toward 0.
1722
1723Uses the __trunc__ magic method.
1724[clinic start generated code]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001725
1726static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001727math_trunc(PyObject *module, PyObject *x)
1728/*[clinic end generated code: output=34b9697b707e1031 input=2168b34e0a09134d]*/
Christian Heimes400adb02008-02-01 08:12:03 +00001729{
Benjamin Petersonce798522012-01-22 11:24:29 -05001730 _Py_IDENTIFIER(__trunc__);
Benjamin Petersonb0125892010-07-02 13:35:17 +00001731 PyObject *trunc, *result;
Christian Heimes400adb02008-02-01 08:12:03 +00001732
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001733 if (Py_TYPE(x)->tp_dict == NULL) {
1734 if (PyType_Ready(Py_TYPE(x)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 return NULL;
1736 }
Christian Heimes400adb02008-02-01 08:12:03 +00001737
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001738 trunc = _PyObject_LookupSpecial(x, &PyId___trunc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 if (trunc == NULL) {
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001740 if (!PyErr_Occurred())
1741 PyErr_Format(PyExc_TypeError,
1742 "type %.100s doesn't define __trunc__ method",
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001743 Py_TYPE(x)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 return NULL;
1745 }
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001746 result = _PyObject_CallNoArg(trunc);
Benjamin Petersonb0125892010-07-02 13:35:17 +00001747 Py_DECREF(trunc);
1748 return result;
Christian Heimes400adb02008-02-01 08:12:03 +00001749}
1750
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001751
1752/*[clinic input]
1753math.frexp
1754
1755 x: double
1756 /
1757
1758Return the mantissa and exponent of x, as pair (m, e).
1759
1760m is a float and e is an int, such that x = m * 2.**e.
1761If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.
1762[clinic start generated code]*/
Christian Heimes400adb02008-02-01 08:12:03 +00001763
1764static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001765math_frexp_impl(PyObject *module, double x)
1766/*[clinic end generated code: output=03e30d252a15ad4a input=96251c9e208bc6e9]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00001767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 /* deal with special cases directly, to sidestep platform
1770 differences */
1771 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
1772 i = 0;
1773 }
1774 else {
1775 PyFPE_START_PROTECT("in math_frexp", return 0);
1776 x = frexp(x, &i);
1777 PyFPE_END_PROTECT(x);
1778 }
1779 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001780}
1781
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001782
1783/*[clinic input]
1784math.ldexp
1785
1786 x: double
1787 i: object
1788 /
1789
1790Return x * (2**i).
1791
1792This is essentially the inverse of frexp().
1793[clinic start generated code]*/
Guido van Rossumc6e22901998-12-04 19:26:43 +00001794
Barry Warsaw8b43b191996-12-09 22:32:36 +00001795static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001796math_ldexp_impl(PyObject *module, double x, PyObject *i)
1797/*[clinic end generated code: output=b6892f3c2df9cc6a input=17d5970c1a40a8c1]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00001798{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001799 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 long exp;
1801 int overflow;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001802
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001803 if (PyLong_Check(i)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 /* on overflow, replace exponent with either LONG_MAX
1805 or LONG_MIN, depending on the sign. */
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001806 exp = PyLong_AsLongAndOverflow(i, &overflow);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 if (exp == -1 && PyErr_Occurred())
1808 return NULL;
1809 if (overflow)
1810 exp = overflow < 0 ? LONG_MIN : LONG_MAX;
1811 }
1812 else {
1813 PyErr_SetString(PyExc_TypeError,
Serhiy Storchaka95949422013-08-27 19:40:23 +03001814 "Expected an int as second argument to ldexp.");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 return NULL;
1816 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 if (x == 0. || !Py_IS_FINITE(x)) {
1819 /* NaNs, zeros and infinities are returned unchanged */
1820 r = x;
1821 errno = 0;
1822 } else if (exp > INT_MAX) {
1823 /* overflow */
1824 r = copysign(Py_HUGE_VAL, x);
1825 errno = ERANGE;
1826 } else if (exp < INT_MIN) {
1827 /* underflow to +-0 */
1828 r = copysign(0., x);
1829 errno = 0;
1830 } else {
1831 errno = 0;
1832 PyFPE_START_PROTECT("in math_ldexp", return 0);
1833 r = ldexp(x, (int)exp);
1834 PyFPE_END_PROTECT(r);
1835 if (Py_IS_INFINITY(r))
1836 errno = ERANGE;
1837 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 if (errno && is_error(r))
1840 return NULL;
1841 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001842}
1843
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001844
1845/*[clinic input]
1846math.modf
1847
1848 x: double
1849 /
1850
1851Return the fractional and integer parts of x.
1852
1853Both results carry the sign of x and are floats.
1854[clinic start generated code]*/
Guido van Rossumc6e22901998-12-04 19:26:43 +00001855
Barry Warsaw8b43b191996-12-09 22:32:36 +00001856static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001857math_modf_impl(PyObject *module, double x)
1858/*[clinic end generated code: output=90cee0260014c3c0 input=b4cfb6786afd9035]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00001859{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001860 double y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 /* some platforms don't do the right thing for NaNs and
1862 infinities, so we take care of special cases directly. */
1863 if (!Py_IS_FINITE(x)) {
1864 if (Py_IS_INFINITY(x))
1865 return Py_BuildValue("(dd)", copysign(0., x), x);
1866 else if (Py_IS_NAN(x))
1867 return Py_BuildValue("(dd)", x, x);
1868 }
Christian Heimesa342c012008-04-20 21:01:16 +00001869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 errno = 0;
1871 PyFPE_START_PROTECT("in math_modf", return 0);
1872 x = modf(x, &y);
1873 PyFPE_END_PROTECT(x);
1874 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001875}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001876
Guido van Rossumc6e22901998-12-04 19:26:43 +00001877
Serhiy Storchaka95949422013-08-27 19:40:23 +03001878/* A decent logarithm is easy to compute even for huge ints, but libm can't
Tim Peters78526162001-09-05 00:53:45 +00001879 do that by itself -- loghelper can. func is log or log10, and name is
Serhiy Storchaka95949422013-08-27 19:40:23 +03001880 "log" or "log10". Note that overflow of the result isn't possible: an int
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00001881 can contain no more than INT_MAX * SHIFT bits, so has value certainly less
1882 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 +00001883 small enough to fit in an IEEE single. log and log10 are even smaller.
Serhiy Storchaka95949422013-08-27 19:40:23 +03001884 However, intermediate overflow is possible for an int if the number of bits
1885 in that int is larger than PY_SSIZE_T_MAX. */
Tim Peters78526162001-09-05 00:53:45 +00001886
1887static PyObject*
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001888loghelper(PyObject* arg, double (*func)(double), const char *funcname)
Tim Peters78526162001-09-05 00:53:45 +00001889{
Serhiy Storchaka95949422013-08-27 19:40:23 +03001890 /* If it is int, do it ourselves. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 if (PyLong_Check(arg)) {
Mark Dickinsonc6037172010-09-29 19:06:36 +00001892 double x, result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 Py_ssize_t e;
Mark Dickinsonc6037172010-09-29 19:06:36 +00001894
1895 /* Negative or zero inputs give a ValueError. */
1896 if (Py_SIZE(arg) <= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 PyErr_SetString(PyExc_ValueError,
1898 "math domain error");
1899 return NULL;
1900 }
Mark Dickinsonfa41e602010-09-28 07:22:27 +00001901
Mark Dickinsonc6037172010-09-29 19:06:36 +00001902 x = PyLong_AsDouble(arg);
1903 if (x == -1.0 && PyErr_Occurred()) {
1904 if (!PyErr_ExceptionMatches(PyExc_OverflowError))
1905 return NULL;
1906 /* Here the conversion to double overflowed, but it's possible
1907 to compute the log anyway. Clear the exception and continue. */
1908 PyErr_Clear();
1909 x = _PyLong_Frexp((PyLongObject *)arg, &e);
1910 if (x == -1.0 && PyErr_Occurred())
1911 return NULL;
1912 /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */
1913 result = func(x) + func(2.0) * e;
1914 }
1915 else
1916 /* Successfully converted x to a double. */
1917 result = func(x);
1918 return PyFloat_FromDouble(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 }
Tim Peters78526162001-09-05 00:53:45 +00001920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 /* Else let libm handle it by itself. */
1922 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +00001923}
1924
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001925
1926/*[clinic input]
1927math.log
1928
1929 x: object
1930 [
1931 base: object(c_default="NULL") = math.e
1932 ]
1933 /
1934
1935Return the logarithm of x to the given base.
1936
1937If the base not specified, returns the natural logarithm (base e) of x.
1938[clinic start generated code]*/
1939
Tim Peters78526162001-09-05 00:53:45 +00001940static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001941math_log_impl(PyObject *module, PyObject *x, int group_right_1,
1942 PyObject *base)
1943/*[clinic end generated code: output=7b5a39e526b73fc9 input=0f62d5726cbfebbd]*/
Tim Peters78526162001-09-05 00:53:45 +00001944{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 PyObject *num, *den;
1946 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001947
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001948 num = loghelper(x, m_log, "log");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 if (num == NULL || base == NULL)
1950 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 den = loghelper(base, m_log, "log");
1953 if (den == NULL) {
1954 Py_DECREF(num);
1955 return NULL;
1956 }
Raymond Hettinger866964c2002-12-14 19:51:34 +00001957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 ans = PyNumber_TrueDivide(num, den);
1959 Py_DECREF(num);
1960 Py_DECREF(den);
1961 return ans;
Tim Peters78526162001-09-05 00:53:45 +00001962}
1963
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001964
1965/*[clinic input]
1966math.log2
1967
1968 x: object
1969 /
1970
1971Return the base 2 logarithm of x.
1972[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00001973
1974static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001975math_log2(PyObject *module, PyObject *x)
1976/*[clinic end generated code: output=5425899a4d5d6acb input=08321262bae4f39b]*/
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001977{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001978 return loghelper(x, m_log2, "log2");
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001979}
1980
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001981
1982/*[clinic input]
1983math.log10
1984
1985 x: object
1986 /
1987
1988Return the base 10 logarithm of x.
1989[clinic start generated code]*/
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001990
1991static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001992math_log10(PyObject *module, PyObject *x)
1993/*[clinic end generated code: output=be72a64617df9c6f input=b2469d02c6469e53]*/
Tim Peters78526162001-09-05 00:53:45 +00001994{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001995 return loghelper(x, m_log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +00001996}
1997
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001998
1999/*[clinic input]
2000math.fmod
2001
2002 x: double
2003 y: double
2004 /
2005
2006Return fmod(x, y), according to platform C.
2007
2008x % y may differ.
2009[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002010
Christian Heimes53876d92008-04-19 00:31:39 +00002011static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002012math_fmod_impl(PyObject *module, double x, double y)
2013/*[clinic end generated code: output=7559d794343a27b5 input=4f84caa8cfc26a03]*/
Christian Heimes53876d92008-04-19 00:31:39 +00002014{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002015 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 /* fmod(x, +/-Inf) returns x for finite x. */
2017 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
2018 return PyFloat_FromDouble(x);
2019 errno = 0;
2020 PyFPE_START_PROTECT("in math_fmod", return 0);
2021 r = fmod(x, y);
2022 PyFPE_END_PROTECT(r);
2023 if (Py_IS_NAN(r)) {
2024 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
2025 errno = EDOM;
2026 else
2027 errno = 0;
2028 }
2029 if (errno && is_error(r))
2030 return NULL;
2031 else
2032 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00002033}
2034
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002035
2036/*[clinic input]
2037math.hypot
2038
2039 x: double
2040 y: double
2041 /
2042
2043Return the Euclidean distance, sqrt(x*x + y*y).
2044[clinic start generated code]*/
Christian Heimes53876d92008-04-19 00:31:39 +00002045
2046static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002047math_hypot_impl(PyObject *module, double x, double y)
2048/*[clinic end generated code: output=b7686e5be468ef87 input=7f8eea70406474aa]*/
Christian Heimes53876d92008-04-19 00:31:39 +00002049{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002050 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */
2052 if (Py_IS_INFINITY(x))
2053 return PyFloat_FromDouble(fabs(x));
2054 if (Py_IS_INFINITY(y))
2055 return PyFloat_FromDouble(fabs(y));
2056 errno = 0;
2057 PyFPE_START_PROTECT("in math_hypot", return 0);
2058 r = hypot(x, y);
2059 PyFPE_END_PROTECT(r);
2060 if (Py_IS_NAN(r)) {
2061 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
2062 errno = EDOM;
2063 else
2064 errno = 0;
2065 }
2066 else if (Py_IS_INFINITY(r)) {
2067 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
2068 errno = ERANGE;
2069 else
2070 errno = 0;
2071 }
2072 if (errno && is_error(r))
2073 return NULL;
2074 else
2075 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00002076}
2077
Christian Heimes53876d92008-04-19 00:31:39 +00002078
2079/* pow can't use math_2, but needs its own wrapper: the problem is
2080 that an infinite result can arise either as a result of overflow
2081 (in which case OverflowError should be raised) or as a result of
2082 e.g. 0.**-5. (for which ValueError needs to be raised.)
2083*/
2084
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002085/*[clinic input]
2086math.pow
Christian Heimes53876d92008-04-19 00:31:39 +00002087
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002088 x: double
2089 y: double
2090 /
2091
2092Return x**y (x to the power of y).
2093[clinic start generated code]*/
2094
2095static PyObject *
2096math_pow_impl(PyObject *module, double x, double y)
2097/*[clinic end generated code: output=fff93e65abccd6b0 input=c26f1f6075088bfd]*/
2098{
2099 double r;
2100 int odd_y;
Christian Heimesa342c012008-04-20 21:01:16 +00002101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 /* deal directly with IEEE specials, to cope with problems on various
2103 platforms whose semantics don't exactly match C99 */
2104 r = 0.; /* silence compiler warning */
2105 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
2106 errno = 0;
2107 if (Py_IS_NAN(x))
2108 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
2109 else if (Py_IS_NAN(y))
2110 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
2111 else if (Py_IS_INFINITY(x)) {
2112 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
2113 if (y > 0.)
2114 r = odd_y ? x : fabs(x);
2115 else if (y == 0.)
2116 r = 1.;
2117 else /* y < 0. */
2118 r = odd_y ? copysign(0., x) : 0.;
2119 }
2120 else if (Py_IS_INFINITY(y)) {
2121 if (fabs(x) == 1.0)
2122 r = 1.;
2123 else if (y > 0. && fabs(x) > 1.0)
2124 r = y;
2125 else if (y < 0. && fabs(x) < 1.0) {
2126 r = -y; /* result is +inf */
2127 if (x == 0.) /* 0**-inf: divide-by-zero */
2128 errno = EDOM;
2129 }
2130 else
2131 r = 0.;
2132 }
2133 }
2134 else {
2135 /* let libm handle finite**finite */
2136 errno = 0;
2137 PyFPE_START_PROTECT("in math_pow", return 0);
2138 r = pow(x, y);
2139 PyFPE_END_PROTECT(r);
2140 /* a NaN result should arise only from (-ve)**(finite
2141 non-integer); in this case we want to raise ValueError. */
2142 if (!Py_IS_FINITE(r)) {
2143 if (Py_IS_NAN(r)) {
2144 errno = EDOM;
2145 }
2146 /*
2147 an infinite result here arises either from:
2148 (A) (+/-0.)**negative (-> divide-by-zero)
2149 (B) overflow of x**y with x and y finite
2150 */
2151 else if (Py_IS_INFINITY(r)) {
2152 if (x == 0.)
2153 errno = EDOM;
2154 else
2155 errno = ERANGE;
2156 }
2157 }
2158 }
Christian Heimes53876d92008-04-19 00:31:39 +00002159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 if (errno && is_error(r))
2161 return NULL;
2162 else
2163 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00002164}
2165
Christian Heimes53876d92008-04-19 00:31:39 +00002166
Christian Heimes072c0f12008-01-03 23:01:04 +00002167static const double degToRad = Py_MATH_PI / 180.0;
2168static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002169
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002170/*[clinic input]
2171math.degrees
2172
2173 x: double
2174 /
2175
2176Convert angle x from radians to degrees.
2177[clinic start generated code]*/
2178
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002179static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002180math_degrees_impl(PyObject *module, double x)
2181/*[clinic end generated code: output=7fea78b294acd12f input=81e016555d6e3660]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002182{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002184}
2185
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002186
2187/*[clinic input]
2188math.radians
2189
2190 x: double
2191 /
2192
2193Convert angle x from degrees to radians.
2194[clinic start generated code]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002195
2196static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002197math_radians_impl(PyObject *module, double x)
2198/*[clinic end generated code: output=34daa47caf9b1590 input=91626fc489fe3d63]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 return PyFloat_FromDouble(x * degToRad);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002201}
2202
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002203
2204/*[clinic input]
2205math.isfinite
2206
2207 x: double
2208 /
2209
2210Return True if x is neither an infinity nor a NaN, and False otherwise.
2211[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002212
Christian Heimes072c0f12008-01-03 23:01:04 +00002213static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002214math_isfinite_impl(PyObject *module, double x)
2215/*[clinic end generated code: output=8ba1f396440c9901 input=46967d254812e54a]*/
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002216{
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002217 return PyBool_FromLong((long)Py_IS_FINITE(x));
2218}
2219
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002220
2221/*[clinic input]
2222math.isnan
2223
2224 x: double
2225 /
2226
2227Return True if x is a NaN (not a number), and False otherwise.
2228[clinic start generated code]*/
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002229
2230static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002231math_isnan_impl(PyObject *module, double x)
2232/*[clinic end generated code: output=f537b4d6df878c3e input=935891e66083f46a]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00002235}
2236
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002237
2238/*[clinic input]
2239math.isinf
2240
2241 x: double
2242 /
2243
2244Return True if x is a positive or negative infinity, and False otherwise.
2245[clinic start generated code]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002246
2247static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002248math_isinf_impl(PyObject *module, double x)
2249/*[clinic end generated code: output=9f00cbec4de7b06b input=32630e4212cf961f]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002250{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00002252}
2253
Christian Heimes072c0f12008-01-03 23:01:04 +00002254
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002255/*[clinic input]
2256math.isclose -> bool
2257
2258 a: double
2259 b: double
2260 *
2261 rel_tol: double = 1e-09
2262 maximum difference for being considered "close", relative to the
2263 magnitude of the input values
2264 abs_tol: double = 0.0
2265 maximum difference for being considered "close", regardless of the
2266 magnitude of the input values
2267
2268Determine whether two floating point numbers are close in value.
2269
2270Return True if a is close in value to b, and False otherwise.
2271
2272For the values to be considered close, the difference between them
2273must be smaller than at least one of the tolerances.
2274
2275-inf, inf and NaN behave similarly to the IEEE 754 Standard. That
2276is, NaN is not close to anything, even itself. inf and -inf are
2277only close to themselves.
2278[clinic start generated code]*/
2279
2280static int
2281math_isclose_impl(PyObject *module, double a, double b, double rel_tol,
2282 double abs_tol)
2283/*[clinic end generated code: output=b73070207511952d input=f28671871ea5bfba]*/
Tal Einatd5519ed2015-05-31 22:05:00 +03002284{
Tal Einatd5519ed2015-05-31 22:05:00 +03002285 double diff = 0.0;
Tal Einatd5519ed2015-05-31 22:05:00 +03002286
2287 /* sanity check on the inputs */
2288 if (rel_tol < 0.0 || abs_tol < 0.0 ) {
2289 PyErr_SetString(PyExc_ValueError,
2290 "tolerances must be non-negative");
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002291 return -1;
Tal Einatd5519ed2015-05-31 22:05:00 +03002292 }
2293
2294 if ( a == b ) {
2295 /* short circuit exact equality -- needed to catch two infinities of
2296 the same sign. And perhaps speeds things up a bit sometimes.
2297 */
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002298 return 1;
Tal Einatd5519ed2015-05-31 22:05:00 +03002299 }
2300
2301 /* This catches the case of two infinities of opposite sign, or
2302 one infinity and one finite number. Two infinities of opposite
2303 sign would otherwise have an infinite relative tolerance.
2304 Two infinities of the same sign are caught by the equality check
2305 above.
2306 */
2307
2308 if (Py_IS_INFINITY(a) || Py_IS_INFINITY(b)) {
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002309 return 0;
Tal Einatd5519ed2015-05-31 22:05:00 +03002310 }
2311
2312 /* now do the regular computation
2313 this is essentially the "weak" test from the Boost library
2314 */
2315
2316 diff = fabs(b - a);
2317
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002318 return (((diff <= fabs(rel_tol * b)) ||
2319 (diff <= fabs(rel_tol * a))) ||
2320 (diff <= abs_tol));
Tal Einatd5519ed2015-05-31 22:05:00 +03002321}
2322
Tal Einatd5519ed2015-05-31 22:05:00 +03002323
Barry Warsaw8b43b191996-12-09 22:32:36 +00002324static PyMethodDef math_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 {"acos", math_acos, METH_O, math_acos_doc},
2326 {"acosh", math_acosh, METH_O, math_acosh_doc},
2327 {"asin", math_asin, METH_O, math_asin_doc},
2328 {"asinh", math_asinh, METH_O, math_asinh_doc},
2329 {"atan", math_atan, METH_O, math_atan_doc},
2330 {"atan2", math_atan2, METH_VARARGS, math_atan2_doc},
2331 {"atanh", math_atanh, METH_O, math_atanh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002332 MATH_CEIL_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 {"copysign", math_copysign, METH_VARARGS, math_copysign_doc},
2334 {"cos", math_cos, METH_O, math_cos_doc},
2335 {"cosh", math_cosh, METH_O, math_cosh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002336 MATH_DEGREES_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 {"erf", math_erf, METH_O, math_erf_doc},
2338 {"erfc", math_erfc, METH_O, math_erfc_doc},
2339 {"exp", math_exp, METH_O, math_exp_doc},
2340 {"expm1", math_expm1, METH_O, math_expm1_doc},
2341 {"fabs", math_fabs, METH_O, math_fabs_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002342 MATH_FACTORIAL_METHODDEF
2343 MATH_FLOOR_METHODDEF
2344 MATH_FMOD_METHODDEF
2345 MATH_FREXP_METHODDEF
2346 MATH_FSUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 {"gamma", math_gamma, METH_O, math_gamma_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002348 MATH_GCD_METHODDEF
2349 MATH_HYPOT_METHODDEF
2350 MATH_ISCLOSE_METHODDEF
2351 MATH_ISFINITE_METHODDEF
2352 MATH_ISINF_METHODDEF
2353 MATH_ISNAN_METHODDEF
2354 MATH_LDEXP_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002356 MATH_LOG_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 {"log1p", math_log1p, METH_O, math_log1p_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002358 MATH_LOG10_METHODDEF
2359 MATH_LOG2_METHODDEF
2360 MATH_MODF_METHODDEF
2361 MATH_POW_METHODDEF
2362 MATH_RADIANS_METHODDEF
Mark Dickinsona0ce3752017-04-05 18:34:27 +01002363 {"remainder", math_remainder, METH_VARARGS, math_remainder_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 {"sin", math_sin, METH_O, math_sin_doc},
2365 {"sinh", math_sinh, METH_O, math_sinh_doc},
2366 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
2367 {"tan", math_tan, METH_O, math_tan_doc},
2368 {"tanh", math_tanh, METH_O, math_tanh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002369 MATH_TRUNC_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002371};
2372
Guido van Rossumc6e22901998-12-04 19:26:43 +00002373
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002374PyDoc_STRVAR(module_doc,
Tim Peters63c94532001-09-04 23:17:42 +00002375"This module is always available. It provides access to the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002376"mathematical functions defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00002377
Martin v. Löwis1a214512008-06-11 05:26:20 +00002378
2379static struct PyModuleDef mathmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 PyModuleDef_HEAD_INIT,
2381 "math",
2382 module_doc,
2383 -1,
2384 math_methods,
2385 NULL,
2386 NULL,
2387 NULL,
2388 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002389};
2390
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002391PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002392PyInit_math(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002393{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 PyObject *m;
Tim Petersfe71f812001-08-07 22:10:00 +00002395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 m = PyModule_Create(&mathmodule);
2397 if (m == NULL)
2398 goto finally;
Barry Warsawfc93f751996-12-17 00:47:03 +00002399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
2401 PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
Guido van Rossum0a891d72016-08-15 09:12:52 -07002402 PyModule_AddObject(m, "tau", PyFloat_FromDouble(Py_MATH_TAU)); /* 2pi */
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +00002403 PyModule_AddObject(m, "inf", PyFloat_FromDouble(m_inf()));
2404#if !defined(PY_NO_SHORT_FLOAT_REPR) || defined(Py_NAN)
2405 PyModule_AddObject(m, "nan", PyFloat_FromDouble(m_nan()));
2406#endif
Barry Warsawfc93f751996-12-17 00:47:03 +00002407
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +00002408 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002410}