blob: e956314e27fca384ac34b9c0e18a229a16f32887 [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:
Barry Warsawb2e57942017-09-14 18:13:16 -0700108 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 }
110 return copysign(1.0, x)*r;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000111}
112
113/* Implementation of the real gamma function. In extensive but non-exhaustive
114 random tests, this function proved accurate to within <= 10 ulps across the
115 entire float domain. Note that accuracy may depend on the quality of the
116 system math functions, the pow function in particular. Special cases
117 follow C99 annex F. The parameters and method are tailored to platforms
118 whose double format is the IEEE 754 binary64 format.
119
120 Method: for x > 0.0 we use the Lanczos approximation with parameters N=13
121 and g=6.024680040776729583740234375; these parameters are amongst those
122 used by the Boost library. Following Boost (again), we re-express the
123 Lanczos sum as a rational function, and compute it that way. The
124 coefficients below were computed independently using MPFR, and have been
125 double-checked against the coefficients in the Boost source code.
126
127 For x < 0.0 we use the reflection formula.
128
129 There's one minor tweak that deserves explanation: Lanczos' formula for
130 Gamma(x) involves computing pow(x+g-0.5, x-0.5) / exp(x+g-0.5). For many x
131 values, x+g-0.5 can be represented exactly. However, in cases where it
132 can't be represented exactly the small error in x+g-0.5 can be magnified
133 significantly by the pow and exp calls, especially for large x. A cheap
134 correction is to multiply by (1 + e*g/(x+g-0.5)), where e is the error
135 involved in the computation of x+g-0.5 (that is, e = computed value of
136 x+g-0.5 - exact value of x+g-0.5). Here's the proof:
137
138 Correction factor
139 -----------------
140 Write x+g-0.5 = y-e, where y is exactly representable as an IEEE 754
141 double, and e is tiny. Then:
142
143 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) = pow(y-e, x-0.5)/exp(y-e)
144 = pow(y, x-0.5)/exp(y) * C,
145
146 where the correction_factor C is given by
147
148 C = pow(1-e/y, x-0.5) * exp(e)
149
150 Since e is tiny, pow(1-e/y, x-0.5) ~ 1-(x-0.5)*e/y, and exp(x) ~ 1+e, so:
151
152 C ~ (1-(x-0.5)*e/y) * (1+e) ~ 1 + e*(y-(x-0.5))/y
153
154 But y-(x-0.5) = g+e, and g+e ~ g. So we get C ~ 1 + e*g/y, and
155
156 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) ~ pow(y, x-0.5)/exp(y) * (1 + e*g/y),
157
158 Note that for accuracy, when computing r*C it's better to do
159
160 r + e*g/y*r;
161
162 than
163
164 r * (1 + e*g/y);
165
166 since the addition in the latter throws away most of the bits of
167 information in e*g/y.
168*/
169
170#define LANCZOS_N 13
171static const double lanczos_g = 6.024680040776729583740234375;
172static const double lanczos_g_minus_half = 5.524680040776729583740234375;
173static const double lanczos_num_coeffs[LANCZOS_N] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 23531376880.410759688572007674451636754734846804940,
175 42919803642.649098768957899047001988850926355848959,
176 35711959237.355668049440185451547166705960488635843,
177 17921034426.037209699919755754458931112671403265390,
178 6039542586.3520280050642916443072979210699388420708,
179 1439720407.3117216736632230727949123939715485786772,
180 248874557.86205415651146038641322942321632125127801,
181 31426415.585400194380614231628318205362874684987640,
182 2876370.6289353724412254090516208496135991145378768,
183 186056.26539522349504029498971604569928220784236328,
184 8071.6720023658162106380029022722506138218516325024,
185 210.82427775157934587250973392071336271166969580291,
186 2.5066282746310002701649081771338373386264310793408
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000187};
188
189/* denominator is x*(x+1)*...*(x+LANCZOS_N-2) */
190static const double lanczos_den_coeffs[LANCZOS_N] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 0.0, 39916800.0, 120543840.0, 150917976.0, 105258076.0, 45995730.0,
192 13339535.0, 2637558.0, 357423.0, 32670.0, 1925.0, 66.0, 1.0};
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000193
194/* gamma values for small positive integers, 1 though NGAMMA_INTEGRAL */
195#define NGAMMA_INTEGRAL 23
196static const double gamma_integral[NGAMMA_INTEGRAL] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0,
198 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0,
199 1307674368000.0, 20922789888000.0, 355687428096000.0,
200 6402373705728000.0, 121645100408832000.0, 2432902008176640000.0,
201 51090942171709440000.0, 1124000727777607680000.0,
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000202};
203
204/* Lanczos' sum L_g(x), for positive x */
205
206static double
207lanczos_sum(double x)
208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 double num = 0.0, den = 0.0;
210 int i;
211 assert(x > 0.0);
212 /* evaluate the rational function lanczos_sum(x). For large
213 x, the obvious algorithm risks overflow, so we instead
214 rescale the denominator and numerator of the rational
215 function by x**(1-LANCZOS_N) and treat this as a
216 rational function in 1/x. This also reduces the error for
217 larger x values. The choice of cutoff point (5.0 below) is
218 somewhat arbitrary; in tests, smaller cutoff values than
219 this resulted in lower accuracy. */
220 if (x < 5.0) {
221 for (i = LANCZOS_N; --i >= 0; ) {
222 num = num * x + lanczos_num_coeffs[i];
223 den = den * x + lanczos_den_coeffs[i];
224 }
225 }
226 else {
227 for (i = 0; i < LANCZOS_N; i++) {
228 num = num / x + lanczos_num_coeffs[i];
229 den = den / x + lanczos_den_coeffs[i];
230 }
231 }
232 return num/den;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000233}
234
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +0000235/* Constant for +infinity, generated in the same way as float('inf'). */
236
237static double
238m_inf(void)
239{
240#ifndef PY_NO_SHORT_FLOAT_REPR
241 return _Py_dg_infinity(0);
242#else
243 return Py_HUGE_VAL;
244#endif
245}
246
247/* Constant nan value, generated in the same way as float('nan'). */
248/* We don't currently assume that Py_NAN is defined everywhere. */
249
250#if !defined(PY_NO_SHORT_FLOAT_REPR) || defined(Py_NAN)
251
252static double
253m_nan(void)
254{
255#ifndef PY_NO_SHORT_FLOAT_REPR
256 return _Py_dg_stdnan(0);
257#else
258 return Py_NAN;
259#endif
260}
261
262#endif
263
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000264static double
265m_tgamma(double x)
266{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 double absx, r, y, z, sqrtpow;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 /* special cases */
270 if (!Py_IS_FINITE(x)) {
271 if (Py_IS_NAN(x) || x > 0.0)
272 return x; /* tgamma(nan) = nan, tgamma(inf) = inf */
273 else {
274 errno = EDOM;
275 return Py_NAN; /* tgamma(-inf) = nan, invalid */
276 }
277 }
278 if (x == 0.0) {
279 errno = EDOM;
Mark Dickinson50203a62011-09-25 15:26:43 +0100280 /* tgamma(+-0.0) = +-inf, divide-by-zero */
281 return copysign(Py_HUGE_VAL, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 /* integer arguments */
285 if (x == floor(x)) {
286 if (x < 0.0) {
287 errno = EDOM; /* tgamma(n) = nan, invalid for */
288 return Py_NAN; /* negative integers n */
289 }
290 if (x <= NGAMMA_INTEGRAL)
291 return gamma_integral[(int)x - 1];
292 }
293 absx = fabs(x);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 /* tiny arguments: tgamma(x) ~ 1/x for x near 0 */
296 if (absx < 1e-20) {
297 r = 1.0/x;
298 if (Py_IS_INFINITY(r))
299 errno = ERANGE;
300 return r;
301 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 /* large arguments: assuming IEEE 754 doubles, tgamma(x) overflows for
304 x > 200, and underflows to +-0.0 for x < -200, not a negative
305 integer. */
306 if (absx > 200.0) {
307 if (x < 0.0) {
308 return 0.0/sinpi(x);
309 }
310 else {
311 errno = ERANGE;
312 return Py_HUGE_VAL;
313 }
314 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 y = absx + lanczos_g_minus_half;
317 /* compute error in sum */
318 if (absx > lanczos_g_minus_half) {
319 /* note: the correction can be foiled by an optimizing
320 compiler that (incorrectly) thinks that an expression like
321 a + b - a - b can be optimized to 0.0. This shouldn't
322 happen in a standards-conforming compiler. */
323 double q = y - absx;
324 z = q - lanczos_g_minus_half;
325 }
326 else {
327 double q = y - lanczos_g_minus_half;
328 z = q - absx;
329 }
330 z = z * lanczos_g / y;
331 if (x < 0.0) {
332 r = -pi / sinpi(absx) / absx * exp(y) / lanczos_sum(absx);
333 r -= z * r;
334 if (absx < 140.0) {
335 r /= pow(y, absx - 0.5);
336 }
337 else {
338 sqrtpow = pow(y, absx / 2.0 - 0.25);
339 r /= sqrtpow;
340 r /= sqrtpow;
341 }
342 }
343 else {
344 r = lanczos_sum(absx) / exp(y);
345 r += z * r;
346 if (absx < 140.0) {
347 r *= pow(y, absx - 0.5);
348 }
349 else {
350 sqrtpow = pow(y, absx / 2.0 - 0.25);
351 r *= sqrtpow;
352 r *= sqrtpow;
353 }
354 }
355 if (Py_IS_INFINITY(r))
356 errno = ERANGE;
357 return r;
Guido van Rossum8832b621991-12-16 15:44:24 +0000358}
359
Christian Heimes53876d92008-04-19 00:31:39 +0000360/*
Mark Dickinson05d2e082009-12-11 20:17:17 +0000361 lgamma: natural log of the absolute value of the Gamma function.
362 For large arguments, Lanczos' formula works extremely well here.
363*/
364
365static double
366m_lgamma(double x)
367{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200368 double r;
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200369 double absx;
Mark Dickinson05d2e082009-12-11 20:17:17 +0000370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 /* special cases */
372 if (!Py_IS_FINITE(x)) {
373 if (Py_IS_NAN(x))
374 return x; /* lgamma(nan) = nan */
375 else
376 return Py_HUGE_VAL; /* lgamma(+-inf) = +inf */
377 }
Mark Dickinson05d2e082009-12-11 20:17:17 +0000378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 /* integer arguments */
380 if (x == floor(x) && x <= 2.0) {
381 if (x <= 0.0) {
382 errno = EDOM; /* lgamma(n) = inf, divide-by-zero for */
383 return Py_HUGE_VAL; /* integers n <= 0 */
384 }
385 else {
386 return 0.0; /* lgamma(1) = lgamma(2) = 0.0 */
387 }
388 }
Mark Dickinson05d2e082009-12-11 20:17:17 +0000389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 absx = fabs(x);
391 /* tiny arguments: lgamma(x) ~ -log(fabs(x)) for small x */
392 if (absx < 1e-20)
393 return -log(absx);
Mark Dickinson05d2e082009-12-11 20:17:17 +0000394
Mark Dickinson9c91eb82010-07-07 16:17:31 +0000395 /* Lanczos' formula. We could save a fraction of a ulp in accuracy by
396 having a second set of numerator coefficients for lanczos_sum that
397 absorbed the exp(-lanczos_g) term, and throwing out the lanczos_g
398 subtraction below; it's probably not worth it. */
399 r = log(lanczos_sum(absx)) - lanczos_g;
400 r += (absx - 0.5) * (log(absx + lanczos_g - 0.5) - 1);
401 if (x < 0.0)
402 /* Use reflection formula to get value for negative x. */
403 r = logpi - log(fabs(sinpi(absx))) - log(absx) - r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 if (Py_IS_INFINITY(r))
405 errno = ERANGE;
406 return r;
Mark Dickinson05d2e082009-12-11 20:17:17 +0000407}
408
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200409#if !defined(HAVE_ERF) || !defined(HAVE_ERFC)
410
Mark Dickinson45f992a2009-12-19 11:20:49 +0000411/*
412 Implementations of the error function erf(x) and the complementary error
413 function erfc(x).
414
Brett Cannon45adb312016-01-15 09:38:24 -0800415 Method: we use a series approximation for erf for small x, and a continued
416 fraction approximation for erfc(x) for larger x;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000417 combined with the relations erf(-x) = -erf(x) and erfc(x) = 1.0 - erf(x),
418 this gives us erf(x) and erfc(x) for all x.
419
420 The series expansion used is:
421
422 erf(x) = x*exp(-x*x)/sqrt(pi) * [
423 2/1 + 4/3 x**2 + 8/15 x**4 + 16/105 x**6 + ...]
424
425 The coefficient of x**(2k-2) here is 4**k*factorial(k)/factorial(2*k).
426 This series converges well for smallish x, but slowly for larger x.
427
428 The continued fraction expansion used is:
429
430 erfc(x) = x*exp(-x*x)/sqrt(pi) * [1/(0.5 + x**2 -) 0.5/(2.5 + x**2 - )
431 3.0/(4.5 + x**2 - ) 7.5/(6.5 + x**2 - ) ...]
432
433 after the first term, the general term has the form:
434
435 k*(k-0.5)/(2*k+0.5 + x**2 - ...).
436
437 This expansion converges fast for larger x, but convergence becomes
438 infinitely slow as x approaches 0.0. The (somewhat naive) continued
439 fraction evaluation algorithm used below also risks overflow for large x;
440 but for large x, erfc(x) == 0.0 to within machine precision. (For
441 example, erfc(30.0) is approximately 2.56e-393).
442
443 Parameters: use series expansion for abs(x) < ERF_SERIES_CUTOFF and
444 continued fraction expansion for ERF_SERIES_CUTOFF <= abs(x) <
445 ERFC_CONTFRAC_CUTOFF. ERFC_SERIES_TERMS and ERFC_CONTFRAC_TERMS are the
446 numbers of terms to use for the relevant expansions. */
447
448#define ERF_SERIES_CUTOFF 1.5
449#define ERF_SERIES_TERMS 25
450#define ERFC_CONTFRAC_CUTOFF 30.0
451#define ERFC_CONTFRAC_TERMS 50
452
453/*
454 Error function, via power series.
455
456 Given a finite float x, return an approximation to erf(x).
457 Converges reasonably fast for small x.
458*/
459
460static double
461m_erf_series(double x)
462{
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000463 double x2, acc, fk, result;
464 int i, saved_errno;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 x2 = x * x;
467 acc = 0.0;
468 fk = (double)ERF_SERIES_TERMS + 0.5;
469 for (i = 0; i < ERF_SERIES_TERMS; i++) {
470 acc = 2.0 + x2 * acc / fk;
471 fk -= 1.0;
472 }
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000473 /* Make sure the exp call doesn't affect errno;
474 see m_erfc_contfrac for more. */
475 saved_errno = errno;
476 result = acc * x * exp(-x2) / sqrtpi;
477 errno = saved_errno;
478 return result;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000479}
480
481/*
482 Complementary error function, via continued fraction expansion.
483
484 Given a positive float x, return an approximation to erfc(x). Converges
485 reasonably fast for x large (say, x > 2.0), and should be safe from
486 overflow if x and nterms are not too large. On an IEEE 754 machine, with x
487 <= 30.0, we're safe up to nterms = 100. For x >= 30.0, erfc(x) is smaller
488 than the smallest representable nonzero float. */
489
490static double
491m_erfc_contfrac(double x)
492{
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000493 double x2, a, da, p, p_last, q, q_last, b, result;
494 int i, saved_errno;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 if (x >= ERFC_CONTFRAC_CUTOFF)
497 return 0.0;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 x2 = x*x;
500 a = 0.0;
501 da = 0.5;
502 p = 1.0; p_last = 0.0;
503 q = da + x2; q_last = 1.0;
504 for (i = 0; i < ERFC_CONTFRAC_TERMS; i++) {
505 double temp;
506 a += da;
507 da += 2.0;
508 b = da + x2;
509 temp = p; p = b*p - a*p_last; p_last = temp;
510 temp = q; q = b*q - a*q_last; q_last = temp;
511 }
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000512 /* Issue #8986: On some platforms, exp sets errno on underflow to zero;
513 save the current errno value so that we can restore it later. */
514 saved_errno = errno;
515 result = p / q * x * exp(-x2) / sqrtpi;
516 errno = saved_errno;
517 return result;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000518}
519
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200520#endif /* !defined(HAVE_ERF) || !defined(HAVE_ERFC) */
521
Mark Dickinson45f992a2009-12-19 11:20:49 +0000522/* Error function erf(x), for general x */
523
524static double
525m_erf(double x)
526{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200527#ifdef HAVE_ERF
528 return erf(x);
529#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 double absx, cf;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 if (Py_IS_NAN(x))
533 return x;
534 absx = fabs(x);
535 if (absx < ERF_SERIES_CUTOFF)
536 return m_erf_series(x);
537 else {
538 cf = m_erfc_contfrac(absx);
539 return x > 0.0 ? 1.0 - cf : cf - 1.0;
540 }
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200541#endif
Mark Dickinson45f992a2009-12-19 11:20:49 +0000542}
543
544/* Complementary error function erfc(x), for general x. */
545
546static double
547m_erfc(double x)
548{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200549#ifdef HAVE_ERFC
550 return erfc(x);
551#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 double absx, cf;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 if (Py_IS_NAN(x))
555 return x;
556 absx = fabs(x);
557 if (absx < ERF_SERIES_CUTOFF)
558 return 1.0 - m_erf_series(x);
559 else {
560 cf = m_erfc_contfrac(absx);
561 return x > 0.0 ? cf : 2.0 - cf;
562 }
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200563#endif
Mark Dickinson45f992a2009-12-19 11:20:49 +0000564}
Mark Dickinson05d2e082009-12-11 20:17:17 +0000565
566/*
Christian Heimese57950f2008-04-21 13:08:03 +0000567 wrapper for atan2 that deals directly with special cases before
568 delegating to the platform libm for the remaining cases. This
569 is necessary to get consistent behaviour across platforms.
570 Windows, FreeBSD and alpha Tru64 are amongst platforms that don't
571 always follow C99.
572*/
573
574static double
575m_atan2(double y, double x)
576{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 if (Py_IS_NAN(x) || Py_IS_NAN(y))
578 return Py_NAN;
579 if (Py_IS_INFINITY(y)) {
580 if (Py_IS_INFINITY(x)) {
581 if (copysign(1., x) == 1.)
582 /* atan2(+-inf, +inf) == +-pi/4 */
583 return copysign(0.25*Py_MATH_PI, y);
584 else
585 /* atan2(+-inf, -inf) == +-pi*3/4 */
586 return copysign(0.75*Py_MATH_PI, y);
587 }
588 /* atan2(+-inf, x) == +-pi/2 for finite x */
589 return copysign(0.5*Py_MATH_PI, y);
590 }
591 if (Py_IS_INFINITY(x) || y == 0.) {
592 if (copysign(1., x) == 1.)
593 /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */
594 return copysign(0., y);
595 else
596 /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */
597 return copysign(Py_MATH_PI, y);
598 }
599 return atan2(y, x);
Christian Heimese57950f2008-04-21 13:08:03 +0000600}
601
Mark Dickinsona0ce3752017-04-05 18:34:27 +0100602
603/* IEEE 754-style remainder operation: x - n*y where n*y is the nearest
604 multiple of y to x, taking n even in the case of a tie. Assuming an IEEE 754
605 binary floating-point format, the result is always exact. */
606
607static double
608m_remainder(double x, double y)
609{
610 /* Deal with most common case first. */
611 if (Py_IS_FINITE(x) && Py_IS_FINITE(y)) {
612 double absx, absy, c, m, r;
613
614 if (y == 0.0) {
615 return Py_NAN;
616 }
617
618 absx = fabs(x);
619 absy = fabs(y);
620 m = fmod(absx, absy);
621
622 /*
623 Warning: some subtlety here. What we *want* to know at this point is
624 whether the remainder m is less than, equal to, or greater than half
625 of absy. However, we can't do that comparison directly because we
626 can't be sure that 0.5*absy is representable (the mutiplication
627 might incur precision loss due to underflow). So instead we compare
628 m with the complement c = absy - m: m < 0.5*absy if and only if m <
629 c, and so on. The catch is that absy - m might also not be
630 representable, but it turns out that it doesn't matter:
631
632 - if m > 0.5*absy then absy - m is exactly representable, by
633 Sterbenz's lemma, so m > c
634 - if m == 0.5*absy then again absy - m is exactly representable
635 and m == c
636 - if m < 0.5*absy then either (i) 0.5*absy is exactly representable,
637 in which case 0.5*absy < absy - m, so 0.5*absy <= c and hence m <
638 c, or (ii) absy is tiny, either subnormal or in the lowest normal
639 binade. Then absy - m is exactly representable and again m < c.
640 */
641
642 c = absy - m;
643 if (m < c) {
644 r = m;
645 }
646 else if (m > c) {
647 r = -c;
648 }
649 else {
650 /*
651 Here absx is exactly halfway between two multiples of absy,
652 and we need to choose the even multiple. x now has the form
653
654 absx = n * absy + m
655
656 for some integer n (recalling that m = 0.5*absy at this point).
657 If n is even we want to return m; if n is odd, we need to
658 return -m.
659
660 So
661
662 0.5 * (absx - m) = (n/2) * absy
663
664 and now reducing modulo absy gives us:
665
666 | m, if n is odd
667 fmod(0.5 * (absx - m), absy) = |
668 | 0, if n is even
669
670 Now m - 2.0 * fmod(...) gives the desired result: m
671 if n is even, -m if m is odd.
672
673 Note that all steps in fmod(0.5 * (absx - m), absy)
674 will be computed exactly, with no rounding error
675 introduced.
676 */
677 assert(m == c);
678 r = m - 2.0 * fmod(0.5 * (absx - m), absy);
679 }
680 return copysign(1.0, x) * r;
681 }
682
683 /* Special values. */
684 if (Py_IS_NAN(x)) {
685 return x;
686 }
687 if (Py_IS_NAN(y)) {
688 return y;
689 }
690 if (Py_IS_INFINITY(x)) {
691 return Py_NAN;
692 }
693 assert(Py_IS_INFINITY(y));
694 return x;
695}
696
697
Christian Heimese57950f2008-04-21 13:08:03 +0000698/*
Mark Dickinsone675f082008-12-11 21:56:00 +0000699 Various platforms (Solaris, OpenBSD) do nonstandard things for log(0),
700 log(-ve), log(NaN). Here are wrappers for log and log10 that deal with
701 special values directly, passing positive non-special values through to
702 the system log/log10.
703 */
704
705static double
706m_log(double x)
707{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 if (Py_IS_FINITE(x)) {
709 if (x > 0.0)
710 return log(x);
711 errno = EDOM;
712 if (x == 0.0)
713 return -Py_HUGE_VAL; /* log(0) = -inf */
714 else
715 return Py_NAN; /* log(-ve) = nan */
716 }
717 else if (Py_IS_NAN(x))
718 return x; /* log(nan) = nan */
719 else if (x > 0.0)
720 return x; /* log(inf) = inf */
721 else {
722 errno = EDOM;
723 return Py_NAN; /* log(-inf) = nan */
724 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000725}
726
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200727/*
728 log2: log to base 2.
729
730 Uses an algorithm that should:
Mark Dickinson83b8c0b2011-05-09 08:40:20 +0100731
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200732 (a) produce exact results for powers of 2, and
Mark Dickinson83b8c0b2011-05-09 08:40:20 +0100733 (b) give a monotonic log2 (for positive finite floats),
734 assuming that the system log is monotonic.
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200735*/
736
737static double
738m_log2(double x)
739{
740 if (!Py_IS_FINITE(x)) {
741 if (Py_IS_NAN(x))
742 return x; /* log2(nan) = nan */
743 else if (x > 0.0)
744 return x; /* log2(+inf) = +inf */
745 else {
746 errno = EDOM;
747 return Py_NAN; /* log2(-inf) = nan, invalid-operation */
748 }
749 }
750
751 if (x > 0.0) {
Victor Stinner8f9f8d62011-05-09 12:45:41 +0200752#ifdef HAVE_LOG2
753 return log2(x);
754#else
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200755 double m;
756 int e;
757 m = frexp(x, &e);
758 /* We want log2(m * 2**e) == log(m) / log(2) + e. Care is needed when
759 * x is just greater than 1.0: in that case e is 1, log(m) is negative,
760 * and we get significant cancellation error from the addition of
761 * log(m) / log(2) to e. The slight rewrite of the expression below
762 * avoids this problem.
763 */
764 if (x >= 1.0) {
765 return log(2.0 * m) / log(2.0) + (e - 1);
766 }
767 else {
768 return log(m) / log(2.0) + e;
769 }
Victor Stinner8f9f8d62011-05-09 12:45:41 +0200770#endif
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200771 }
772 else if (x == 0.0) {
773 errno = EDOM;
774 return -Py_HUGE_VAL; /* log2(0) = -inf, divide-by-zero */
775 }
776 else {
777 errno = EDOM;
Mark Dickinson23442582011-05-09 08:05:00 +0100778 return Py_NAN; /* log2(-inf) = nan, invalid-operation */
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200779 }
780}
781
Mark Dickinsone675f082008-12-11 21:56:00 +0000782static double
783m_log10(double x)
784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 if (Py_IS_FINITE(x)) {
786 if (x > 0.0)
787 return log10(x);
788 errno = EDOM;
789 if (x == 0.0)
790 return -Py_HUGE_VAL; /* log10(0) = -inf */
791 else
792 return Py_NAN; /* log10(-ve) = nan */
793 }
794 else if (Py_IS_NAN(x))
795 return x; /* log10(nan) = nan */
796 else if (x > 0.0)
797 return x; /* log10(inf) = inf */
798 else {
799 errno = EDOM;
800 return Py_NAN; /* log10(-inf) = nan */
801 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000802}
803
804
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200805/*[clinic input]
806math.gcd
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300807
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200808 x as a: object
809 y as b: object
810 /
811
812greatest common divisor of x and y
813[clinic start generated code]*/
814
815static PyObject *
816math_gcd_impl(PyObject *module, PyObject *a, PyObject *b)
817/*[clinic end generated code: output=7b2e0c151bd7a5d8 input=c2691e57fb2a98fa]*/
818{
819 PyObject *g;
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300820
821 a = PyNumber_Index(a);
822 if (a == NULL)
823 return NULL;
824 b = PyNumber_Index(b);
825 if (b == NULL) {
826 Py_DECREF(a);
827 return NULL;
828 }
829 g = _PyLong_GCD(a, b);
830 Py_DECREF(a);
831 Py_DECREF(b);
832 return g;
833}
834
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300835
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000836/* Call is_error when errno != 0, and where x is the result libm
837 * returned. is_error will usually set up an exception and return
838 * true (1), but may return false (0) without setting up an exception.
839 */
840static int
841is_error(double x)
842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 int result = 1; /* presumption of guilt */
844 assert(errno); /* non-zero errno is a precondition for calling */
845 if (errno == EDOM)
846 PyErr_SetString(PyExc_ValueError, "math domain error");
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 else if (errno == ERANGE) {
849 /* ANSI C generally requires libm functions to set ERANGE
850 * on overflow, but also generally *allows* them to set
851 * ERANGE on underflow too. There's no consistency about
852 * the latter across platforms.
853 * Alas, C99 never requires that errno be set.
854 * Here we suppress the underflow errors (libm functions
855 * should return a zero on underflow, and +- HUGE_VAL on
856 * overflow, so testing the result for zero suffices to
857 * distinguish the cases).
858 *
859 * On some platforms (Ubuntu/ia64) it seems that errno can be
860 * set to ERANGE for subnormal results that do *not* underflow
861 * to zero. So to be safe, we'll ignore ERANGE whenever the
862 * function result is less than one in absolute value.
863 */
864 if (fabs(x) < 1.0)
865 result = 0;
866 else
867 PyErr_SetString(PyExc_OverflowError,
868 "math range error");
869 }
870 else
871 /* Unexpected math error */
872 PyErr_SetFromErrno(PyExc_ValueError);
873 return result;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000874}
875
Mark Dickinsone675f082008-12-11 21:56:00 +0000876/*
Christian Heimes53876d92008-04-19 00:31:39 +0000877 math_1 is used to wrap a libm function f that takes a double
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200878 argument and returns a double.
Christian Heimes53876d92008-04-19 00:31:39 +0000879
880 The error reporting follows these rules, which are designed to do
881 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
882 platforms.
883
884 - a NaN result from non-NaN inputs causes ValueError to be raised
885 - an infinite result from finite inputs causes OverflowError to be
886 raised if can_overflow is 1, or raises ValueError if can_overflow
887 is 0.
888 - if the result is finite and errno == EDOM then ValueError is
889 raised
890 - if the result is finite and nonzero and errno == ERANGE then
891 OverflowError is raised
892
893 The last rule is used to catch overflow on platforms which follow
894 C89 but for which HUGE_VAL is not an infinity.
895
896 For the majority of one-argument functions these rules are enough
897 to ensure that Python's functions behave as specified in 'Annex F'
898 of the C99 standard, with the 'invalid' and 'divide-by-zero'
899 floating-point exceptions mapping to Python's ValueError and the
900 'overflow' floating-point exception mapping to OverflowError.
901 math_1 only works for functions that don't have singularities *and*
902 the possibility of overflow; fortunately, that covers everything we
903 care about right now.
904*/
905
Barry Warsaw8b43b191996-12-09 22:32:36 +0000906static PyObject *
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000907math_1_to_whatever(PyObject *arg, double (*func) (double),
Christian Heimes53876d92008-04-19 00:31:39 +0000908 PyObject *(*from_double_func) (double),
909 int can_overflow)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 double x, r;
912 x = PyFloat_AsDouble(arg);
913 if (x == -1.0 && PyErr_Occurred())
914 return NULL;
915 errno = 0;
916 PyFPE_START_PROTECT("in math_1", return 0);
917 r = (*func)(x);
918 PyFPE_END_PROTECT(r);
919 if (Py_IS_NAN(r) && !Py_IS_NAN(x)) {
920 PyErr_SetString(PyExc_ValueError,
921 "math domain error"); /* invalid arg */
922 return NULL;
923 }
924 if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) {
Benjamin Peterson2354a752012-03-13 16:13:09 -0500925 if (can_overflow)
926 PyErr_SetString(PyExc_OverflowError,
927 "math range error"); /* overflow */
928 else
929 PyErr_SetString(PyExc_ValueError,
930 "math domain error"); /* singularity */
931 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 }
933 if (Py_IS_FINITE(r) && errno && is_error(r))
934 /* this branch unnecessary on most platforms */
935 return NULL;
Mark Dickinsonde429622008-05-01 00:19:23 +0000936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 return (*from_double_func)(r);
Christian Heimes53876d92008-04-19 00:31:39 +0000938}
939
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000940/* variant of math_1, to be used when the function being wrapped is known to
941 set errno properly (that is, errno = EDOM for invalid or divide-by-zero,
942 errno = ERANGE for overflow). */
943
944static PyObject *
945math_1a(PyObject *arg, double (*func) (double))
946{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 double x, r;
948 x = PyFloat_AsDouble(arg);
949 if (x == -1.0 && PyErr_Occurred())
950 return NULL;
951 errno = 0;
952 PyFPE_START_PROTECT("in math_1a", return 0);
953 r = (*func)(x);
954 PyFPE_END_PROTECT(r);
955 if (errno && is_error(r))
956 return NULL;
957 return PyFloat_FromDouble(r);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000958}
959
Christian Heimes53876d92008-04-19 00:31:39 +0000960/*
961 math_2 is used to wrap a libm function f that takes two double
962 arguments and returns a double.
963
964 The error reporting follows these rules, which are designed to do
965 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
966 platforms.
967
968 - a NaN result from non-NaN inputs causes ValueError to be raised
969 - an infinite result from finite inputs causes OverflowError to be
970 raised.
971 - if the result is finite and errno == EDOM then ValueError is
972 raised
973 - if the result is finite and nonzero and errno == ERANGE then
974 OverflowError is raised
975
976 The last rule is used to catch overflow on platforms which follow
977 C89 but for which HUGE_VAL is not an infinity.
978
979 For most two-argument functions (copysign, fmod, hypot, atan2)
980 these rules are enough to ensure that Python's functions behave as
981 specified in 'Annex F' of the C99 standard, with the 'invalid' and
982 'divide-by-zero' floating-point exceptions mapping to Python's
983 ValueError and the 'overflow' floating-point exception mapping to
984 OverflowError.
985*/
986
987static PyObject *
988math_1(PyObject *arg, double (*func) (double), int can_overflow)
989{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow);
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000991}
992
993static PyObject *
Christian Heimes53876d92008-04-19 00:31:39 +0000994math_1_to_int(PyObject *arg, double (*func) (double), int can_overflow)
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000995{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 return math_1_to_whatever(arg, func, PyLong_FromDouble, can_overflow);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000997}
998
Barry Warsaw8b43b191996-12-09 22:32:36 +0000999static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001000math_2(PyObject *args, double (*func) (double, double), const char *funcname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 PyObject *ox, *oy;
1003 double x, y, r;
1004 if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy))
1005 return NULL;
1006 x = PyFloat_AsDouble(ox);
1007 y = PyFloat_AsDouble(oy);
1008 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1009 return NULL;
1010 errno = 0;
1011 PyFPE_START_PROTECT("in math_2", return 0);
1012 r = (*func)(x, y);
1013 PyFPE_END_PROTECT(r);
1014 if (Py_IS_NAN(r)) {
1015 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1016 errno = EDOM;
1017 else
1018 errno = 0;
1019 }
1020 else if (Py_IS_INFINITY(r)) {
1021 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
1022 errno = ERANGE;
1023 else
1024 errno = 0;
1025 }
1026 if (errno && is_error(r))
1027 return NULL;
1028 else
1029 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001030}
1031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032#define FUNC1(funcname, func, can_overflow, docstring) \
1033 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
1034 return math_1(args, func, can_overflow); \
1035 }\
1036 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038#define FUNC1A(funcname, func, docstring) \
1039 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
1040 return math_1a(args, func); \
1041 }\
1042 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001043
Fred Drake40c48682000-07-03 18:11:56 +00001044#define FUNC2(funcname, func, docstring) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
1046 return math_2(args, func, #funcname); \
1047 }\
1048 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001049
Christian Heimes53876d92008-04-19 00:31:39 +00001050FUNC1(acos, acos, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001051 "acos($module, x, /)\n--\n\n"
1052 "Return the arc cosine (measured in radians) of x.")
Mark Dickinsonf3718592009-12-21 15:27:41 +00001053FUNC1(acosh, m_acosh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001054 "acosh($module, x, /)\n--\n\n"
1055 "Return the inverse hyperbolic cosine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001056FUNC1(asin, asin, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001057 "asin($module, x, /)\n--\n\n"
1058 "Return the arc sine (measured in radians) of x.")
Mark Dickinsonf3718592009-12-21 15:27:41 +00001059FUNC1(asinh, m_asinh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001060 "asinh($module, x, /)\n--\n\n"
1061 "Return the inverse hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001062FUNC1(atan, atan, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001063 "atan($module, x, /)\n--\n\n"
1064 "Return the arc tangent (measured in radians) of x.")
Christian Heimese57950f2008-04-21 13:08:03 +00001065FUNC2(atan2, m_atan2,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001066 "atan2($module, y, x, /)\n--\n\n"
1067 "Return the arc tangent (measured in radians) of y/x.\n\n"
Tim Petersfe71f812001-08-07 22:10:00 +00001068 "Unlike atan(y/x), the signs of both x and y are considered.")
Mark Dickinsonf3718592009-12-21 15:27:41 +00001069FUNC1(atanh, m_atanh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001070 "atanh($module, x, /)\n--\n\n"
1071 "Return the inverse hyperbolic tangent of x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +00001072
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001073/*[clinic input]
1074math.ceil
1075
1076 x as number: object
1077 /
1078
1079Return the ceiling of x as an Integral.
1080
1081This is the smallest integer >= x.
1082[clinic start generated code]*/
1083
1084static PyObject *
1085math_ceil(PyObject *module, PyObject *number)
1086/*[clinic end generated code: output=6c3b8a78bc201c67 input=2725352806399cab]*/
1087{
Benjamin Petersonce798522012-01-22 11:24:29 -05001088 _Py_IDENTIFIER(__ceil__);
Mark Dickinson6d02d9c2010-07-02 16:05:15 +00001089 PyObject *method, *result;
Guido van Rossum13e05de2007-08-23 22:56:55 +00001090
Benjamin Petersonce798522012-01-22 11:24:29 -05001091 method = _PyObject_LookupSpecial(number, &PyId___ceil__);
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001092 if (method == NULL) {
1093 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 return math_1_to_int(number, ceil, 0);
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001096 }
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001097 result = _PyObject_CallNoArg(method);
Mark Dickinson6d02d9c2010-07-02 16:05:15 +00001098 Py_DECREF(method);
1099 return result;
Guido van Rossum13e05de2007-08-23 22:56:55 +00001100}
1101
Christian Heimes072c0f12008-01-03 23:01:04 +00001102FUNC2(copysign, copysign,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001103 "copysign($module, x, y, /)\n--\n\n"
1104 "Return a float with the magnitude (absolute value) of x but the sign of y.\n\n"
1105 "On platforms that support signed zeros, copysign(1.0, -0.0)\n"
1106 "returns -1.0.\n")
Christian Heimes53876d92008-04-19 00:31:39 +00001107FUNC1(cos, cos, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001108 "cos($module, x, /)\n--\n\n"
1109 "Return the cosine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001110FUNC1(cosh, cosh, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001111 "cosh($module, x, /)\n--\n\n"
1112 "Return the hyperbolic cosine of x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +00001113FUNC1A(erf, m_erf,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001114 "erf($module, x, /)\n--\n\n"
1115 "Error function at x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +00001116FUNC1A(erfc, m_erfc,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001117 "erfc($module, x, /)\n--\n\n"
1118 "Complementary error function at x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001119FUNC1(exp, exp, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001120 "exp($module, x, /)\n--\n\n"
1121 "Return e raised to the power of x.")
Mark Dickinson664b5112009-12-16 20:23:42 +00001122FUNC1(expm1, m_expm1, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001123 "expm1($module, x, /)\n--\n\n"
1124 "Return exp(x)-1.\n\n"
Mark Dickinson664b5112009-12-16 20:23:42 +00001125 "This function avoids the loss of precision involved in the direct "
1126 "evaluation of exp(x)-1 for small x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001127FUNC1(fabs, fabs, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001128 "fabs($module, x, /)\n--\n\n"
1129 "Return the absolute value of the float x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +00001130
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001131/*[clinic input]
1132math.floor
1133
1134 x as number: object
1135 /
1136
1137Return the floor of x as an Integral.
1138
1139This is the largest integer <= x.
1140[clinic start generated code]*/
1141
1142static PyObject *
1143math_floor(PyObject *module, PyObject *number)
1144/*[clinic end generated code: output=c6a65c4884884b8a input=63af6b5d7ebcc3d6]*/
1145{
Benjamin Petersonce798522012-01-22 11:24:29 -05001146 _Py_IDENTIFIER(__floor__);
Benjamin Petersonb0125892010-07-02 13:35:17 +00001147 PyObject *method, *result;
Guido van Rossum13e05de2007-08-23 22:56:55 +00001148
Benjamin Petersonce798522012-01-22 11:24:29 -05001149 method = _PyObject_LookupSpecial(number, &PyId___floor__);
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001150 if (method == NULL) {
1151 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 return math_1_to_int(number, floor, 0);
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001154 }
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001155 result = _PyObject_CallNoArg(method);
Benjamin Petersonb0125892010-07-02 13:35:17 +00001156 Py_DECREF(method);
1157 return result;
Guido van Rossum13e05de2007-08-23 22:56:55 +00001158}
1159
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001160FUNC1A(gamma, m_tgamma,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001161 "gamma($module, x, /)\n--\n\n"
1162 "Gamma function at x.")
Mark Dickinson05d2e082009-12-11 20:17:17 +00001163FUNC1A(lgamma, m_lgamma,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001164 "lgamma($module, x, /)\n--\n\n"
1165 "Natural logarithm of absolute value of Gamma function at x.")
Mark Dickinsonbe64d952010-07-07 16:21:29 +00001166FUNC1(log1p, m_log1p, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001167 "log1p($module, x, /)\n--\n\n"
1168 "Return the natural logarithm of 1+x (base e).\n\n"
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001169 "The result is computed in a way which is accurate for x near zero.")
Mark Dickinsona0ce3752017-04-05 18:34:27 +01001170FUNC2(remainder, m_remainder,
1171 "remainder($module, x, y, /)\n--\n\n"
1172 "Difference between x and the closest integer multiple of y.\n\n"
1173 "Return x - n*y where n*y is the closest integer multiple of y.\n"
1174 "In the case where x is exactly halfway between two multiples of\n"
1175 "y, the nearest even value of n is used. The result is always exact.")
Christian Heimes53876d92008-04-19 00:31:39 +00001176FUNC1(sin, sin, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001177 "sin($module, x, /)\n--\n\n"
1178 "Return the sine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001179FUNC1(sinh, sinh, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001180 "sinh($module, x, /)\n--\n\n"
1181 "Return the hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001182FUNC1(sqrt, sqrt, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001183 "sqrt($module, x, /)\n--\n\n"
1184 "Return the square root of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001185FUNC1(tan, tan, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001186 "tan($module, x, /)\n--\n\n"
1187 "Return the tangent of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001188FUNC1(tanh, tanh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001189 "tanh($module, x, /)\n--\n\n"
1190 "Return the hyperbolic tangent of x.")
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001191
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001192/* Precision summation function as msum() by Raymond Hettinger in
1193 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
1194 enhanced with the exact partials sum and roundoff from Mark
1195 Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
1196 See those links for more details, proofs and other references.
1197
1198 Note 1: IEEE 754R floating point semantics are assumed,
1199 but the current implementation does not re-establish special
1200 value semantics across iterations (i.e. handling -Inf + Inf).
1201
1202 Note 2: No provision is made for intermediate overflow handling;
Georg Brandlf78e02b2008-06-10 17:40:04 +00001203 therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001204 sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
1205 overflow of the first partial sum.
1206
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001207 Note 3: The intermediate values lo, yr, and hi are declared volatile so
1208 aggressive compilers won't algebraically reduce lo to always be exactly 0.0.
Georg Brandlf78e02b2008-06-10 17:40:04 +00001209 Also, the volatile declaration forces the values to be stored in memory as
1210 regular doubles instead of extended long precision (80-bit) values. This
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001211 prevents double rounding because any addition or subtraction of two doubles
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 can be resolved exactly into double-sized hi and lo values. As long as the
Georg Brandlf78e02b2008-06-10 17:40:04 +00001213 hi value gets forced into a double before yr and lo are computed, the extra
1214 bits in downstream extended precision operations (x87 for example) will be
1215 exactly zero and therefore can be losslessly stored back into a double,
1216 thereby preventing double rounding.
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001217
1218 Note 4: A similar implementation is in Modules/cmathmodule.c.
1219 Be sure to update both when making changes.
1220
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001221 Note 5: The signature of math.fsum() differs from builtins.sum()
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001222 because the start argument doesn't make sense in the context of
1223 accurate summation. Since the partials table is collapsed before
1224 returning a result, sum(seq2, start=sum(seq1)) may not equal the
1225 accurate result returned by sum(itertools.chain(seq1, seq2)).
1226*/
1227
1228#define NUM_PARTIALS 32 /* initial partials array size, on stack */
1229
1230/* Extend the partials array p[] by doubling its size. */
1231static int /* non-zero on error */
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001232_fsum_realloc(double **p_ptr, Py_ssize_t n,
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001233 double *ps, Py_ssize_t *m_ptr)
1234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 void *v = NULL;
1236 Py_ssize_t m = *m_ptr;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 m += m; /* double */
Victor Stinner049e5092014-08-17 22:20:00 +02001239 if (n < m && (size_t)m < ((size_t)PY_SSIZE_T_MAX / sizeof(double))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 double *p = *p_ptr;
1241 if (p == ps) {
1242 v = PyMem_Malloc(sizeof(double) * m);
1243 if (v != NULL)
1244 memcpy(v, ps, sizeof(double) * n);
1245 }
1246 else
1247 v = PyMem_Realloc(p, sizeof(double) * m);
1248 }
1249 if (v == NULL) { /* size overflow or no memory */
1250 PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
1251 return 1;
1252 }
1253 *p_ptr = (double*) v;
1254 *m_ptr = m;
1255 return 0;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001256}
1257
1258/* Full precision summation of a sequence of floats.
1259
1260 def msum(iterable):
1261 partials = [] # sorted, non-overlapping partial sums
1262 for x in iterable:
Mark Dickinsonfdb0acc2010-06-25 20:22:24 +00001263 i = 0
1264 for y in partials:
1265 if abs(x) < abs(y):
1266 x, y = y, x
1267 hi = x + y
1268 lo = y - (hi - x)
1269 if lo:
1270 partials[i] = lo
1271 i += 1
1272 x = hi
1273 partials[i:] = [x]
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001274 return sum_exact(partials)
1275
1276 Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
1277 are exactly equal to x+y. The inner loop applies hi/lo summation to each
1278 partial so that the list of partial sums remains exact.
1279
1280 Sum_exact() adds the partial sums exactly and correctly rounds the final
1281 result (using the round-half-to-even rule). The items in partials remain
1282 non-zero, non-special, non-overlapping and strictly increasing in
1283 magnitude, but possibly not all having the same sign.
1284
1285 Depends on IEEE 754 arithmetic guarantees and half-even rounding.
1286*/
1287
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001288/*[clinic input]
1289math.fsum
1290
1291 seq: object
1292 /
1293
1294Return an accurate floating point sum of values in the iterable seq.
1295
1296Assumes IEEE-754 floating point arithmetic.
1297[clinic start generated code]*/
1298
1299static PyObject *
1300math_fsum(PyObject *module, PyObject *seq)
1301/*[clinic end generated code: output=ba5c672b87fe34fc input=c51b7d8caf6f6e82]*/
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 PyObject *item, *iter, *sum = NULL;
1304 Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
1305 double x, y, t, ps[NUM_PARTIALS], *p = ps;
1306 double xsave, special_sum = 0.0, inf_sum = 0.0;
1307 volatile double hi, yr, lo;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 iter = PyObject_GetIter(seq);
1310 if (iter == NULL)
1311 return NULL;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 for(;;) { /* for x in iterable */
1316 assert(0 <= n && n <= m);
1317 assert((m == NUM_PARTIALS && p == ps) ||
1318 (m > NUM_PARTIALS && p != NULL));
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 item = PyIter_Next(iter);
1321 if (item == NULL) {
1322 if (PyErr_Occurred())
1323 goto _fsum_error;
1324 break;
1325 }
1326 x = PyFloat_AsDouble(item);
1327 Py_DECREF(item);
1328 if (PyErr_Occurred())
1329 goto _fsum_error;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 xsave = x;
1332 for (i = j = 0; j < n; j++) { /* for y in partials */
1333 y = p[j];
1334 if (fabs(x) < fabs(y)) {
1335 t = x; x = y; y = t;
1336 }
1337 hi = x + y;
1338 yr = hi - x;
1339 lo = y - yr;
1340 if (lo != 0.0)
1341 p[i++] = lo;
1342 x = hi;
1343 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 n = i; /* ps[i:] = [x] */
1346 if (x != 0.0) {
1347 if (! Py_IS_FINITE(x)) {
1348 /* a nonfinite x could arise either as
1349 a result of intermediate overflow, or
1350 as a result of a nan or inf in the
1351 summands */
1352 if (Py_IS_FINITE(xsave)) {
1353 PyErr_SetString(PyExc_OverflowError,
1354 "intermediate overflow in fsum");
1355 goto _fsum_error;
1356 }
1357 if (Py_IS_INFINITY(xsave))
1358 inf_sum += xsave;
1359 special_sum += xsave;
1360 /* reset partials */
1361 n = 0;
1362 }
1363 else if (n >= m && _fsum_realloc(&p, n, ps, &m))
1364 goto _fsum_error;
1365 else
1366 p[n++] = x;
1367 }
1368 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 if (special_sum != 0.0) {
1371 if (Py_IS_NAN(inf_sum))
1372 PyErr_SetString(PyExc_ValueError,
1373 "-inf + inf in fsum");
1374 else
1375 sum = PyFloat_FromDouble(special_sum);
1376 goto _fsum_error;
1377 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 hi = 0.0;
1380 if (n > 0) {
1381 hi = p[--n];
1382 /* sum_exact(ps, hi) from the top, stop when the sum becomes
1383 inexact. */
1384 while (n > 0) {
1385 x = hi;
1386 y = p[--n];
1387 assert(fabs(y) < fabs(x));
1388 hi = x + y;
1389 yr = hi - x;
1390 lo = y - yr;
1391 if (lo != 0.0)
1392 break;
1393 }
1394 /* Make half-even rounding work across multiple partials.
1395 Needed so that sum([1e-16, 1, 1e16]) will round-up the last
1396 digit to two instead of down to zero (the 1e-16 makes the 1
1397 slightly closer to two). With a potential 1 ULP rounding
1398 error fixed-up, math.fsum() can guarantee commutativity. */
1399 if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
1400 (lo > 0.0 && p[n-1] > 0.0))) {
1401 y = lo * 2.0;
1402 x = hi + y;
1403 yr = x - hi;
1404 if (y == yr)
1405 hi = x;
1406 }
1407 }
1408 sum = PyFloat_FromDouble(hi);
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001409
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001410_fsum_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 PyFPE_END_PROTECT(hi)
1412 Py_DECREF(iter);
1413 if (p != ps)
1414 PyMem_Free(p);
1415 return sum;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001416}
1417
1418#undef NUM_PARTIALS
1419
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001420
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001421/* Return the smallest integer k such that n < 2**k, or 0 if n == 0.
1422 * Equivalent to floor(lg(x))+1. Also equivalent to: bitwidth_of_type -
1423 * count_leading_zero_bits(x)
1424 */
1425
1426/* XXX: This routine does more or less the same thing as
1427 * bits_in_digit() in Objects/longobject.c. Someday it would be nice to
1428 * consolidate them. On BSD, there's a library function called fls()
1429 * that we could use, and GCC provides __builtin_clz().
1430 */
1431
1432static unsigned long
1433bit_length(unsigned long n)
1434{
1435 unsigned long len = 0;
1436 while (n != 0) {
1437 ++len;
1438 n >>= 1;
1439 }
1440 return len;
1441}
1442
1443static unsigned long
1444count_set_bits(unsigned long n)
1445{
1446 unsigned long count = 0;
1447 while (n != 0) {
1448 ++count;
1449 n &= n - 1; /* clear least significant bit */
1450 }
1451 return count;
1452}
1453
1454/* Divide-and-conquer factorial algorithm
1455 *
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07001456 * Based on the formula and pseudo-code provided at:
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001457 * http://www.luschny.de/math/factorial/binarysplitfact.html
1458 *
1459 * Faster algorithms exist, but they're more complicated and depend on
Ezio Melotti9527afd2010-07-08 15:03:02 +00001460 * a fast prime factorization algorithm.
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001461 *
1462 * Notes on the algorithm
1463 * ----------------------
1464 *
1465 * factorial(n) is written in the form 2**k * m, with m odd. k and m are
1466 * computed separately, and then combined using a left shift.
1467 *
1468 * The function factorial_odd_part computes the odd part m (i.e., the greatest
1469 * odd divisor) of factorial(n), using the formula:
1470 *
1471 * factorial_odd_part(n) =
1472 *
1473 * product_{i >= 0} product_{0 < j <= n / 2**i, j odd} j
1474 *
1475 * Example: factorial_odd_part(20) =
1476 *
1477 * (1) *
1478 * (1) *
1479 * (1 * 3 * 5) *
1480 * (1 * 3 * 5 * 7 * 9)
1481 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1482 *
1483 * Here i goes from large to small: the first term corresponds to i=4 (any
1484 * larger i gives an empty product), and the last term corresponds to i=0.
1485 * Each term can be computed from the last by multiplying by the extra odd
1486 * numbers required: e.g., to get from the penultimate term to the last one,
1487 * we multiply by (11 * 13 * 15 * 17 * 19).
1488 *
1489 * To see a hint of why this formula works, here are the same numbers as above
1490 * but with the even parts (i.e., the appropriate powers of 2) included. For
1491 * each subterm in the product for i, we multiply that subterm by 2**i:
1492 *
1493 * factorial(20) =
1494 *
1495 * (16) *
1496 * (8) *
1497 * (4 * 12 * 20) *
1498 * (2 * 6 * 10 * 14 * 18) *
1499 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1500 *
1501 * The factorial_partial_product function computes the product of all odd j in
1502 * range(start, stop) for given start and stop. It's used to compute the
1503 * partial products like (11 * 13 * 15 * 17 * 19) in the example above. It
1504 * operates recursively, repeatedly splitting the range into two roughly equal
1505 * pieces until the subranges are small enough to be computed using only C
1506 * integer arithmetic.
1507 *
1508 * The two-valuation k (i.e., the exponent of the largest power of 2 dividing
1509 * the factorial) is computed independently in the main math_factorial
1510 * function. By standard results, its value is:
1511 *
1512 * two_valuation = n//2 + n//4 + n//8 + ....
1513 *
1514 * It can be shown (e.g., by complete induction on n) that two_valuation is
1515 * equal to n - count_set_bits(n), where count_set_bits(n) gives the number of
1516 * '1'-bits in the binary expansion of n.
1517 */
1518
1519/* factorial_partial_product: Compute product(range(start, stop, 2)) using
1520 * divide and conquer. Assumes start and stop are odd and stop > start.
1521 * max_bits must be >= bit_length(stop - 2). */
1522
1523static PyObject *
1524factorial_partial_product(unsigned long start, unsigned long stop,
1525 unsigned long max_bits)
1526{
1527 unsigned long midpoint, num_operands;
1528 PyObject *left = NULL, *right = NULL, *result = NULL;
1529
1530 /* If the return value will fit an unsigned long, then we can
1531 * multiply in a tight, fast loop where each multiply is O(1).
1532 * Compute an upper bound on the number of bits required to store
1533 * the answer.
1534 *
1535 * Storing some integer z requires floor(lg(z))+1 bits, which is
1536 * conveniently the value returned by bit_length(z). The
1537 * product x*y will require at most
1538 * bit_length(x) + bit_length(y) bits to store, based
1539 * on the idea that lg product = lg x + lg y.
1540 *
1541 * We know that stop - 2 is the largest number to be multiplied. From
1542 * there, we have: bit_length(answer) <= num_operands *
1543 * bit_length(stop - 2)
1544 */
1545
1546 num_operands = (stop - start) / 2;
1547 /* The "num_operands <= 8 * SIZEOF_LONG" check guards against the
1548 * unlikely case of an overflow in num_operands * max_bits. */
1549 if (num_operands <= 8 * SIZEOF_LONG &&
1550 num_operands * max_bits <= 8 * SIZEOF_LONG) {
1551 unsigned long j, total;
1552 for (total = start, j = start + 2; j < stop; j += 2)
1553 total *= j;
1554 return PyLong_FromUnsignedLong(total);
1555 }
1556
1557 /* find midpoint of range(start, stop), rounded up to next odd number. */
1558 midpoint = (start + num_operands) | 1;
1559 left = factorial_partial_product(start, midpoint,
1560 bit_length(midpoint - 2));
1561 if (left == NULL)
1562 goto error;
1563 right = factorial_partial_product(midpoint, stop, max_bits);
1564 if (right == NULL)
1565 goto error;
1566 result = PyNumber_Multiply(left, right);
1567
1568 error:
1569 Py_XDECREF(left);
1570 Py_XDECREF(right);
1571 return result;
1572}
1573
1574/* factorial_odd_part: compute the odd part of factorial(n). */
1575
1576static PyObject *
1577factorial_odd_part(unsigned long n)
1578{
1579 long i;
1580 unsigned long v, lower, upper;
1581 PyObject *partial, *tmp, *inner, *outer;
1582
1583 inner = PyLong_FromLong(1);
1584 if (inner == NULL)
1585 return NULL;
1586 outer = inner;
1587 Py_INCREF(outer);
1588
1589 upper = 3;
1590 for (i = bit_length(n) - 2; i >= 0; i--) {
1591 v = n >> i;
1592 if (v <= 2)
1593 continue;
1594 lower = upper;
1595 /* (v + 1) | 1 = least odd integer strictly larger than n / 2**i */
1596 upper = (v + 1) | 1;
1597 /* Here inner is the product of all odd integers j in the range (0,
1598 n/2**(i+1)]. The factorial_partial_product call below gives the
1599 product of all odd integers j in the range (n/2**(i+1), n/2**i]. */
1600 partial = factorial_partial_product(lower, upper, bit_length(upper-2));
1601 /* inner *= partial */
1602 if (partial == NULL)
1603 goto error;
1604 tmp = PyNumber_Multiply(inner, partial);
1605 Py_DECREF(partial);
1606 if (tmp == NULL)
1607 goto error;
1608 Py_DECREF(inner);
1609 inner = tmp;
1610 /* Now inner is the product of all odd integers j in the range (0,
1611 n/2**i], giving the inner product in the formula above. */
1612
1613 /* outer *= inner; */
1614 tmp = PyNumber_Multiply(outer, inner);
1615 if (tmp == NULL)
1616 goto error;
1617 Py_DECREF(outer);
1618 outer = tmp;
1619 }
Mark Dickinson76464492012-10-25 10:46:28 +01001620 Py_DECREF(inner);
1621 return outer;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001622
1623 error:
1624 Py_DECREF(outer);
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001625 Py_DECREF(inner);
Mark Dickinson76464492012-10-25 10:46:28 +01001626 return NULL;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001627}
1628
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001629
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001630/* Lookup table for small factorial values */
1631
1632static const unsigned long SmallFactorials[] = {
1633 1, 1, 2, 6, 24, 120, 720, 5040, 40320,
1634 362880, 3628800, 39916800, 479001600,
1635#if SIZEOF_LONG >= 8
1636 6227020800, 87178291200, 1307674368000,
1637 20922789888000, 355687428096000, 6402373705728000,
1638 121645100408832000, 2432902008176640000
1639#endif
1640};
1641
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001642/*[clinic input]
1643math.factorial
1644
1645 x as arg: object
1646 /
1647
1648Find x!.
1649
1650Raise a ValueError if x is negative or non-integral.
1651[clinic start generated code]*/
1652
Barry Warsaw8b43b191996-12-09 22:32:36 +00001653static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001654math_factorial(PyObject *module, PyObject *arg)
1655/*[clinic end generated code: output=6686f26fae00e9ca input=6d1c8105c0d91fb4]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001656{
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001657 long x;
Mark Dickinson5990d282014-04-10 09:29:39 -04001658 int overflow;
Pablo Galindoe9ba3702018-09-03 22:20:06 +01001659 PyObject *result, *odd_part, *two_valuation, *pyint_form;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 if (PyFloat_Check(arg)) {
1662 PyObject *lx;
1663 double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
1664 if (!(Py_IS_FINITE(dx) && dx == floor(dx))) {
1665 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001666 "factorial() only accepts integral values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 return NULL;
1668 }
1669 lx = PyLong_FromDouble(dx);
1670 if (lx == NULL)
1671 return NULL;
Mark Dickinson5990d282014-04-10 09:29:39 -04001672 x = PyLong_AsLongAndOverflow(lx, &overflow);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 Py_DECREF(lx);
1674 }
Pablo Galindoe9ba3702018-09-03 22:20:06 +01001675 else {
1676 pyint_form = PyNumber_Index(arg);
1677 if (pyint_form == NULL) {
1678 return NULL;
1679 }
1680 x = PyLong_AsLongAndOverflow(pyint_form, &overflow);
1681 Py_DECREF(pyint_form);
1682 }
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001683
Mark Dickinson5990d282014-04-10 09:29:39 -04001684 if (x == -1 && PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 return NULL;
Mark Dickinson5990d282014-04-10 09:29:39 -04001686 }
1687 else if (overflow == 1) {
1688 PyErr_Format(PyExc_OverflowError,
1689 "factorial() argument should not exceed %ld",
1690 LONG_MAX);
1691 return NULL;
1692 }
1693 else if (overflow == -1 || x < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001695 "factorial() not defined for negative values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 return NULL;
1697 }
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001698
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001699 /* use lookup table if x is small */
Victor Stinner63941882011-09-29 00:42:28 +02001700 if (x < (long)Py_ARRAY_LENGTH(SmallFactorials))
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001701 return PyLong_FromUnsignedLong(SmallFactorials[x]);
1702
1703 /* else express in the form odd_part * 2**two_valuation, and compute as
1704 odd_part << two_valuation. */
1705 odd_part = factorial_odd_part(x);
1706 if (odd_part == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 return NULL;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001708 two_valuation = PyLong_FromLong(x - count_set_bits(x));
1709 if (two_valuation == NULL) {
1710 Py_DECREF(odd_part);
1711 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 }
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001713 result = PyNumber_Lshift(odd_part, two_valuation);
1714 Py_DECREF(two_valuation);
1715 Py_DECREF(odd_part);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 return result;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001717}
1718
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001719
1720/*[clinic input]
1721math.trunc
1722
1723 x: object
1724 /
1725
1726Truncates the Real x to the nearest Integral toward 0.
1727
1728Uses the __trunc__ magic method.
1729[clinic start generated code]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001730
1731static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001732math_trunc(PyObject *module, PyObject *x)
1733/*[clinic end generated code: output=34b9697b707e1031 input=2168b34e0a09134d]*/
Christian Heimes400adb02008-02-01 08:12:03 +00001734{
Benjamin Petersonce798522012-01-22 11:24:29 -05001735 _Py_IDENTIFIER(__trunc__);
Benjamin Petersonb0125892010-07-02 13:35:17 +00001736 PyObject *trunc, *result;
Christian Heimes400adb02008-02-01 08:12:03 +00001737
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001738 if (Py_TYPE(x)->tp_dict == NULL) {
1739 if (PyType_Ready(Py_TYPE(x)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 return NULL;
1741 }
Christian Heimes400adb02008-02-01 08:12:03 +00001742
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001743 trunc = _PyObject_LookupSpecial(x, &PyId___trunc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 if (trunc == NULL) {
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001745 if (!PyErr_Occurred())
1746 PyErr_Format(PyExc_TypeError,
1747 "type %.100s doesn't define __trunc__ method",
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001748 Py_TYPE(x)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 return NULL;
1750 }
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001751 result = _PyObject_CallNoArg(trunc);
Benjamin Petersonb0125892010-07-02 13:35:17 +00001752 Py_DECREF(trunc);
1753 return result;
Christian Heimes400adb02008-02-01 08:12:03 +00001754}
1755
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001756
1757/*[clinic input]
1758math.frexp
1759
1760 x: double
1761 /
1762
1763Return the mantissa and exponent of x, as pair (m, e).
1764
1765m is a float and e is an int, such that x = m * 2.**e.
1766If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.
1767[clinic start generated code]*/
Christian Heimes400adb02008-02-01 08:12:03 +00001768
1769static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001770math_frexp_impl(PyObject *module, double x)
1771/*[clinic end generated code: output=03e30d252a15ad4a input=96251c9e208bc6e9]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00001772{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 /* deal with special cases directly, to sidestep platform
1775 differences */
1776 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
1777 i = 0;
1778 }
1779 else {
1780 PyFPE_START_PROTECT("in math_frexp", return 0);
1781 x = frexp(x, &i);
1782 PyFPE_END_PROTECT(x);
1783 }
1784 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001785}
1786
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001787
1788/*[clinic input]
1789math.ldexp
1790
1791 x: double
1792 i: object
1793 /
1794
1795Return x * (2**i).
1796
1797This is essentially the inverse of frexp().
1798[clinic start generated code]*/
Guido van Rossumc6e22901998-12-04 19:26:43 +00001799
Barry Warsaw8b43b191996-12-09 22:32:36 +00001800static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001801math_ldexp_impl(PyObject *module, double x, PyObject *i)
1802/*[clinic end generated code: output=b6892f3c2df9cc6a input=17d5970c1a40a8c1]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00001803{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001804 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 long exp;
1806 int overflow;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001807
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001808 if (PyLong_Check(i)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 /* on overflow, replace exponent with either LONG_MAX
1810 or LONG_MIN, depending on the sign. */
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001811 exp = PyLong_AsLongAndOverflow(i, &overflow);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 if (exp == -1 && PyErr_Occurred())
1813 return NULL;
1814 if (overflow)
1815 exp = overflow < 0 ? LONG_MIN : LONG_MAX;
1816 }
1817 else {
1818 PyErr_SetString(PyExc_TypeError,
Serhiy Storchaka95949422013-08-27 19:40:23 +03001819 "Expected an int as second argument to ldexp.");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 return NULL;
1821 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 if (x == 0. || !Py_IS_FINITE(x)) {
1824 /* NaNs, zeros and infinities are returned unchanged */
1825 r = x;
1826 errno = 0;
1827 } else if (exp > INT_MAX) {
1828 /* overflow */
1829 r = copysign(Py_HUGE_VAL, x);
1830 errno = ERANGE;
1831 } else if (exp < INT_MIN) {
1832 /* underflow to +-0 */
1833 r = copysign(0., x);
1834 errno = 0;
1835 } else {
1836 errno = 0;
1837 PyFPE_START_PROTECT("in math_ldexp", return 0);
1838 r = ldexp(x, (int)exp);
1839 PyFPE_END_PROTECT(r);
1840 if (Py_IS_INFINITY(r))
1841 errno = ERANGE;
1842 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 if (errno && is_error(r))
1845 return NULL;
1846 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001847}
1848
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001849
1850/*[clinic input]
1851math.modf
1852
1853 x: double
1854 /
1855
1856Return the fractional and integer parts of x.
1857
1858Both results carry the sign of x and are floats.
1859[clinic start generated code]*/
Guido van Rossumc6e22901998-12-04 19:26:43 +00001860
Barry Warsaw8b43b191996-12-09 22:32:36 +00001861static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001862math_modf_impl(PyObject *module, double x)
1863/*[clinic end generated code: output=90cee0260014c3c0 input=b4cfb6786afd9035]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00001864{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001865 double y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 /* some platforms don't do the right thing for NaNs and
1867 infinities, so we take care of special cases directly. */
1868 if (!Py_IS_FINITE(x)) {
1869 if (Py_IS_INFINITY(x))
1870 return Py_BuildValue("(dd)", copysign(0., x), x);
1871 else if (Py_IS_NAN(x))
1872 return Py_BuildValue("(dd)", x, x);
1873 }
Christian Heimesa342c012008-04-20 21:01:16 +00001874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 errno = 0;
1876 PyFPE_START_PROTECT("in math_modf", return 0);
1877 x = modf(x, &y);
1878 PyFPE_END_PROTECT(x);
1879 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +00001880}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001881
Guido van Rossumc6e22901998-12-04 19:26:43 +00001882
Serhiy Storchaka95949422013-08-27 19:40:23 +03001883/* A decent logarithm is easy to compute even for huge ints, but libm can't
Tim Peters78526162001-09-05 00:53:45 +00001884 do that by itself -- loghelper can. func is log or log10, and name is
Serhiy Storchaka95949422013-08-27 19:40:23 +03001885 "log" or "log10". Note that overflow of the result isn't possible: an int
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00001886 can contain no more than INT_MAX * SHIFT bits, so has value certainly less
1887 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 +00001888 small enough to fit in an IEEE single. log and log10 are even smaller.
Serhiy Storchaka95949422013-08-27 19:40:23 +03001889 However, intermediate overflow is possible for an int if the number of bits
1890 in that int is larger than PY_SSIZE_T_MAX. */
Tim Peters78526162001-09-05 00:53:45 +00001891
1892static PyObject*
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001893loghelper(PyObject* arg, double (*func)(double), const char *funcname)
Tim Peters78526162001-09-05 00:53:45 +00001894{
Serhiy Storchaka95949422013-08-27 19:40:23 +03001895 /* If it is int, do it ourselves. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 if (PyLong_Check(arg)) {
Mark Dickinsonc6037172010-09-29 19:06:36 +00001897 double x, result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 Py_ssize_t e;
Mark Dickinsonc6037172010-09-29 19:06:36 +00001899
1900 /* Negative or zero inputs give a ValueError. */
1901 if (Py_SIZE(arg) <= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 PyErr_SetString(PyExc_ValueError,
1903 "math domain error");
1904 return NULL;
1905 }
Mark Dickinsonfa41e602010-09-28 07:22:27 +00001906
Mark Dickinsonc6037172010-09-29 19:06:36 +00001907 x = PyLong_AsDouble(arg);
1908 if (x == -1.0 && PyErr_Occurred()) {
1909 if (!PyErr_ExceptionMatches(PyExc_OverflowError))
1910 return NULL;
1911 /* Here the conversion to double overflowed, but it's possible
1912 to compute the log anyway. Clear the exception and continue. */
1913 PyErr_Clear();
1914 x = _PyLong_Frexp((PyLongObject *)arg, &e);
1915 if (x == -1.0 && PyErr_Occurred())
1916 return NULL;
1917 /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */
1918 result = func(x) + func(2.0) * e;
1919 }
1920 else
1921 /* Successfully converted x to a double. */
1922 result = func(x);
1923 return PyFloat_FromDouble(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 }
Tim Peters78526162001-09-05 00:53:45 +00001925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 /* Else let libm handle it by itself. */
1927 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +00001928}
1929
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001930
1931/*[clinic input]
1932math.log
1933
1934 x: object
1935 [
1936 base: object(c_default="NULL") = math.e
1937 ]
1938 /
1939
1940Return the logarithm of x to the given base.
1941
1942If the base not specified, returns the natural logarithm (base e) of x.
1943[clinic start generated code]*/
1944
Tim Peters78526162001-09-05 00:53:45 +00001945static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001946math_log_impl(PyObject *module, PyObject *x, int group_right_1,
1947 PyObject *base)
1948/*[clinic end generated code: output=7b5a39e526b73fc9 input=0f62d5726cbfebbd]*/
Tim Peters78526162001-09-05 00:53:45 +00001949{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 PyObject *num, *den;
1951 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001952
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001953 num = loghelper(x, m_log, "log");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 if (num == NULL || base == NULL)
1955 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +00001956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 den = loghelper(base, m_log, "log");
1958 if (den == NULL) {
1959 Py_DECREF(num);
1960 return NULL;
1961 }
Raymond Hettinger866964c2002-12-14 19:51:34 +00001962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 ans = PyNumber_TrueDivide(num, den);
1964 Py_DECREF(num);
1965 Py_DECREF(den);
1966 return ans;
Tim Peters78526162001-09-05 00:53:45 +00001967}
1968
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001969
1970/*[clinic input]
1971math.log2
1972
1973 x: object
1974 /
1975
1976Return the base 2 logarithm of x.
1977[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00001978
1979static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001980math_log2(PyObject *module, PyObject *x)
1981/*[clinic end generated code: output=5425899a4d5d6acb input=08321262bae4f39b]*/
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001982{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001983 return loghelper(x, m_log2, "log2");
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001984}
1985
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001986
1987/*[clinic input]
1988math.log10
1989
1990 x: object
1991 /
1992
1993Return the base 10 logarithm of x.
1994[clinic start generated code]*/
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001995
1996static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001997math_log10(PyObject *module, PyObject *x)
1998/*[clinic end generated code: output=be72a64617df9c6f input=b2469d02c6469e53]*/
Tim Peters78526162001-09-05 00:53:45 +00001999{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002000 return loghelper(x, m_log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +00002001}
2002
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002003
2004/*[clinic input]
2005math.fmod
2006
2007 x: double
2008 y: double
2009 /
2010
2011Return fmod(x, y), according to platform C.
2012
2013x % y may differ.
2014[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002015
Christian Heimes53876d92008-04-19 00:31:39 +00002016static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002017math_fmod_impl(PyObject *module, double x, double y)
2018/*[clinic end generated code: output=7559d794343a27b5 input=4f84caa8cfc26a03]*/
Christian Heimes53876d92008-04-19 00:31:39 +00002019{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002020 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 /* fmod(x, +/-Inf) returns x for finite x. */
2022 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
2023 return PyFloat_FromDouble(x);
2024 errno = 0;
2025 PyFPE_START_PROTECT("in math_fmod", return 0);
2026 r = fmod(x, y);
2027 PyFPE_END_PROTECT(r);
2028 if (Py_IS_NAN(r)) {
2029 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
2030 errno = EDOM;
2031 else
2032 errno = 0;
2033 }
2034 if (errno && is_error(r))
2035 return NULL;
2036 else
2037 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00002038}
2039
Raymond Hettinger13990742018-08-11 11:26:36 -07002040/*
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002041Given an *n* length *vec* of values and a value *max*, compute:
Raymond Hettinger13990742018-08-11 11:26:36 -07002042
Raymond Hettingerc630e102018-08-11 18:39:05 -07002043 max * sqrt(sum((x / max) ** 2 for x in vec))
Raymond Hettinger13990742018-08-11 11:26:36 -07002044
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002045The value of the *max* variable must be non-negative and
2046at least equal to the absolute value of the largest magnitude
2047entry in the vector. If n==0, then *max* should be 0.0.
2048If an infinity is present in the vec, *max* should be INF.
Raymond Hettingerc630e102018-08-11 18:39:05 -07002049
2050The *found_nan* variable indicates whether some member of
2051the *vec* is a NaN.
Raymond Hettinger21786f52018-08-28 22:47:24 -07002052
2053To improve accuracy and to increase the number of cases where
2054vector_norm() is commutative, we use a variant of Neumaier
2055summation specialized to exploit that we always know that
2056|csum| >= |x|.
2057
2058The *csum* variable tracks the cumulative sum and *frac* tracks
2059the cumulative fractional errors at each step. Since this
2060variant assumes that |csum| >= |x| at each step, we establish
2061the precondition by starting the accumulation from 1.0 which
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002062represents the largest possible value of (x/max)**2.
2063
2064After the loop is finished, the initial 1.0 is subtracted out
2065for a net zero effect on the final sum. Since *csum* will be
2066greater than 1.0, the subtraction of 1.0 will not cause
2067fractional digits to be dropped from *csum*.
Raymond Hettinger21786f52018-08-28 22:47:24 -07002068
Raymond Hettinger13990742018-08-11 11:26:36 -07002069*/
2070
2071static inline double
Raymond Hettingerc630e102018-08-11 18:39:05 -07002072vector_norm(Py_ssize_t n, double *vec, double max, int found_nan)
Raymond Hettinger13990742018-08-11 11:26:36 -07002073{
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002074 double x, csum = 1.0, oldcsum, frac = 0.0;
Raymond Hettinger13990742018-08-11 11:26:36 -07002075 Py_ssize_t i;
2076
Raymond Hettingerc630e102018-08-11 18:39:05 -07002077 if (Py_IS_INFINITY(max)) {
2078 return max;
2079 }
2080 if (found_nan) {
2081 return Py_NAN;
2082 }
Raymond Hettingerf3267142018-09-02 13:34:21 -07002083 if (max == 0.0 || n <= 1) {
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002084 return max;
Raymond Hettinger13990742018-08-11 11:26:36 -07002085 }
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002086 for (i=0 ; i < n ; i++) {
Raymond Hettinger13990742018-08-11 11:26:36 -07002087 x = vec[i];
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002088 assert(Py_IS_FINITE(x) && fabs(x) <= max);
Raymond Hettinger13990742018-08-11 11:26:36 -07002089 x /= max;
Raymond Hettinger21786f52018-08-28 22:47:24 -07002090 x = x*x;
Raymond Hettinger13990742018-08-11 11:26:36 -07002091 oldcsum = csum;
2092 csum += x;
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002093 assert(csum >= x);
Raymond Hettinger21786f52018-08-28 22:47:24 -07002094 frac += (oldcsum - csum) + x;
Raymond Hettinger13990742018-08-11 11:26:36 -07002095 }
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002096 return max * sqrt(csum - 1.0 + frac);
Raymond Hettinger13990742018-08-11 11:26:36 -07002097}
2098
Raymond Hettingerc630e102018-08-11 18:39:05 -07002099#define NUM_STACK_ELEMS 16
2100
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002101/*[clinic input]
2102math.dist
2103
Raymond Hettingerdf810152018-09-29 14:30:38 -07002104 p: object
2105 q: object
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002106 /
2107
2108Return the Euclidean distance between two points p and q.
2109
2110The points should be specified as tuples of coordinates.
2111Both tuples must be the same size.
2112
2113Roughly equivalent to:
2114 sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
2115[clinic start generated code]*/
2116
2117static PyObject *
2118math_dist_impl(PyObject *module, PyObject *p, PyObject *q)
Raymond Hettingerdf810152018-09-29 14:30:38 -07002119/*[clinic end generated code: output=56bd9538d06bbcfe input=8c83c07c7a524664]*/
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002120{
2121 PyObject *item;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002122 double max = 0.0;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002123 double x, px, qx, result;
2124 Py_ssize_t i, m, n;
2125 int found_nan = 0;
Raymond Hettingerc630e102018-08-11 18:39:05 -07002126 double diffs_on_stack[NUM_STACK_ELEMS];
2127 double *diffs = diffs_on_stack;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002128
Raymond Hettingerdf810152018-09-29 14:30:38 -07002129 if (!PyTuple_Check(p) || !PyTuple_Check(q)) {
2130 PyErr_SetString(PyExc_TypeError, "dist argument must be a tuple");
2131 return NULL;
2132 }
2133
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002134 m = PyTuple_GET_SIZE(p);
2135 n = PyTuple_GET_SIZE(q);
2136 if (m != n) {
2137 PyErr_SetString(PyExc_ValueError,
2138 "both points must have the same number of dimensions");
2139 return NULL;
2140
2141 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002142 if (n > NUM_STACK_ELEMS) {
2143 diffs = (double *) PyObject_Malloc(n * sizeof(double));
2144 if (diffs == NULL) {
2145 return NULL;
2146 }
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002147 }
2148 for (i=0 ; i<n ; i++) {
2149 item = PyTuple_GET_ITEM(p, i);
Raymond Hettinger74734f72018-08-26 19:38:31 -05002150 if (PyFloat_CheckExact(item)) {
2151 px = PyFloat_AS_DOUBLE(item);
2152 } else {
2153 px = PyFloat_AsDouble(item);
2154 if (px == -1.0 && PyErr_Occurred()) {
2155 goto error_exit;
2156 }
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002157 }
2158 item = PyTuple_GET_ITEM(q, i);
Raymond Hettinger74734f72018-08-26 19:38:31 -05002159 if (PyFloat_CheckExact(item)) {
2160 qx = PyFloat_AS_DOUBLE(item);
2161 } else {
2162 qx = PyFloat_AsDouble(item);
2163 if (qx == -1.0 && PyErr_Occurred()) {
2164 goto error_exit;
2165 }
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002166 }
2167 x = fabs(px - qx);
2168 diffs[i] = x;
2169 found_nan |= Py_IS_NAN(x);
2170 if (x > max) {
2171 max = x;
2172 }
2173 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002174 result = vector_norm(n, diffs, max, found_nan);
2175 if (diffs != diffs_on_stack) {
2176 PyObject_Free(diffs);
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002177 }
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002178 return PyFloat_FromDouble(result);
Raymond Hettingerc630e102018-08-11 18:39:05 -07002179
2180 error_exit:
2181 if (diffs != diffs_on_stack) {
2182 PyObject_Free(diffs);
2183 }
2184 return NULL;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002185}
2186
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002187/* AC: cannot convert yet, waiting for *args support */
Christian Heimes53876d92008-04-19 00:31:39 +00002188static PyObject *
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002189math_hypot(PyObject *self, PyObject *args)
Christian Heimes53876d92008-04-19 00:31:39 +00002190{
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002191 Py_ssize_t i, n;
2192 PyObject *item;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002193 double max = 0.0;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002194 double x, result;
2195 int found_nan = 0;
Raymond Hettingerc630e102018-08-11 18:39:05 -07002196 double coord_on_stack[NUM_STACK_ELEMS];
2197 double *coordinates = coord_on_stack;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002198
2199 n = PyTuple_GET_SIZE(args);
Raymond Hettingerc630e102018-08-11 18:39:05 -07002200 if (n > NUM_STACK_ELEMS) {
2201 coordinates = (double *) PyObject_Malloc(n * sizeof(double));
2202 if (coordinates == NULL)
2203 return NULL;
2204 }
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002205 for (i=0 ; i<n ; i++) {
2206 item = PyTuple_GET_ITEM(args, i);
Raymond Hettinger74734f72018-08-26 19:38:31 -05002207 if (PyFloat_CheckExact(item)) {
2208 x = PyFloat_AS_DOUBLE(item);
2209 } else {
2210 x = PyFloat_AsDouble(item);
2211 if (x == -1.0 && PyErr_Occurred()) {
2212 goto error_exit;
2213 }
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002214 }
2215 x = fabs(x);
2216 coordinates[i] = x;
2217 found_nan |= Py_IS_NAN(x);
2218 if (x > max) {
2219 max = x;
2220 }
2221 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002222 result = vector_norm(n, coordinates, max, found_nan);
2223 if (coordinates != coord_on_stack) {
2224 PyObject_Free(coordinates);
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002225 }
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002226 return PyFloat_FromDouble(result);
Raymond Hettingerc630e102018-08-11 18:39:05 -07002227
2228 error_exit:
2229 if (coordinates != coord_on_stack) {
2230 PyObject_Free(coordinates);
2231 }
2232 return NULL;
Christian Heimes53876d92008-04-19 00:31:39 +00002233}
2234
Raymond Hettingerc630e102018-08-11 18:39:05 -07002235#undef NUM_STACK_ELEMS
2236
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002237PyDoc_STRVAR(math_hypot_doc,
2238 "hypot(*coordinates) -> value\n\n\
2239Multidimensional Euclidean distance from the origin to a point.\n\
2240\n\
2241Roughly equivalent to:\n\
2242 sqrt(sum(x**2 for x in coordinates))\n\
2243\n\
2244For a two dimensional point (x, y), gives the hypotenuse\n\
2245using the Pythagorean theorem: sqrt(x*x + y*y).\n\
2246\n\
2247For example, the hypotenuse of a 3/4/5 right triangle is:\n\
2248\n\
2249 >>> hypot(3.0, 4.0)\n\
2250 5.0\n\
2251");
Christian Heimes53876d92008-04-19 00:31:39 +00002252
2253/* pow can't use math_2, but needs its own wrapper: the problem is
2254 that an infinite result can arise either as a result of overflow
2255 (in which case OverflowError should be raised) or as a result of
2256 e.g. 0.**-5. (for which ValueError needs to be raised.)
2257*/
2258
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002259/*[clinic input]
2260math.pow
Christian Heimes53876d92008-04-19 00:31:39 +00002261
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002262 x: double
2263 y: double
2264 /
2265
2266Return x**y (x to the power of y).
2267[clinic start generated code]*/
2268
2269static PyObject *
2270math_pow_impl(PyObject *module, double x, double y)
2271/*[clinic end generated code: output=fff93e65abccd6b0 input=c26f1f6075088bfd]*/
2272{
2273 double r;
2274 int odd_y;
Christian Heimesa342c012008-04-20 21:01:16 +00002275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 /* deal directly with IEEE specials, to cope with problems on various
2277 platforms whose semantics don't exactly match C99 */
2278 r = 0.; /* silence compiler warning */
2279 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
2280 errno = 0;
2281 if (Py_IS_NAN(x))
2282 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
2283 else if (Py_IS_NAN(y))
2284 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
2285 else if (Py_IS_INFINITY(x)) {
2286 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
2287 if (y > 0.)
2288 r = odd_y ? x : fabs(x);
2289 else if (y == 0.)
2290 r = 1.;
2291 else /* y < 0. */
2292 r = odd_y ? copysign(0., x) : 0.;
2293 }
2294 else if (Py_IS_INFINITY(y)) {
2295 if (fabs(x) == 1.0)
2296 r = 1.;
2297 else if (y > 0. && fabs(x) > 1.0)
2298 r = y;
2299 else if (y < 0. && fabs(x) < 1.0) {
2300 r = -y; /* result is +inf */
2301 if (x == 0.) /* 0**-inf: divide-by-zero */
2302 errno = EDOM;
2303 }
2304 else
2305 r = 0.;
2306 }
2307 }
2308 else {
2309 /* let libm handle finite**finite */
2310 errno = 0;
2311 PyFPE_START_PROTECT("in math_pow", return 0);
2312 r = pow(x, y);
2313 PyFPE_END_PROTECT(r);
2314 /* a NaN result should arise only from (-ve)**(finite
2315 non-integer); in this case we want to raise ValueError. */
2316 if (!Py_IS_FINITE(r)) {
2317 if (Py_IS_NAN(r)) {
2318 errno = EDOM;
2319 }
2320 /*
2321 an infinite result here arises either from:
2322 (A) (+/-0.)**negative (-> divide-by-zero)
2323 (B) overflow of x**y with x and y finite
2324 */
2325 else if (Py_IS_INFINITY(r)) {
2326 if (x == 0.)
2327 errno = EDOM;
2328 else
2329 errno = ERANGE;
2330 }
2331 }
2332 }
Christian Heimes53876d92008-04-19 00:31:39 +00002333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 if (errno && is_error(r))
2335 return NULL;
2336 else
2337 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00002338}
2339
Christian Heimes53876d92008-04-19 00:31:39 +00002340
Christian Heimes072c0f12008-01-03 23:01:04 +00002341static const double degToRad = Py_MATH_PI / 180.0;
2342static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002343
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002344/*[clinic input]
2345math.degrees
2346
2347 x: double
2348 /
2349
2350Convert angle x from radians to degrees.
2351[clinic start generated code]*/
2352
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002353static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002354math_degrees_impl(PyObject *module, double x)
2355/*[clinic end generated code: output=7fea78b294acd12f input=81e016555d6e3660]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002358}
2359
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002360
2361/*[clinic input]
2362math.radians
2363
2364 x: double
2365 /
2366
2367Convert angle x from degrees to radians.
2368[clinic start generated code]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002369
2370static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002371math_radians_impl(PyObject *module, double x)
2372/*[clinic end generated code: output=34daa47caf9b1590 input=91626fc489fe3d63]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 return PyFloat_FromDouble(x * degToRad);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002375}
2376
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002377
2378/*[clinic input]
2379math.isfinite
2380
2381 x: double
2382 /
2383
2384Return True if x is neither an infinity nor a NaN, and False otherwise.
2385[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002386
Christian Heimes072c0f12008-01-03 23:01:04 +00002387static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002388math_isfinite_impl(PyObject *module, double x)
2389/*[clinic end generated code: output=8ba1f396440c9901 input=46967d254812e54a]*/
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002390{
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002391 return PyBool_FromLong((long)Py_IS_FINITE(x));
2392}
2393
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002394
2395/*[clinic input]
2396math.isnan
2397
2398 x: double
2399 /
2400
2401Return True if x is a NaN (not a number), and False otherwise.
2402[clinic start generated code]*/
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002403
2404static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002405math_isnan_impl(PyObject *module, double x)
2406/*[clinic end generated code: output=f537b4d6df878c3e input=935891e66083f46a]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00002409}
2410
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002411
2412/*[clinic input]
2413math.isinf
2414
2415 x: double
2416 /
2417
2418Return True if x is a positive or negative infinity, and False otherwise.
2419[clinic start generated code]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002420
2421static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002422math_isinf_impl(PyObject *module, double x)
2423/*[clinic end generated code: output=9f00cbec4de7b06b input=32630e4212cf961f]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00002426}
2427
Christian Heimes072c0f12008-01-03 23:01:04 +00002428
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002429/*[clinic input]
2430math.isclose -> bool
2431
2432 a: double
2433 b: double
2434 *
2435 rel_tol: double = 1e-09
2436 maximum difference for being considered "close", relative to the
2437 magnitude of the input values
2438 abs_tol: double = 0.0
2439 maximum difference for being considered "close", regardless of the
2440 magnitude of the input values
2441
2442Determine whether two floating point numbers are close in value.
2443
2444Return True if a is close in value to b, and False otherwise.
2445
2446For the values to be considered close, the difference between them
2447must be smaller than at least one of the tolerances.
2448
2449-inf, inf and NaN behave similarly to the IEEE 754 Standard. That
2450is, NaN is not close to anything, even itself. inf and -inf are
2451only close to themselves.
2452[clinic start generated code]*/
2453
2454static int
2455math_isclose_impl(PyObject *module, double a, double b, double rel_tol,
2456 double abs_tol)
2457/*[clinic end generated code: output=b73070207511952d input=f28671871ea5bfba]*/
Tal Einatd5519ed2015-05-31 22:05:00 +03002458{
Tal Einatd5519ed2015-05-31 22:05:00 +03002459 double diff = 0.0;
Tal Einatd5519ed2015-05-31 22:05:00 +03002460
2461 /* sanity check on the inputs */
2462 if (rel_tol < 0.0 || abs_tol < 0.0 ) {
2463 PyErr_SetString(PyExc_ValueError,
2464 "tolerances must be non-negative");
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002465 return -1;
Tal Einatd5519ed2015-05-31 22:05:00 +03002466 }
2467
2468 if ( a == b ) {
2469 /* short circuit exact equality -- needed to catch two infinities of
2470 the same sign. And perhaps speeds things up a bit sometimes.
2471 */
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002472 return 1;
Tal Einatd5519ed2015-05-31 22:05:00 +03002473 }
2474
2475 /* This catches the case of two infinities of opposite sign, or
2476 one infinity and one finite number. Two infinities of opposite
2477 sign would otherwise have an infinite relative tolerance.
2478 Two infinities of the same sign are caught by the equality check
2479 above.
2480 */
2481
2482 if (Py_IS_INFINITY(a) || Py_IS_INFINITY(b)) {
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002483 return 0;
Tal Einatd5519ed2015-05-31 22:05:00 +03002484 }
2485
2486 /* now do the regular computation
2487 this is essentially the "weak" test from the Boost library
2488 */
2489
2490 diff = fabs(b - a);
2491
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002492 return (((diff <= fabs(rel_tol * b)) ||
2493 (diff <= fabs(rel_tol * a))) ||
2494 (diff <= abs_tol));
Tal Einatd5519ed2015-05-31 22:05:00 +03002495}
2496
Tal Einatd5519ed2015-05-31 22:05:00 +03002497
Barry Warsaw8b43b191996-12-09 22:32:36 +00002498static PyMethodDef math_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 {"acos", math_acos, METH_O, math_acos_doc},
2500 {"acosh", math_acosh, METH_O, math_acosh_doc},
2501 {"asin", math_asin, METH_O, math_asin_doc},
2502 {"asinh", math_asinh, METH_O, math_asinh_doc},
2503 {"atan", math_atan, METH_O, math_atan_doc},
2504 {"atan2", math_atan2, METH_VARARGS, math_atan2_doc},
2505 {"atanh", math_atanh, METH_O, math_atanh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002506 MATH_CEIL_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 {"copysign", math_copysign, METH_VARARGS, math_copysign_doc},
2508 {"cos", math_cos, METH_O, math_cos_doc},
2509 {"cosh", math_cosh, METH_O, math_cosh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002510 MATH_DEGREES_METHODDEF
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002511 MATH_DIST_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002512 {"erf", math_erf, METH_O, math_erf_doc},
2513 {"erfc", math_erfc, METH_O, math_erfc_doc},
2514 {"exp", math_exp, METH_O, math_exp_doc},
2515 {"expm1", math_expm1, METH_O, math_expm1_doc},
2516 {"fabs", math_fabs, METH_O, math_fabs_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002517 MATH_FACTORIAL_METHODDEF
2518 MATH_FLOOR_METHODDEF
2519 MATH_FMOD_METHODDEF
2520 MATH_FREXP_METHODDEF
2521 MATH_FSUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 {"gamma", math_gamma, METH_O, math_gamma_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002523 MATH_GCD_METHODDEF
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002524 {"hypot", math_hypot, METH_VARARGS, math_hypot_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002525 MATH_ISCLOSE_METHODDEF
2526 MATH_ISFINITE_METHODDEF
2527 MATH_ISINF_METHODDEF
2528 MATH_ISNAN_METHODDEF
2529 MATH_LDEXP_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002531 MATH_LOG_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532 {"log1p", math_log1p, METH_O, math_log1p_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002533 MATH_LOG10_METHODDEF
2534 MATH_LOG2_METHODDEF
2535 MATH_MODF_METHODDEF
2536 MATH_POW_METHODDEF
2537 MATH_RADIANS_METHODDEF
Mark Dickinsona0ce3752017-04-05 18:34:27 +01002538 {"remainder", math_remainder, METH_VARARGS, math_remainder_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 {"sin", math_sin, METH_O, math_sin_doc},
2540 {"sinh", math_sinh, METH_O, math_sinh_doc},
2541 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
2542 {"tan", math_tan, METH_O, math_tan_doc},
2543 {"tanh", math_tanh, METH_O, math_tanh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002544 MATH_TRUNC_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002546};
2547
Guido van Rossumc6e22901998-12-04 19:26:43 +00002548
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002549PyDoc_STRVAR(module_doc,
Tim Peters63c94532001-09-04 23:17:42 +00002550"This module is always available. It provides access to the\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002551"mathematical functions defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00002552
Martin v. Löwis1a214512008-06-11 05:26:20 +00002553
2554static struct PyModuleDef mathmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 PyModuleDef_HEAD_INIT,
2556 "math",
2557 module_doc,
2558 -1,
2559 math_methods,
2560 NULL,
2561 NULL,
2562 NULL,
2563 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002564};
2565
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002566PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002567PyInit_math(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002568{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002569 PyObject *m;
Tim Petersfe71f812001-08-07 22:10:00 +00002570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002571 m = PyModule_Create(&mathmodule);
2572 if (m == NULL)
2573 goto finally;
Barry Warsawfc93f751996-12-17 00:47:03 +00002574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
2576 PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
Guido van Rossum0a891d72016-08-15 09:12:52 -07002577 PyModule_AddObject(m, "tau", PyFloat_FromDouble(Py_MATH_TAU)); /* 2pi */
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +00002578 PyModule_AddObject(m, "inf", PyFloat_FromDouble(m_inf()));
2579#if !defined(PY_NO_SHORT_FLOAT_REPR) || defined(Py_NAN)
2580 PyModule_AddObject(m, "nan", PyFloat_FromDouble(m_nan()));
2581#endif
Barry Warsawfc93f751996-12-17 00:47:03 +00002582
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +00002583 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002584 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002585}