blob: 77e325cf0c63d36f8be1b556de68962d752a268c [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"
Victor Stinnere9e7d282020-02-12 22:54:42 +010056#include "pycore_dtoa.h"
Mark Dickinson664b5112009-12-16 20:23:42 +000057#include "_math.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000058
Serhiy Storchakac9ea9332017-01-19 18:13:09 +020059#include "clinic/mathmodule.c.h"
60
61/*[clinic input]
62module math
63[clinic start generated code]*/
64/*[clinic end generated code: output=da39a3ee5e6b4b0d input=76bc7002685dd942]*/
65
66
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000067/*
68 sin(pi*x), giving accurate results for all finite x (especially x
69 integral or close to an integer). This is here for use in the
70 reflection formula for the gamma function. It conforms to IEEE
71 754-2008 for finite arguments, but not for infinities or nans.
72*/
Tim Petersa40c7932001-09-05 22:36:56 +000073
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000074static const double pi = 3.141592653589793238462643383279502884197;
Mark Dickinson9c91eb82010-07-07 16:17:31 +000075static const double logpi = 1.144729885849400174143427351353058711647;
Louie Lu7a264642017-03-31 01:05:10 +080076#if !defined(HAVE_ERF) || !defined(HAVE_ERFC)
77static const double sqrtpi = 1.772453850905516027298167483341145182798;
78#endif /* !defined(HAVE_ERF) || !defined(HAVE_ERFC) */
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000079
Raymond Hettingercfd735e2019-01-29 20:39:53 -080080
81/* Version of PyFloat_AsDouble() with in-line fast paths
82 for exact floats and integers. Gives a substantial
83 speed improvement for extracting float arguments.
84*/
85
86#define ASSIGN_DOUBLE(target_var, obj, error_label) \
87 if (PyFloat_CheckExact(obj)) { \
88 target_var = PyFloat_AS_DOUBLE(obj); \
89 } \
90 else if (PyLong_CheckExact(obj)) { \
91 target_var = PyLong_AsDouble(obj); \
92 if (target_var == -1.0 && PyErr_Occurred()) { \
93 goto error_label; \
94 } \
95 } \
96 else { \
97 target_var = PyFloat_AsDouble(obj); \
98 if (target_var == -1.0 && PyErr_Occurred()) { \
99 goto error_label; \
100 } \
101 }
102
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000103static double
Dima Pasechnikf57cd822019-02-26 06:36:11 +0000104m_sinpi(double x)
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000105{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 double y, r;
107 int n;
108 /* this function should only ever be called for finite arguments */
109 assert(Py_IS_FINITE(x));
110 y = fmod(fabs(x), 2.0);
111 n = (int)round(2.0*y);
112 assert(0 <= n && n <= 4);
113 switch (n) {
114 case 0:
115 r = sin(pi*y);
116 break;
117 case 1:
118 r = cos(pi*(y-0.5));
119 break;
120 case 2:
121 /* N.B. -sin(pi*(y-1.0)) is *not* equivalent: it would give
122 -0.0 instead of 0.0 when y == 1.0. */
123 r = sin(pi*(1.0-y));
124 break;
125 case 3:
126 r = -cos(pi*(y-1.5));
127 break;
128 case 4:
129 r = sin(pi*(y-2.0));
130 break;
131 default:
Barry Warsawb2e57942017-09-14 18:13:16 -0700132 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 }
134 return copysign(1.0, x)*r;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000135}
136
137/* Implementation of the real gamma function. In extensive but non-exhaustive
138 random tests, this function proved accurate to within <= 10 ulps across the
139 entire float domain. Note that accuracy may depend on the quality of the
140 system math functions, the pow function in particular. Special cases
141 follow C99 annex F. The parameters and method are tailored to platforms
142 whose double format is the IEEE 754 binary64 format.
143
144 Method: for x > 0.0 we use the Lanczos approximation with parameters N=13
145 and g=6.024680040776729583740234375; these parameters are amongst those
146 used by the Boost library. Following Boost (again), we re-express the
147 Lanczos sum as a rational function, and compute it that way. The
148 coefficients below were computed independently using MPFR, and have been
149 double-checked against the coefficients in the Boost source code.
150
151 For x < 0.0 we use the reflection formula.
152
153 There's one minor tweak that deserves explanation: Lanczos' formula for
154 Gamma(x) involves computing pow(x+g-0.5, x-0.5) / exp(x+g-0.5). For many x
155 values, x+g-0.5 can be represented exactly. However, in cases where it
156 can't be represented exactly the small error in x+g-0.5 can be magnified
157 significantly by the pow and exp calls, especially for large x. A cheap
158 correction is to multiply by (1 + e*g/(x+g-0.5)), where e is the error
159 involved in the computation of x+g-0.5 (that is, e = computed value of
160 x+g-0.5 - exact value of x+g-0.5). Here's the proof:
161
162 Correction factor
163 -----------------
164 Write x+g-0.5 = y-e, where y is exactly representable as an IEEE 754
165 double, and e is tiny. Then:
166
167 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) = pow(y-e, x-0.5)/exp(y-e)
168 = pow(y, x-0.5)/exp(y) * C,
169
170 where the correction_factor C is given by
171
172 C = pow(1-e/y, x-0.5) * exp(e)
173
174 Since e is tiny, pow(1-e/y, x-0.5) ~ 1-(x-0.5)*e/y, and exp(x) ~ 1+e, so:
175
176 C ~ (1-(x-0.5)*e/y) * (1+e) ~ 1 + e*(y-(x-0.5))/y
177
178 But y-(x-0.5) = g+e, and g+e ~ g. So we get C ~ 1 + e*g/y, and
179
180 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) ~ pow(y, x-0.5)/exp(y) * (1 + e*g/y),
181
182 Note that for accuracy, when computing r*C it's better to do
183
184 r + e*g/y*r;
185
186 than
187
188 r * (1 + e*g/y);
189
190 since the addition in the latter throws away most of the bits of
191 information in e*g/y.
192*/
193
194#define LANCZOS_N 13
195static const double lanczos_g = 6.024680040776729583740234375;
196static const double lanczos_g_minus_half = 5.524680040776729583740234375;
197static const double lanczos_num_coeffs[LANCZOS_N] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 23531376880.410759688572007674451636754734846804940,
199 42919803642.649098768957899047001988850926355848959,
200 35711959237.355668049440185451547166705960488635843,
201 17921034426.037209699919755754458931112671403265390,
202 6039542586.3520280050642916443072979210699388420708,
203 1439720407.3117216736632230727949123939715485786772,
204 248874557.86205415651146038641322942321632125127801,
205 31426415.585400194380614231628318205362874684987640,
206 2876370.6289353724412254090516208496135991145378768,
207 186056.26539522349504029498971604569928220784236328,
208 8071.6720023658162106380029022722506138218516325024,
209 210.82427775157934587250973392071336271166969580291,
210 2.5066282746310002701649081771338373386264310793408
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000211};
212
213/* denominator is x*(x+1)*...*(x+LANCZOS_N-2) */
214static const double lanczos_den_coeffs[LANCZOS_N] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000215 0.0, 39916800.0, 120543840.0, 150917976.0, 105258076.0, 45995730.0,
216 13339535.0, 2637558.0, 357423.0, 32670.0, 1925.0, 66.0, 1.0};
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000217
218/* gamma values for small positive integers, 1 though NGAMMA_INTEGRAL */
219#define NGAMMA_INTEGRAL 23
220static const double gamma_integral[NGAMMA_INTEGRAL] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0,
222 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0,
223 1307674368000.0, 20922789888000.0, 355687428096000.0,
224 6402373705728000.0, 121645100408832000.0, 2432902008176640000.0,
225 51090942171709440000.0, 1124000727777607680000.0,
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000226};
227
228/* Lanczos' sum L_g(x), for positive x */
229
230static double
231lanczos_sum(double x)
232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 double num = 0.0, den = 0.0;
234 int i;
235 assert(x > 0.0);
236 /* evaluate the rational function lanczos_sum(x). For large
237 x, the obvious algorithm risks overflow, so we instead
238 rescale the denominator and numerator of the rational
239 function by x**(1-LANCZOS_N) and treat this as a
240 rational function in 1/x. This also reduces the error for
241 larger x values. The choice of cutoff point (5.0 below) is
242 somewhat arbitrary; in tests, smaller cutoff values than
243 this resulted in lower accuracy. */
244 if (x < 5.0) {
245 for (i = LANCZOS_N; --i >= 0; ) {
246 num = num * x + lanczos_num_coeffs[i];
247 den = den * x + lanczos_den_coeffs[i];
248 }
249 }
250 else {
251 for (i = 0; i < LANCZOS_N; i++) {
252 num = num / x + lanczos_num_coeffs[i];
253 den = den / x + lanczos_den_coeffs[i];
254 }
255 }
256 return num/den;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000257}
258
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +0000259/* Constant for +infinity, generated in the same way as float('inf'). */
260
261static double
262m_inf(void)
263{
264#ifndef PY_NO_SHORT_FLOAT_REPR
265 return _Py_dg_infinity(0);
266#else
267 return Py_HUGE_VAL;
268#endif
269}
270
271/* Constant nan value, generated in the same way as float('nan'). */
272/* We don't currently assume that Py_NAN is defined everywhere. */
273
274#if !defined(PY_NO_SHORT_FLOAT_REPR) || defined(Py_NAN)
275
276static double
277m_nan(void)
278{
279#ifndef PY_NO_SHORT_FLOAT_REPR
280 return _Py_dg_stdnan(0);
281#else
282 return Py_NAN;
283#endif
284}
285
286#endif
287
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000288static double
289m_tgamma(double x)
290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 double absx, r, y, z, sqrtpow;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 /* special cases */
294 if (!Py_IS_FINITE(x)) {
295 if (Py_IS_NAN(x) || x > 0.0)
296 return x; /* tgamma(nan) = nan, tgamma(inf) = inf */
297 else {
298 errno = EDOM;
299 return Py_NAN; /* tgamma(-inf) = nan, invalid */
300 }
301 }
302 if (x == 0.0) {
303 errno = EDOM;
Mark Dickinson50203a62011-09-25 15:26:43 +0100304 /* tgamma(+-0.0) = +-inf, divide-by-zero */
305 return copysign(Py_HUGE_VAL, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 /* integer arguments */
309 if (x == floor(x)) {
310 if (x < 0.0) {
311 errno = EDOM; /* tgamma(n) = nan, invalid for */
312 return Py_NAN; /* negative integers n */
313 }
314 if (x <= NGAMMA_INTEGRAL)
315 return gamma_integral[(int)x - 1];
316 }
317 absx = fabs(x);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 /* tiny arguments: tgamma(x) ~ 1/x for x near 0 */
320 if (absx < 1e-20) {
321 r = 1.0/x;
322 if (Py_IS_INFINITY(r))
323 errno = ERANGE;
324 return r;
325 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 /* large arguments: assuming IEEE 754 doubles, tgamma(x) overflows for
328 x > 200, and underflows to +-0.0 for x < -200, not a negative
329 integer. */
330 if (absx > 200.0) {
331 if (x < 0.0) {
Dima Pasechnikf57cd822019-02-26 06:36:11 +0000332 return 0.0/m_sinpi(x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 }
334 else {
335 errno = ERANGE;
336 return Py_HUGE_VAL;
337 }
338 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 y = absx + lanczos_g_minus_half;
341 /* compute error in sum */
342 if (absx > lanczos_g_minus_half) {
343 /* note: the correction can be foiled by an optimizing
344 compiler that (incorrectly) thinks that an expression like
345 a + b - a - b can be optimized to 0.0. This shouldn't
346 happen in a standards-conforming compiler. */
347 double q = y - absx;
348 z = q - lanczos_g_minus_half;
349 }
350 else {
351 double q = y - lanczos_g_minus_half;
352 z = q - absx;
353 }
354 z = z * lanczos_g / y;
355 if (x < 0.0) {
Dima Pasechnikf57cd822019-02-26 06:36:11 +0000356 r = -pi / m_sinpi(absx) / absx * exp(y) / lanczos_sum(absx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 r -= z * r;
358 if (absx < 140.0) {
359 r /= pow(y, absx - 0.5);
360 }
361 else {
362 sqrtpow = pow(y, absx / 2.0 - 0.25);
363 r /= sqrtpow;
364 r /= sqrtpow;
365 }
366 }
367 else {
368 r = lanczos_sum(absx) / exp(y);
369 r += z * r;
370 if (absx < 140.0) {
371 r *= pow(y, absx - 0.5);
372 }
373 else {
374 sqrtpow = pow(y, absx / 2.0 - 0.25);
375 r *= sqrtpow;
376 r *= sqrtpow;
377 }
378 }
379 if (Py_IS_INFINITY(r))
380 errno = ERANGE;
381 return r;
Guido van Rossum8832b621991-12-16 15:44:24 +0000382}
383
Christian Heimes53876d92008-04-19 00:31:39 +0000384/*
Mark Dickinson05d2e082009-12-11 20:17:17 +0000385 lgamma: natural log of the absolute value of the Gamma function.
386 For large arguments, Lanczos' formula works extremely well here.
387*/
388
389static double
390m_lgamma(double x)
391{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200392 double r;
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200393 double absx;
Mark Dickinson05d2e082009-12-11 20:17:17 +0000394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 /* special cases */
396 if (!Py_IS_FINITE(x)) {
397 if (Py_IS_NAN(x))
398 return x; /* lgamma(nan) = nan */
399 else
400 return Py_HUGE_VAL; /* lgamma(+-inf) = +inf */
401 }
Mark Dickinson05d2e082009-12-11 20:17:17 +0000402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 /* integer arguments */
404 if (x == floor(x) && x <= 2.0) {
405 if (x <= 0.0) {
406 errno = EDOM; /* lgamma(n) = inf, divide-by-zero for */
407 return Py_HUGE_VAL; /* integers n <= 0 */
408 }
409 else {
410 return 0.0; /* lgamma(1) = lgamma(2) = 0.0 */
411 }
412 }
Mark Dickinson05d2e082009-12-11 20:17:17 +0000413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 absx = fabs(x);
415 /* tiny arguments: lgamma(x) ~ -log(fabs(x)) for small x */
416 if (absx < 1e-20)
417 return -log(absx);
Mark Dickinson05d2e082009-12-11 20:17:17 +0000418
Mark Dickinson9c91eb82010-07-07 16:17:31 +0000419 /* Lanczos' formula. We could save a fraction of a ulp in accuracy by
420 having a second set of numerator coefficients for lanczos_sum that
421 absorbed the exp(-lanczos_g) term, and throwing out the lanczos_g
422 subtraction below; it's probably not worth it. */
423 r = log(lanczos_sum(absx)) - lanczos_g;
424 r += (absx - 0.5) * (log(absx + lanczos_g - 0.5) - 1);
425 if (x < 0.0)
426 /* Use reflection formula to get value for negative x. */
Dima Pasechnikf57cd822019-02-26 06:36:11 +0000427 r = logpi - log(fabs(m_sinpi(absx))) - log(absx) - r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 if (Py_IS_INFINITY(r))
429 errno = ERANGE;
430 return r;
Mark Dickinson05d2e082009-12-11 20:17:17 +0000431}
432
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200433#if !defined(HAVE_ERF) || !defined(HAVE_ERFC)
434
Mark Dickinson45f992a2009-12-19 11:20:49 +0000435/*
436 Implementations of the error function erf(x) and the complementary error
437 function erfc(x).
438
Brett Cannon45adb312016-01-15 09:38:24 -0800439 Method: we use a series approximation for erf for small x, and a continued
440 fraction approximation for erfc(x) for larger x;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000441 combined with the relations erf(-x) = -erf(x) and erfc(x) = 1.0 - erf(x),
442 this gives us erf(x) and erfc(x) for all x.
443
444 The series expansion used is:
445
446 erf(x) = x*exp(-x*x)/sqrt(pi) * [
447 2/1 + 4/3 x**2 + 8/15 x**4 + 16/105 x**6 + ...]
448
449 The coefficient of x**(2k-2) here is 4**k*factorial(k)/factorial(2*k).
450 This series converges well for smallish x, but slowly for larger x.
451
452 The continued fraction expansion used is:
453
454 erfc(x) = x*exp(-x*x)/sqrt(pi) * [1/(0.5 + x**2 -) 0.5/(2.5 + x**2 - )
455 3.0/(4.5 + x**2 - ) 7.5/(6.5 + x**2 - ) ...]
456
457 after the first term, the general term has the form:
458
459 k*(k-0.5)/(2*k+0.5 + x**2 - ...).
460
461 This expansion converges fast for larger x, but convergence becomes
462 infinitely slow as x approaches 0.0. The (somewhat naive) continued
463 fraction evaluation algorithm used below also risks overflow for large x;
464 but for large x, erfc(x) == 0.0 to within machine precision. (For
465 example, erfc(30.0) is approximately 2.56e-393).
466
467 Parameters: use series expansion for abs(x) < ERF_SERIES_CUTOFF and
468 continued fraction expansion for ERF_SERIES_CUTOFF <= abs(x) <
469 ERFC_CONTFRAC_CUTOFF. ERFC_SERIES_TERMS and ERFC_CONTFRAC_TERMS are the
470 numbers of terms to use for the relevant expansions. */
471
472#define ERF_SERIES_CUTOFF 1.5
473#define ERF_SERIES_TERMS 25
474#define ERFC_CONTFRAC_CUTOFF 30.0
475#define ERFC_CONTFRAC_TERMS 50
476
477/*
478 Error function, via power series.
479
480 Given a finite float x, return an approximation to erf(x).
481 Converges reasonably fast for small x.
482*/
483
484static double
485m_erf_series(double x)
486{
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000487 double x2, acc, fk, result;
488 int i, saved_errno;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 x2 = x * x;
491 acc = 0.0;
492 fk = (double)ERF_SERIES_TERMS + 0.5;
493 for (i = 0; i < ERF_SERIES_TERMS; i++) {
494 acc = 2.0 + x2 * acc / fk;
495 fk -= 1.0;
496 }
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000497 /* Make sure the exp call doesn't affect errno;
498 see m_erfc_contfrac for more. */
499 saved_errno = errno;
500 result = acc * x * exp(-x2) / sqrtpi;
501 errno = saved_errno;
502 return result;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000503}
504
505/*
506 Complementary error function, via continued fraction expansion.
507
508 Given a positive float x, return an approximation to erfc(x). Converges
509 reasonably fast for x large (say, x > 2.0), and should be safe from
510 overflow if x and nterms are not too large. On an IEEE 754 machine, with x
511 <= 30.0, we're safe up to nterms = 100. For x >= 30.0, erfc(x) is smaller
512 than the smallest representable nonzero float. */
513
514static double
515m_erfc_contfrac(double x)
516{
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000517 double x2, a, da, p, p_last, q, q_last, b, result;
518 int i, saved_errno;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 if (x >= ERFC_CONTFRAC_CUTOFF)
521 return 0.0;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 x2 = x*x;
524 a = 0.0;
525 da = 0.5;
526 p = 1.0; p_last = 0.0;
527 q = da + x2; q_last = 1.0;
528 for (i = 0; i < ERFC_CONTFRAC_TERMS; i++) {
529 double temp;
530 a += da;
531 da += 2.0;
532 b = da + x2;
533 temp = p; p = b*p - a*p_last; p_last = temp;
534 temp = q; q = b*q - a*q_last; q_last = temp;
535 }
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000536 /* Issue #8986: On some platforms, exp sets errno on underflow to zero;
537 save the current errno value so that we can restore it later. */
538 saved_errno = errno;
539 result = p / q * x * exp(-x2) / sqrtpi;
540 errno = saved_errno;
541 return result;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000542}
543
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200544#endif /* !defined(HAVE_ERF) || !defined(HAVE_ERFC) */
545
Mark Dickinson45f992a2009-12-19 11:20:49 +0000546/* Error function erf(x), for general x */
547
548static double
549m_erf(double x)
550{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200551#ifdef HAVE_ERF
552 return erf(x);
553#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 double absx, cf;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 if (Py_IS_NAN(x))
557 return x;
558 absx = fabs(x);
559 if (absx < ERF_SERIES_CUTOFF)
560 return m_erf_series(x);
561 else {
562 cf = m_erfc_contfrac(absx);
563 return x > 0.0 ? 1.0 - cf : cf - 1.0;
564 }
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200565#endif
Mark Dickinson45f992a2009-12-19 11:20:49 +0000566}
567
568/* Complementary error function erfc(x), for general x. */
569
570static double
571m_erfc(double x)
572{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200573#ifdef HAVE_ERFC
574 return erfc(x);
575#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 double absx, cf;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 if (Py_IS_NAN(x))
579 return x;
580 absx = fabs(x);
581 if (absx < ERF_SERIES_CUTOFF)
582 return 1.0 - m_erf_series(x);
583 else {
584 cf = m_erfc_contfrac(absx);
585 return x > 0.0 ? cf : 2.0 - cf;
586 }
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200587#endif
Mark Dickinson45f992a2009-12-19 11:20:49 +0000588}
Mark Dickinson05d2e082009-12-11 20:17:17 +0000589
590/*
Christian Heimese57950f2008-04-21 13:08:03 +0000591 wrapper for atan2 that deals directly with special cases before
592 delegating to the platform libm for the remaining cases. This
593 is necessary to get consistent behaviour across platforms.
594 Windows, FreeBSD and alpha Tru64 are amongst platforms that don't
595 always follow C99.
596*/
597
598static double
599m_atan2(double y, double x)
600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 if (Py_IS_NAN(x) || Py_IS_NAN(y))
602 return Py_NAN;
603 if (Py_IS_INFINITY(y)) {
604 if (Py_IS_INFINITY(x)) {
605 if (copysign(1., x) == 1.)
606 /* atan2(+-inf, +inf) == +-pi/4 */
607 return copysign(0.25*Py_MATH_PI, y);
608 else
609 /* atan2(+-inf, -inf) == +-pi*3/4 */
610 return copysign(0.75*Py_MATH_PI, y);
611 }
612 /* atan2(+-inf, x) == +-pi/2 for finite x */
613 return copysign(0.5*Py_MATH_PI, y);
614 }
615 if (Py_IS_INFINITY(x) || y == 0.) {
616 if (copysign(1., x) == 1.)
617 /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */
618 return copysign(0., y);
619 else
620 /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */
621 return copysign(Py_MATH_PI, y);
622 }
623 return atan2(y, x);
Christian Heimese57950f2008-04-21 13:08:03 +0000624}
625
Mark Dickinsona0ce3752017-04-05 18:34:27 +0100626
627/* IEEE 754-style remainder operation: x - n*y where n*y is the nearest
628 multiple of y to x, taking n even in the case of a tie. Assuming an IEEE 754
629 binary floating-point format, the result is always exact. */
630
631static double
632m_remainder(double x, double y)
633{
634 /* Deal with most common case first. */
635 if (Py_IS_FINITE(x) && Py_IS_FINITE(y)) {
636 double absx, absy, c, m, r;
637
638 if (y == 0.0) {
639 return Py_NAN;
640 }
641
642 absx = fabs(x);
643 absy = fabs(y);
644 m = fmod(absx, absy);
645
646 /*
647 Warning: some subtlety here. What we *want* to know at this point is
648 whether the remainder m is less than, equal to, or greater than half
649 of absy. However, we can't do that comparison directly because we
Mark Dickinson01484702019-07-13 16:50:03 +0100650 can't be sure that 0.5*absy is representable (the multiplication
Mark Dickinsona0ce3752017-04-05 18:34:27 +0100651 might incur precision loss due to underflow). So instead we compare
652 m with the complement c = absy - m: m < 0.5*absy if and only if m <
653 c, and so on. The catch is that absy - m might also not be
654 representable, but it turns out that it doesn't matter:
655
656 - if m > 0.5*absy then absy - m is exactly representable, by
657 Sterbenz's lemma, so m > c
658 - if m == 0.5*absy then again absy - m is exactly representable
659 and m == c
660 - if m < 0.5*absy then either (i) 0.5*absy is exactly representable,
661 in which case 0.5*absy < absy - m, so 0.5*absy <= c and hence m <
662 c, or (ii) absy is tiny, either subnormal or in the lowest normal
663 binade. Then absy - m is exactly representable and again m < c.
664 */
665
666 c = absy - m;
667 if (m < c) {
668 r = m;
669 }
670 else if (m > c) {
671 r = -c;
672 }
673 else {
674 /*
675 Here absx is exactly halfway between two multiples of absy,
676 and we need to choose the even multiple. x now has the form
677
678 absx = n * absy + m
679
680 for some integer n (recalling that m = 0.5*absy at this point).
681 If n is even we want to return m; if n is odd, we need to
682 return -m.
683
684 So
685
686 0.5 * (absx - m) = (n/2) * absy
687
688 and now reducing modulo absy gives us:
689
690 | m, if n is odd
691 fmod(0.5 * (absx - m), absy) = |
692 | 0, if n is even
693
694 Now m - 2.0 * fmod(...) gives the desired result: m
695 if n is even, -m if m is odd.
696
697 Note that all steps in fmod(0.5 * (absx - m), absy)
698 will be computed exactly, with no rounding error
699 introduced.
700 */
701 assert(m == c);
702 r = m - 2.0 * fmod(0.5 * (absx - m), absy);
703 }
704 return copysign(1.0, x) * r;
705 }
706
707 /* Special values. */
708 if (Py_IS_NAN(x)) {
709 return x;
710 }
711 if (Py_IS_NAN(y)) {
712 return y;
713 }
714 if (Py_IS_INFINITY(x)) {
715 return Py_NAN;
716 }
717 assert(Py_IS_INFINITY(y));
718 return x;
719}
720
721
Christian Heimese57950f2008-04-21 13:08:03 +0000722/*
Mark Dickinsone675f082008-12-11 21:56:00 +0000723 Various platforms (Solaris, OpenBSD) do nonstandard things for log(0),
724 log(-ve), log(NaN). Here are wrappers for log and log10 that deal with
725 special values directly, passing positive non-special values through to
726 the system log/log10.
727 */
728
729static double
730m_log(double x)
731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 if (Py_IS_FINITE(x)) {
733 if (x > 0.0)
734 return log(x);
735 errno = EDOM;
736 if (x == 0.0)
737 return -Py_HUGE_VAL; /* log(0) = -inf */
738 else
739 return Py_NAN; /* log(-ve) = nan */
740 }
741 else if (Py_IS_NAN(x))
742 return x; /* log(nan) = nan */
743 else if (x > 0.0)
744 return x; /* log(inf) = inf */
745 else {
746 errno = EDOM;
747 return Py_NAN; /* log(-inf) = nan */
748 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000749}
750
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200751/*
752 log2: log to base 2.
753
754 Uses an algorithm that should:
Mark Dickinson83b8c0b2011-05-09 08:40:20 +0100755
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200756 (a) produce exact results for powers of 2, and
Mark Dickinson83b8c0b2011-05-09 08:40:20 +0100757 (b) give a monotonic log2 (for positive finite floats),
758 assuming that the system log is monotonic.
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200759*/
760
761static double
762m_log2(double x)
763{
764 if (!Py_IS_FINITE(x)) {
765 if (Py_IS_NAN(x))
766 return x; /* log2(nan) = nan */
767 else if (x > 0.0)
768 return x; /* log2(+inf) = +inf */
769 else {
770 errno = EDOM;
771 return Py_NAN; /* log2(-inf) = nan, invalid-operation */
772 }
773 }
774
775 if (x > 0.0) {
Victor Stinner8f9f8d62011-05-09 12:45:41 +0200776#ifdef HAVE_LOG2
777 return log2(x);
778#else
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200779 double m;
780 int e;
781 m = frexp(x, &e);
782 /* We want log2(m * 2**e) == log(m) / log(2) + e. Care is needed when
783 * x is just greater than 1.0: in that case e is 1, log(m) is negative,
784 * and we get significant cancellation error from the addition of
785 * log(m) / log(2) to e. The slight rewrite of the expression below
786 * avoids this problem.
787 */
788 if (x >= 1.0) {
789 return log(2.0 * m) / log(2.0) + (e - 1);
790 }
791 else {
792 return log(m) / log(2.0) + e;
793 }
Victor Stinner8f9f8d62011-05-09 12:45:41 +0200794#endif
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200795 }
796 else if (x == 0.0) {
797 errno = EDOM;
798 return -Py_HUGE_VAL; /* log2(0) = -inf, divide-by-zero */
799 }
800 else {
801 errno = EDOM;
Mark Dickinson23442582011-05-09 08:05:00 +0100802 return Py_NAN; /* log2(-inf) = nan, invalid-operation */
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200803 }
804}
805
Mark Dickinsone675f082008-12-11 21:56:00 +0000806static double
807m_log10(double x)
808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 if (Py_IS_FINITE(x)) {
810 if (x > 0.0)
811 return log10(x);
812 errno = EDOM;
813 if (x == 0.0)
814 return -Py_HUGE_VAL; /* log10(0) = -inf */
815 else
816 return Py_NAN; /* log10(-ve) = nan */
817 }
818 else if (Py_IS_NAN(x))
819 return x; /* log10(nan) = nan */
820 else if (x > 0.0)
821 return x; /* log10(inf) = inf */
822 else {
823 errno = EDOM;
824 return Py_NAN; /* log10(-inf) = nan */
825 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000826}
827
828
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200829static PyObject *
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200830math_gcd(PyObject *module, PyObject * const *args, Py_ssize_t nargs)
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200831{
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200832 PyObject *res, *x;
833 Py_ssize_t i;
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300834
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200835 if (nargs == 0) {
836 return PyLong_FromLong(0);
837 }
838 res = PyNumber_Index(args[0]);
839 if (res == NULL) {
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300840 return NULL;
841 }
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200842 if (nargs == 1) {
843 Py_SETREF(res, PyNumber_Absolute(res));
844 return res;
845 }
846 for (i = 1; i < nargs; i++) {
847 x = PyNumber_Index(args[i]);
848 if (x == NULL) {
849 Py_DECREF(res);
850 return NULL;
851 }
852 if (res == _PyLong_One) {
853 /* Fast path: just check arguments.
854 It is okay to use identity comparison here. */
855 Py_DECREF(x);
856 continue;
857 }
858 Py_SETREF(res, _PyLong_GCD(res, x));
859 Py_DECREF(x);
860 if (res == NULL) {
861 return NULL;
862 }
863 }
864 return res;
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300865}
866
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200867PyDoc_STRVAR(math_gcd_doc,
868"gcd($module, *integers)\n"
869"--\n"
870"\n"
871"Greatest Common Divisor.");
872
873
874static PyObject *
875long_lcm(PyObject *a, PyObject *b)
876{
877 PyObject *g, *m, *f, *ab;
878
879 if (Py_SIZE(a) == 0 || Py_SIZE(b) == 0) {
880 return PyLong_FromLong(0);
881 }
882 g = _PyLong_GCD(a, b);
883 if (g == NULL) {
884 return NULL;
885 }
886 f = PyNumber_FloorDivide(a, g);
887 Py_DECREF(g);
888 if (f == NULL) {
889 return NULL;
890 }
891 m = PyNumber_Multiply(f, b);
892 Py_DECREF(f);
893 if (m == NULL) {
894 return NULL;
895 }
896 ab = PyNumber_Absolute(m);
897 Py_DECREF(m);
898 return ab;
899}
900
901
902static PyObject *
903math_lcm(PyObject *module, PyObject * const *args, Py_ssize_t nargs)
904{
905 PyObject *res, *x;
906 Py_ssize_t i;
907
908 if (nargs == 0) {
909 return PyLong_FromLong(1);
910 }
911 res = PyNumber_Index(args[0]);
912 if (res == NULL) {
913 return NULL;
914 }
915 if (nargs == 1) {
916 Py_SETREF(res, PyNumber_Absolute(res));
917 return res;
918 }
919 for (i = 1; i < nargs; i++) {
920 x = PyNumber_Index(args[i]);
921 if (x == NULL) {
922 Py_DECREF(res);
923 return NULL;
924 }
925 if (res == _PyLong_Zero) {
926 /* Fast path: just check arguments.
927 It is okay to use identity comparison here. */
928 Py_DECREF(x);
929 continue;
930 }
931 Py_SETREF(res, long_lcm(res, x));
932 Py_DECREF(x);
933 if (res == NULL) {
934 return NULL;
935 }
936 }
937 return res;
938}
939
940
941PyDoc_STRVAR(math_lcm_doc,
942"lcm($module, *integers)\n"
943"--\n"
944"\n"
945"Least Common Multiple.");
946
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300947
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000948/* Call is_error when errno != 0, and where x is the result libm
949 * returned. is_error will usually set up an exception and return
950 * true (1), but may return false (0) without setting up an exception.
951 */
952static int
953is_error(double x)
954{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 int result = 1; /* presumption of guilt */
956 assert(errno); /* non-zero errno is a precondition for calling */
957 if (errno == EDOM)
958 PyErr_SetString(PyExc_ValueError, "math domain error");
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 else if (errno == ERANGE) {
961 /* ANSI C generally requires libm functions to set ERANGE
962 * on overflow, but also generally *allows* them to set
963 * ERANGE on underflow too. There's no consistency about
964 * the latter across platforms.
965 * Alas, C99 never requires that errno be set.
966 * Here we suppress the underflow errors (libm functions
967 * should return a zero on underflow, and +- HUGE_VAL on
968 * overflow, so testing the result for zero suffices to
969 * distinguish the cases).
970 *
971 * On some platforms (Ubuntu/ia64) it seems that errno can be
972 * set to ERANGE for subnormal results that do *not* underflow
973 * to zero. So to be safe, we'll ignore ERANGE whenever the
974 * function result is less than one in absolute value.
975 */
976 if (fabs(x) < 1.0)
977 result = 0;
978 else
979 PyErr_SetString(PyExc_OverflowError,
980 "math range error");
981 }
982 else
983 /* Unexpected math error */
984 PyErr_SetFromErrno(PyExc_ValueError);
985 return result;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000986}
987
Mark Dickinsone675f082008-12-11 21:56:00 +0000988/*
Christian Heimes53876d92008-04-19 00:31:39 +0000989 math_1 is used to wrap a libm function f that takes a double
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200990 argument and returns a double.
Christian Heimes53876d92008-04-19 00:31:39 +0000991
992 The error reporting follows these rules, which are designed to do
993 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
994 platforms.
995
996 - a NaN result from non-NaN inputs causes ValueError to be raised
997 - an infinite result from finite inputs causes OverflowError to be
998 raised if can_overflow is 1, or raises ValueError if can_overflow
999 is 0.
1000 - if the result is finite and errno == EDOM then ValueError is
1001 raised
1002 - if the result is finite and nonzero and errno == ERANGE then
1003 OverflowError is raised
1004
1005 The last rule is used to catch overflow on platforms which follow
1006 C89 but for which HUGE_VAL is not an infinity.
1007
1008 For the majority of one-argument functions these rules are enough
1009 to ensure that Python's functions behave as specified in 'Annex F'
1010 of the C99 standard, with the 'invalid' and 'divide-by-zero'
1011 floating-point exceptions mapping to Python's ValueError and the
1012 'overflow' floating-point exception mapping to OverflowError.
1013 math_1 only works for functions that don't have singularities *and*
1014 the possibility of overflow; fortunately, that covers everything we
1015 care about right now.
1016*/
1017
Barry Warsaw8b43b191996-12-09 22:32:36 +00001018static PyObject *
Jeffrey Yasskinc2155832008-01-05 20:03:11 +00001019math_1_to_whatever(PyObject *arg, double (*func) (double),
Christian Heimes53876d92008-04-19 00:31:39 +00001020 PyObject *(*from_double_func) (double),
1021 int can_overflow)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001022{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 double x, r;
1024 x = PyFloat_AsDouble(arg);
1025 if (x == -1.0 && PyErr_Occurred())
1026 return NULL;
1027 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 r = (*func)(x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 if (Py_IS_NAN(r) && !Py_IS_NAN(x)) {
1030 PyErr_SetString(PyExc_ValueError,
1031 "math domain error"); /* invalid arg */
1032 return NULL;
1033 }
1034 if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) {
Benjamin Peterson2354a752012-03-13 16:13:09 -05001035 if (can_overflow)
1036 PyErr_SetString(PyExc_OverflowError,
1037 "math range error"); /* overflow */
1038 else
1039 PyErr_SetString(PyExc_ValueError,
1040 "math domain error"); /* singularity */
1041 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 }
1043 if (Py_IS_FINITE(r) && errno && is_error(r))
1044 /* this branch unnecessary on most platforms */
1045 return NULL;
Mark Dickinsonde429622008-05-01 00:19:23 +00001046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 return (*from_double_func)(r);
Christian Heimes53876d92008-04-19 00:31:39 +00001048}
1049
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001050/* variant of math_1, to be used when the function being wrapped is known to
1051 set errno properly (that is, errno = EDOM for invalid or divide-by-zero,
1052 errno = ERANGE for overflow). */
1053
1054static PyObject *
1055math_1a(PyObject *arg, double (*func) (double))
1056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 double x, r;
1058 x = PyFloat_AsDouble(arg);
1059 if (x == -1.0 && PyErr_Occurred())
1060 return NULL;
1061 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 r = (*func)(x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 if (errno && is_error(r))
1064 return NULL;
1065 return PyFloat_FromDouble(r);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001066}
1067
Christian Heimes53876d92008-04-19 00:31:39 +00001068/*
1069 math_2 is used to wrap a libm function f that takes two double
1070 arguments and returns a double.
1071
1072 The error reporting follows these rules, which are designed to do
1073 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
1074 platforms.
1075
1076 - a NaN result from non-NaN inputs causes ValueError to be raised
1077 - an infinite result from finite inputs causes OverflowError to be
1078 raised.
1079 - if the result is finite and errno == EDOM then ValueError is
1080 raised
1081 - if the result is finite and nonzero and errno == ERANGE then
1082 OverflowError is raised
1083
1084 The last rule is used to catch overflow on platforms which follow
1085 C89 but for which HUGE_VAL is not an infinity.
1086
1087 For most two-argument functions (copysign, fmod, hypot, atan2)
1088 these rules are enough to ensure that Python's functions behave as
1089 specified in 'Annex F' of the C99 standard, with the 'invalid' and
1090 'divide-by-zero' floating-point exceptions mapping to Python's
1091 ValueError and the 'overflow' floating-point exception mapping to
1092 OverflowError.
1093*/
1094
1095static PyObject *
1096math_1(PyObject *arg, double (*func) (double), int can_overflow)
1097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow);
Jeffrey Yasskinc2155832008-01-05 20:03:11 +00001099}
1100
1101static PyObject *
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02001102math_2(PyObject *const *args, Py_ssize_t nargs,
1103 double (*func) (double, double), const char *funcname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001104{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 double x, y, r;
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02001106 if (!_PyArg_CheckPositional(funcname, nargs, 2, 2))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 return NULL;
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02001108 x = PyFloat_AsDouble(args[0]);
1109 y = PyFloat_AsDouble(args[1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1111 return NULL;
1112 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 r = (*func)(x, y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 if (Py_IS_NAN(r)) {
1115 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1116 errno = EDOM;
1117 else
1118 errno = 0;
1119 }
1120 else if (Py_IS_INFINITY(r)) {
1121 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
1122 errno = ERANGE;
1123 else
1124 errno = 0;
1125 }
1126 if (errno && is_error(r))
1127 return NULL;
1128 else
1129 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001130}
1131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132#define FUNC1(funcname, func, can_overflow, docstring) \
1133 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
1134 return math_1(args, func, can_overflow); \
1135 }\
1136 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138#define FUNC1A(funcname, func, docstring) \
1139 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
1140 return math_1a(args, func); \
1141 }\
1142 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001143
Fred Drake40c48682000-07-03 18:11:56 +00001144#define FUNC2(funcname, func, docstring) \
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02001145 static PyObject * math_##funcname(PyObject *self, PyObject *const *args, Py_ssize_t nargs) { \
1146 return math_2(args, nargs, func, #funcname); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 }\
1148 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001149
Christian Heimes53876d92008-04-19 00:31:39 +00001150FUNC1(acos, acos, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001151 "acos($module, x, /)\n--\n\n"
Giovanni Cappellottodc3f99f2019-07-13 09:59:55 -04001152 "Return the arc cosine (measured in radians) of x.\n\n"
1153 "The result is between 0 and pi.")
Mark Dickinsonf3718592009-12-21 15:27:41 +00001154FUNC1(acosh, m_acosh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001155 "acosh($module, x, /)\n--\n\n"
1156 "Return the inverse hyperbolic cosine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001157FUNC1(asin, asin, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001158 "asin($module, x, /)\n--\n\n"
Giovanni Cappellottodc3f99f2019-07-13 09:59:55 -04001159 "Return the arc sine (measured in radians) of x.\n\n"
1160 "The result is between -pi/2 and pi/2.")
Mark Dickinsonf3718592009-12-21 15:27:41 +00001161FUNC1(asinh, m_asinh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001162 "asinh($module, x, /)\n--\n\n"
1163 "Return the inverse hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001164FUNC1(atan, atan, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001165 "atan($module, x, /)\n--\n\n"
Giovanni Cappellottodc3f99f2019-07-13 09:59:55 -04001166 "Return the arc tangent (measured in radians) of x.\n\n"
1167 "The result is between -pi/2 and pi/2.")
Christian Heimese57950f2008-04-21 13:08:03 +00001168FUNC2(atan2, m_atan2,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001169 "atan2($module, y, x, /)\n--\n\n"
1170 "Return the arc tangent (measured in radians) of y/x.\n\n"
Tim Petersfe71f812001-08-07 22:10:00 +00001171 "Unlike atan(y/x), the signs of both x and y are considered.")
Mark Dickinsonf3718592009-12-21 15:27:41 +00001172FUNC1(atanh, m_atanh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001173 "atanh($module, x, /)\n--\n\n"
1174 "Return the inverse hyperbolic tangent of x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +00001175
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001176/*[clinic input]
1177math.ceil
1178
1179 x as number: object
1180 /
1181
1182Return the ceiling of x as an Integral.
1183
1184This is the smallest integer >= x.
1185[clinic start generated code]*/
1186
1187static PyObject *
1188math_ceil(PyObject *module, PyObject *number)
1189/*[clinic end generated code: output=6c3b8a78bc201c67 input=2725352806399cab]*/
1190{
Benjamin Petersonce798522012-01-22 11:24:29 -05001191 _Py_IDENTIFIER(__ceil__);
Guido van Rossum13e05de2007-08-23 22:56:55 +00001192
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001193 if (!PyFloat_CheckExact(number)) {
1194 PyObject *method = _PyObject_LookupSpecial(number, &PyId___ceil__);
1195 if (method != NULL) {
1196 PyObject *result = _PyObject_CallNoArg(method);
1197 Py_DECREF(method);
1198 return result;
1199 }
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001200 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 return NULL;
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001202 }
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001203 double x = PyFloat_AsDouble(number);
1204 if (x == -1.0 && PyErr_Occurred())
1205 return NULL;
1206
1207 return PyLong_FromDouble(ceil(x));
Guido van Rossum13e05de2007-08-23 22:56:55 +00001208}
1209
Christian Heimes072c0f12008-01-03 23:01:04 +00001210FUNC2(copysign, copysign,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001211 "copysign($module, x, y, /)\n--\n\n"
1212 "Return a float with the magnitude (absolute value) of x but the sign of y.\n\n"
1213 "On platforms that support signed zeros, copysign(1.0, -0.0)\n"
1214 "returns -1.0.\n")
Christian Heimes53876d92008-04-19 00:31:39 +00001215FUNC1(cos, cos, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001216 "cos($module, x, /)\n--\n\n"
1217 "Return the cosine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001218FUNC1(cosh, cosh, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001219 "cosh($module, x, /)\n--\n\n"
1220 "Return the hyperbolic cosine of x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +00001221FUNC1A(erf, m_erf,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001222 "erf($module, x, /)\n--\n\n"
1223 "Error function at x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +00001224FUNC1A(erfc, m_erfc,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001225 "erfc($module, x, /)\n--\n\n"
1226 "Complementary error function at x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001227FUNC1(exp, exp, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001228 "exp($module, x, /)\n--\n\n"
1229 "Return e raised to the power of x.")
Mark Dickinson664b5112009-12-16 20:23:42 +00001230FUNC1(expm1, m_expm1, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001231 "expm1($module, x, /)\n--\n\n"
1232 "Return exp(x)-1.\n\n"
Mark Dickinson664b5112009-12-16 20:23:42 +00001233 "This function avoids the loss of precision involved in the direct "
1234 "evaluation of exp(x)-1 for small x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001235FUNC1(fabs, fabs, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001236 "fabs($module, x, /)\n--\n\n"
1237 "Return the absolute value of the float x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +00001238
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001239/*[clinic input]
1240math.floor
1241
1242 x as number: object
1243 /
1244
1245Return the floor of x as an Integral.
1246
1247This is the largest integer <= x.
1248[clinic start generated code]*/
1249
1250static PyObject *
1251math_floor(PyObject *module, PyObject *number)
1252/*[clinic end generated code: output=c6a65c4884884b8a input=63af6b5d7ebcc3d6]*/
1253{
Benjamin Petersonce798522012-01-22 11:24:29 -05001254 _Py_IDENTIFIER(__floor__);
Guido van Rossum13e05de2007-08-23 22:56:55 +00001255
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001256 if (!PyFloat_CheckExact(number)) {
1257 PyObject *method = _PyObject_LookupSpecial(number, &PyId___floor__);
1258 if (method != NULL) {
1259 PyObject *result = _PyObject_CallNoArg(method);
1260 Py_DECREF(method);
1261 return result;
1262 }
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001263 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 return NULL;
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001265 }
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001266 double x = PyFloat_AsDouble(number);
1267 if (x == -1.0 && PyErr_Occurred())
1268 return NULL;
1269
1270 return PyLong_FromDouble(floor(x));
Guido van Rossum13e05de2007-08-23 22:56:55 +00001271}
1272
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001273FUNC1A(gamma, m_tgamma,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001274 "gamma($module, x, /)\n--\n\n"
1275 "Gamma function at x.")
Mark Dickinson05d2e082009-12-11 20:17:17 +00001276FUNC1A(lgamma, m_lgamma,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001277 "lgamma($module, x, /)\n--\n\n"
1278 "Natural logarithm of absolute value of Gamma function at x.")
Mark Dickinsonbe64d952010-07-07 16:21:29 +00001279FUNC1(log1p, m_log1p, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001280 "log1p($module, x, /)\n--\n\n"
1281 "Return the natural logarithm of 1+x (base e).\n\n"
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001282 "The result is computed in a way which is accurate for x near zero.")
Mark Dickinsona0ce3752017-04-05 18:34:27 +01001283FUNC2(remainder, m_remainder,
1284 "remainder($module, x, y, /)\n--\n\n"
1285 "Difference between x and the closest integer multiple of y.\n\n"
1286 "Return x - n*y where n*y is the closest integer multiple of y.\n"
1287 "In the case where x is exactly halfway between two multiples of\n"
1288 "y, the nearest even value of n is used. The result is always exact.")
Christian Heimes53876d92008-04-19 00:31:39 +00001289FUNC1(sin, sin, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001290 "sin($module, x, /)\n--\n\n"
1291 "Return the sine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001292FUNC1(sinh, sinh, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001293 "sinh($module, x, /)\n--\n\n"
1294 "Return the hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001295FUNC1(sqrt, sqrt, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001296 "sqrt($module, x, /)\n--\n\n"
1297 "Return the square root of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001298FUNC1(tan, tan, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001299 "tan($module, x, /)\n--\n\n"
1300 "Return the tangent of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001301FUNC1(tanh, tanh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001302 "tanh($module, x, /)\n--\n\n"
1303 "Return the hyperbolic tangent of x.")
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001304
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001305/* Precision summation function as msum() by Raymond Hettinger in
1306 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
1307 enhanced with the exact partials sum and roundoff from Mark
1308 Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
1309 See those links for more details, proofs and other references.
1310
1311 Note 1: IEEE 754R floating point semantics are assumed,
1312 but the current implementation does not re-establish special
1313 value semantics across iterations (i.e. handling -Inf + Inf).
1314
1315 Note 2: No provision is made for intermediate overflow handling;
Georg Brandlf78e02b2008-06-10 17:40:04 +00001316 therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001317 sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
1318 overflow of the first partial sum.
1319
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001320 Note 3: The intermediate values lo, yr, and hi are declared volatile so
1321 aggressive compilers won't algebraically reduce lo to always be exactly 0.0.
Georg Brandlf78e02b2008-06-10 17:40:04 +00001322 Also, the volatile declaration forces the values to be stored in memory as
1323 regular doubles instead of extended long precision (80-bit) values. This
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001324 prevents double rounding because any addition or subtraction of two doubles
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 can be resolved exactly into double-sized hi and lo values. As long as the
Georg Brandlf78e02b2008-06-10 17:40:04 +00001326 hi value gets forced into a double before yr and lo are computed, the extra
1327 bits in downstream extended precision operations (x87 for example) will be
1328 exactly zero and therefore can be losslessly stored back into a double,
1329 thereby preventing double rounding.
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001330
1331 Note 4: A similar implementation is in Modules/cmathmodule.c.
1332 Be sure to update both when making changes.
1333
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001334 Note 5: The signature of math.fsum() differs from builtins.sum()
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001335 because the start argument doesn't make sense in the context of
1336 accurate summation. Since the partials table is collapsed before
1337 returning a result, sum(seq2, start=sum(seq1)) may not equal the
1338 accurate result returned by sum(itertools.chain(seq1, seq2)).
1339*/
1340
1341#define NUM_PARTIALS 32 /* initial partials array size, on stack */
1342
1343/* Extend the partials array p[] by doubling its size. */
1344static int /* non-zero on error */
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001345_fsum_realloc(double **p_ptr, Py_ssize_t n,
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001346 double *ps, Py_ssize_t *m_ptr)
1347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 void *v = NULL;
1349 Py_ssize_t m = *m_ptr;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 m += m; /* double */
Victor Stinner049e5092014-08-17 22:20:00 +02001352 if (n < m && (size_t)m < ((size_t)PY_SSIZE_T_MAX / sizeof(double))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 double *p = *p_ptr;
1354 if (p == ps) {
1355 v = PyMem_Malloc(sizeof(double) * m);
1356 if (v != NULL)
1357 memcpy(v, ps, sizeof(double) * n);
1358 }
1359 else
1360 v = PyMem_Realloc(p, sizeof(double) * m);
1361 }
1362 if (v == NULL) { /* size overflow or no memory */
1363 PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
1364 return 1;
1365 }
1366 *p_ptr = (double*) v;
1367 *m_ptr = m;
1368 return 0;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001369}
1370
1371/* Full precision summation of a sequence of floats.
1372
1373 def msum(iterable):
1374 partials = [] # sorted, non-overlapping partial sums
1375 for x in iterable:
Mark Dickinsonfdb0acc2010-06-25 20:22:24 +00001376 i = 0
1377 for y in partials:
1378 if abs(x) < abs(y):
1379 x, y = y, x
1380 hi = x + y
1381 lo = y - (hi - x)
1382 if lo:
1383 partials[i] = lo
1384 i += 1
1385 x = hi
1386 partials[i:] = [x]
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001387 return sum_exact(partials)
1388
1389 Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
1390 are exactly equal to x+y. The inner loop applies hi/lo summation to each
1391 partial so that the list of partial sums remains exact.
1392
1393 Sum_exact() adds the partial sums exactly and correctly rounds the final
1394 result (using the round-half-to-even rule). The items in partials remain
1395 non-zero, non-special, non-overlapping and strictly increasing in
1396 magnitude, but possibly not all having the same sign.
1397
1398 Depends on IEEE 754 arithmetic guarantees and half-even rounding.
1399*/
1400
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001401/*[clinic input]
1402math.fsum
1403
1404 seq: object
1405 /
1406
1407Return an accurate floating point sum of values in the iterable seq.
1408
1409Assumes IEEE-754 floating point arithmetic.
1410[clinic start generated code]*/
1411
1412static PyObject *
1413math_fsum(PyObject *module, PyObject *seq)
1414/*[clinic end generated code: output=ba5c672b87fe34fc input=c51b7d8caf6f6e82]*/
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 PyObject *item, *iter, *sum = NULL;
1417 Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
1418 double x, y, t, ps[NUM_PARTIALS], *p = ps;
1419 double xsave, special_sum = 0.0, inf_sum = 0.0;
1420 volatile double hi, yr, lo;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 iter = PyObject_GetIter(seq);
1423 if (iter == NULL)
1424 return NULL;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 for(;;) { /* for x in iterable */
1427 assert(0 <= n && n <= m);
1428 assert((m == NUM_PARTIALS && p == ps) ||
1429 (m > NUM_PARTIALS && p != NULL));
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 item = PyIter_Next(iter);
1432 if (item == NULL) {
1433 if (PyErr_Occurred())
1434 goto _fsum_error;
1435 break;
1436 }
Raymond Hettingercfd735e2019-01-29 20:39:53 -08001437 ASSIGN_DOUBLE(x, item, error_with_item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 Py_DECREF(item);
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 xsave = x;
1441 for (i = j = 0; j < n; j++) { /* for y in partials */
1442 y = p[j];
1443 if (fabs(x) < fabs(y)) {
1444 t = x; x = y; y = t;
1445 }
1446 hi = x + y;
1447 yr = hi - x;
1448 lo = y - yr;
1449 if (lo != 0.0)
1450 p[i++] = lo;
1451 x = hi;
1452 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 n = i; /* ps[i:] = [x] */
1455 if (x != 0.0) {
1456 if (! Py_IS_FINITE(x)) {
1457 /* a nonfinite x could arise either as
1458 a result of intermediate overflow, or
1459 as a result of a nan or inf in the
1460 summands */
1461 if (Py_IS_FINITE(xsave)) {
1462 PyErr_SetString(PyExc_OverflowError,
1463 "intermediate overflow in fsum");
1464 goto _fsum_error;
1465 }
1466 if (Py_IS_INFINITY(xsave))
1467 inf_sum += xsave;
1468 special_sum += xsave;
1469 /* reset partials */
1470 n = 0;
1471 }
1472 else if (n >= m && _fsum_realloc(&p, n, ps, &m))
1473 goto _fsum_error;
1474 else
1475 p[n++] = x;
1476 }
1477 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 if (special_sum != 0.0) {
1480 if (Py_IS_NAN(inf_sum))
1481 PyErr_SetString(PyExc_ValueError,
1482 "-inf + inf in fsum");
1483 else
1484 sum = PyFloat_FromDouble(special_sum);
1485 goto _fsum_error;
1486 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 hi = 0.0;
1489 if (n > 0) {
1490 hi = p[--n];
1491 /* sum_exact(ps, hi) from the top, stop when the sum becomes
1492 inexact. */
1493 while (n > 0) {
1494 x = hi;
1495 y = p[--n];
1496 assert(fabs(y) < fabs(x));
1497 hi = x + y;
1498 yr = hi - x;
1499 lo = y - yr;
1500 if (lo != 0.0)
1501 break;
1502 }
1503 /* Make half-even rounding work across multiple partials.
1504 Needed so that sum([1e-16, 1, 1e16]) will round-up the last
1505 digit to two instead of down to zero (the 1e-16 makes the 1
1506 slightly closer to two). With a potential 1 ULP rounding
1507 error fixed-up, math.fsum() can guarantee commutativity. */
1508 if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
1509 (lo > 0.0 && p[n-1] > 0.0))) {
1510 y = lo * 2.0;
1511 x = hi + y;
1512 yr = x - hi;
1513 if (y == yr)
1514 hi = x;
1515 }
1516 }
1517 sum = PyFloat_FromDouble(hi);
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001518
Raymond Hettingercfd735e2019-01-29 20:39:53 -08001519 _fsum_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 Py_DECREF(iter);
1521 if (p != ps)
1522 PyMem_Free(p);
1523 return sum;
Raymond Hettingercfd735e2019-01-29 20:39:53 -08001524
1525 error_with_item:
1526 Py_DECREF(item);
1527 goto _fsum_error;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001528}
1529
1530#undef NUM_PARTIALS
1531
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001532
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001533static unsigned long
1534count_set_bits(unsigned long n)
1535{
1536 unsigned long count = 0;
1537 while (n != 0) {
1538 ++count;
1539 n &= n - 1; /* clear least significant bit */
1540 }
1541 return count;
1542}
1543
Mark Dickinson73934b92019-05-18 12:29:50 +01001544/* Integer square root
1545
1546Given a nonnegative integer `n`, we want to compute the largest integer
1547`a` for which `a * a <= n`, or equivalently the integer part of the exact
1548square root of `n`.
1549
1550We use an adaptive-precision pure-integer version of Newton's iteration. Given
1551a positive integer `n`, the algorithm produces at each iteration an integer
1552approximation `a` to the square root of `n >> s` for some even integer `s`,
1553with `s` decreasing as the iterations progress. On the final iteration, `s` is
1554zero and we have an approximation to the square root of `n` itself.
1555
1556At every step, the approximation `a` is strictly within 1.0 of the true square
1557root, so we have
1558
1559 (a - 1)**2 < (n >> s) < (a + 1)**2
1560
1561After the final iteration, a check-and-correct step is needed to determine
1562whether `a` or `a - 1` gives the desired integer square root of `n`.
1563
1564The algorithm is remarkable in its simplicity. There's no need for a
1565per-iteration check-and-correct step, and termination is straightforward: the
1566number of iterations is known in advance (it's exactly `floor(log2(log2(n)))`
1567for `n > 1`). The only tricky part of the correctness proof is in establishing
1568that the bound `(a - 1)**2 < (n >> s) < (a + 1)**2` is maintained from one
1569iteration to the next. A sketch of the proof of this is given below.
1570
1571In addition to the proof sketch, a formal, computer-verified proof
1572of correctness (using Lean) of an equivalent recursive algorithm can be found
1573here:
1574
1575 https://github.com/mdickinson/snippets/blob/master/proofs/isqrt/src/isqrt.lean
1576
1577
1578Here's Python code equivalent to the C implementation below:
1579
1580 def isqrt(n):
1581 """
1582 Return the integer part of the square root of the input.
1583 """
1584 n = operator.index(n)
1585
1586 if n < 0:
1587 raise ValueError("isqrt() argument must be nonnegative")
1588 if n == 0:
1589 return 0
1590
1591 c = (n.bit_length() - 1) // 2
1592 a = 1
1593 d = 0
1594 for s in reversed(range(c.bit_length())):
Mark Dickinson2dfeaa92019-06-16 17:53:21 +01001595 # Loop invariant: (a-1)**2 < (n >> 2*(c - d)) < (a+1)**2
Mark Dickinson73934b92019-05-18 12:29:50 +01001596 e = d
1597 d = c >> s
1598 a = (a << d - e - 1) + (n >> 2*c - e - d + 1) // a
Mark Dickinson73934b92019-05-18 12:29:50 +01001599
1600 return a - (a*a > n)
1601
1602
1603Sketch of proof of correctness
1604------------------------------
1605
1606The delicate part of the correctness proof is showing that the loop invariant
1607is preserved from one iteration to the next. That is, just before the line
1608
1609 a = (a << d - e - 1) + (n >> 2*c - e - d + 1) // a
1610
1611is executed in the above code, we know that
1612
1613 (1) (a - 1)**2 < (n >> 2*(c - e)) < (a + 1)**2.
1614
1615(since `e` is always the value of `d` from the previous iteration). We must
1616prove that after that line is executed, we have
1617
1618 (a - 1)**2 < (n >> 2*(c - d)) < (a + 1)**2
1619
Min ho Kimf7d72e42019-07-06 07:39:32 +10001620To facilitate the proof, we make some changes of notation. Write `m` for
Mark Dickinson73934b92019-05-18 12:29:50 +01001621`n >> 2*(c-d)`, and write `b` for the new value of `a`, so
1622
1623 b = (a << d - e - 1) + (n >> 2*c - e - d + 1) // a
1624
1625or equivalently:
1626
1627 (2) b = (a << d - e - 1) + (m >> d - e + 1) // a
1628
1629Then we can rewrite (1) as:
1630
1631 (3) (a - 1)**2 < (m >> 2*(d - e)) < (a + 1)**2
1632
1633and we must show that (b - 1)**2 < m < (b + 1)**2.
1634
1635From this point on, we switch to mathematical notation, so `/` means exact
1636division rather than integer division and `^` is used for exponentiation. We
1637use the `√` symbol for the exact square root. In (3), we can remove the
1638implicit floor operation to give:
1639
1640 (4) (a - 1)^2 < m / 4^(d - e) < (a + 1)^2
1641
1642Taking square roots throughout (4), scaling by `2^(d-e)`, and rearranging gives
1643
1644 (5) 0 <= | 2^(d-e)a - √m | < 2^(d-e)
1645
1646Squaring and dividing through by `2^(d-e+1) a` gives
1647
1648 (6) 0 <= 2^(d-e-1) a + m / (2^(d-e+1) a) - √m < 2^(d-e-1) / a
1649
1650We'll show below that `2^(d-e-1) <= a`. Given that, we can replace the
1651right-hand side of (6) with `1`, and now replacing the central
1652term `m / (2^(d-e+1) a)` with its floor in (6) gives
1653
1654 (7) -1 < 2^(d-e-1) a + m // 2^(d-e+1) a - √m < 1
1655
1656Or equivalently, from (2):
1657
1658 (7) -1 < b - √m < 1
1659
1660and rearranging gives that `(b-1)^2 < m < (b+1)^2`, which is what we needed
1661to prove.
1662
1663We're not quite done: we still have to prove the inequality `2^(d - e - 1) <=
1664a` that was used to get line (7) above. From the definition of `c`, we have
1665`4^c <= n`, which implies
1666
1667 (8) 4^d <= m
1668
1669also, since `e == d >> 1`, `d` is at most `2e + 1`, from which it follows
1670that `2d - 2e - 1 <= d` and hence that
1671
1672 (9) 4^(2d - 2e - 1) <= m
1673
1674Dividing both sides by `4^(d - e)` gives
1675
1676 (10) 4^(d - e - 1) <= m / 4^(d - e)
1677
1678But we know from (4) that `m / 4^(d-e) < (a + 1)^2`, hence
1679
1680 (11) 4^(d - e - 1) < (a + 1)^2
1681
1682Now taking square roots of both sides and observing that both `2^(d-e-1)` and
1683`a` are integers gives `2^(d - e - 1) <= a`, which is what we needed. This
1684completes the proof sketch.
1685
1686*/
1687
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001688
1689/* Approximate square root of a large 64-bit integer.
1690
1691 Given `n` satisfying `2**62 <= n < 2**64`, return `a`
1692 satisfying `(a - 1)**2 < n < (a + 1)**2`. */
1693
1694static uint64_t
1695_approximate_isqrt(uint64_t n)
1696{
1697 uint32_t u = 1U + (n >> 62);
1698 u = (u << 1) + (n >> 59) / u;
1699 u = (u << 3) + (n >> 53) / u;
1700 u = (u << 7) + (n >> 41) / u;
1701 return (u << 15) + (n >> 17) / u;
1702}
1703
Mark Dickinson73934b92019-05-18 12:29:50 +01001704/*[clinic input]
1705math.isqrt
1706
1707 n: object
1708 /
1709
1710Return the integer part of the square root of the input.
1711[clinic start generated code]*/
1712
1713static PyObject *
1714math_isqrt(PyObject *module, PyObject *n)
1715/*[clinic end generated code: output=35a6f7f980beab26 input=5b6e7ae4fa6c43d6]*/
1716{
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001717 int a_too_large, c_bit_length;
Mark Dickinson73934b92019-05-18 12:29:50 +01001718 size_t c, d;
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001719 uint64_t m, u;
Mark Dickinson73934b92019-05-18 12:29:50 +01001720 PyObject *a = NULL, *b;
1721
1722 n = PyNumber_Index(n);
1723 if (n == NULL) {
1724 return NULL;
1725 }
1726
1727 if (_PyLong_Sign(n) < 0) {
1728 PyErr_SetString(
1729 PyExc_ValueError,
1730 "isqrt() argument must be nonnegative");
1731 goto error;
1732 }
1733 if (_PyLong_Sign(n) == 0) {
1734 Py_DECREF(n);
1735 return PyLong_FromLong(0);
1736 }
1737
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001738 /* c = (n.bit_length() - 1) // 2 */
Mark Dickinson73934b92019-05-18 12:29:50 +01001739 c = _PyLong_NumBits(n);
1740 if (c == (size_t)(-1)) {
1741 goto error;
1742 }
1743 c = (c - 1U) / 2U;
1744
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001745 /* Fast path: if c <= 31 then n < 2**64 and we can compute directly with a
1746 fast, almost branch-free algorithm. In the final correction, we use `u*u
1747 - 1 >= m` instead of the simpler `u*u > m` in order to get the correct
1748 result in the corner case where `u=2**32`. */
1749 if (c <= 31U) {
1750 m = (uint64_t)PyLong_AsUnsignedLongLong(n);
1751 Py_DECREF(n);
1752 if (m == (uint64_t)(-1) && PyErr_Occurred()) {
1753 return NULL;
1754 }
1755 u = _approximate_isqrt(m << (62U - 2U*c)) >> (31U - c);
1756 u -= u * u - 1U >= m;
1757 return PyLong_FromUnsignedLongLong((unsigned long long)u);
Mark Dickinson73934b92019-05-18 12:29:50 +01001758 }
1759
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001760 /* Slow path: n >= 2**64. We perform the first five iterations in C integer
1761 arithmetic, then switch to using Python long integers. */
1762
1763 /* From n >= 2**64 it follows that c.bit_length() >= 6. */
1764 c_bit_length = 6;
1765 while ((c >> c_bit_length) > 0U) {
1766 ++c_bit_length;
1767 }
1768
1769 /* Initialise d and a. */
1770 d = c >> (c_bit_length - 5);
1771 b = _PyLong_Rshift(n, 2U*c - 62U);
1772 if (b == NULL) {
1773 goto error;
1774 }
1775 m = (uint64_t)PyLong_AsUnsignedLongLong(b);
1776 Py_DECREF(b);
1777 if (m == (uint64_t)(-1) && PyErr_Occurred()) {
1778 goto error;
1779 }
1780 u = _approximate_isqrt(m) >> (31U - d);
1781 a = PyLong_FromUnsignedLongLong((unsigned long long)u);
Mark Dickinson73934b92019-05-18 12:29:50 +01001782 if (a == NULL) {
1783 goto error;
1784 }
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001785
1786 for (int s = c_bit_length - 6; s >= 0; --s) {
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03001787 PyObject *q;
Mark Dickinson73934b92019-05-18 12:29:50 +01001788 size_t e = d;
1789
1790 d = c >> s;
1791
1792 /* q = (n >> 2*c - e - d + 1) // a */
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03001793 q = _PyLong_Rshift(n, 2U*c - d - e + 1U);
Mark Dickinson73934b92019-05-18 12:29:50 +01001794 if (q == NULL) {
1795 goto error;
1796 }
1797 Py_SETREF(q, PyNumber_FloorDivide(q, a));
1798 if (q == NULL) {
1799 goto error;
1800 }
1801
1802 /* a = (a << d - 1 - e) + q */
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03001803 Py_SETREF(a, _PyLong_Lshift(a, d - 1U - e));
Mark Dickinson73934b92019-05-18 12:29:50 +01001804 if (a == NULL) {
1805 Py_DECREF(q);
1806 goto error;
1807 }
1808 Py_SETREF(a, PyNumber_Add(a, q));
1809 Py_DECREF(q);
1810 if (a == NULL) {
1811 goto error;
1812 }
1813 }
1814
1815 /* The correct result is either a or a - 1. Figure out which, and
1816 decrement a if necessary. */
1817
1818 /* a_too_large = n < a * a */
1819 b = PyNumber_Multiply(a, a);
1820 if (b == NULL) {
1821 goto error;
1822 }
1823 a_too_large = PyObject_RichCompareBool(n, b, Py_LT);
1824 Py_DECREF(b);
1825 if (a_too_large == -1) {
1826 goto error;
1827 }
1828
1829 if (a_too_large) {
1830 Py_SETREF(a, PyNumber_Subtract(a, _PyLong_One));
1831 }
1832 Py_DECREF(n);
1833 return a;
1834
1835 error:
1836 Py_XDECREF(a);
1837 Py_DECREF(n);
1838 return NULL;
1839}
1840
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001841/* Divide-and-conquer factorial algorithm
1842 *
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07001843 * Based on the formula and pseudo-code provided at:
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001844 * http://www.luschny.de/math/factorial/binarysplitfact.html
1845 *
1846 * Faster algorithms exist, but they're more complicated and depend on
Ezio Melotti9527afd2010-07-08 15:03:02 +00001847 * a fast prime factorization algorithm.
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001848 *
1849 * Notes on the algorithm
1850 * ----------------------
1851 *
1852 * factorial(n) is written in the form 2**k * m, with m odd. k and m are
1853 * computed separately, and then combined using a left shift.
1854 *
1855 * The function factorial_odd_part computes the odd part m (i.e., the greatest
1856 * odd divisor) of factorial(n), using the formula:
1857 *
1858 * factorial_odd_part(n) =
1859 *
1860 * product_{i >= 0} product_{0 < j <= n / 2**i, j odd} j
1861 *
1862 * Example: factorial_odd_part(20) =
1863 *
1864 * (1) *
1865 * (1) *
1866 * (1 * 3 * 5) *
1867 * (1 * 3 * 5 * 7 * 9)
1868 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1869 *
1870 * Here i goes from large to small: the first term corresponds to i=4 (any
1871 * larger i gives an empty product), and the last term corresponds to i=0.
1872 * Each term can be computed from the last by multiplying by the extra odd
1873 * numbers required: e.g., to get from the penultimate term to the last one,
1874 * we multiply by (11 * 13 * 15 * 17 * 19).
1875 *
1876 * To see a hint of why this formula works, here are the same numbers as above
1877 * but with the even parts (i.e., the appropriate powers of 2) included. For
1878 * each subterm in the product for i, we multiply that subterm by 2**i:
1879 *
1880 * factorial(20) =
1881 *
1882 * (16) *
1883 * (8) *
1884 * (4 * 12 * 20) *
1885 * (2 * 6 * 10 * 14 * 18) *
1886 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1887 *
1888 * The factorial_partial_product function computes the product of all odd j in
1889 * range(start, stop) for given start and stop. It's used to compute the
1890 * partial products like (11 * 13 * 15 * 17 * 19) in the example above. It
1891 * operates recursively, repeatedly splitting the range into two roughly equal
1892 * pieces until the subranges are small enough to be computed using only C
1893 * integer arithmetic.
1894 *
1895 * The two-valuation k (i.e., the exponent of the largest power of 2 dividing
1896 * the factorial) is computed independently in the main math_factorial
1897 * function. By standard results, its value is:
1898 *
1899 * two_valuation = n//2 + n//4 + n//8 + ....
1900 *
1901 * It can be shown (e.g., by complete induction on n) that two_valuation is
1902 * equal to n - count_set_bits(n), where count_set_bits(n) gives the number of
1903 * '1'-bits in the binary expansion of n.
1904 */
1905
1906/* factorial_partial_product: Compute product(range(start, stop, 2)) using
1907 * divide and conquer. Assumes start and stop are odd and stop > start.
1908 * max_bits must be >= bit_length(stop - 2). */
1909
1910static PyObject *
1911factorial_partial_product(unsigned long start, unsigned long stop,
1912 unsigned long max_bits)
1913{
1914 unsigned long midpoint, num_operands;
1915 PyObject *left = NULL, *right = NULL, *result = NULL;
1916
1917 /* If the return value will fit an unsigned long, then we can
1918 * multiply in a tight, fast loop where each multiply is O(1).
1919 * Compute an upper bound on the number of bits required to store
1920 * the answer.
1921 *
1922 * Storing some integer z requires floor(lg(z))+1 bits, which is
1923 * conveniently the value returned by bit_length(z). The
1924 * product x*y will require at most
1925 * bit_length(x) + bit_length(y) bits to store, based
1926 * on the idea that lg product = lg x + lg y.
1927 *
1928 * We know that stop - 2 is the largest number to be multiplied. From
1929 * there, we have: bit_length(answer) <= num_operands *
1930 * bit_length(stop - 2)
1931 */
1932
1933 num_operands = (stop - start) / 2;
1934 /* The "num_operands <= 8 * SIZEOF_LONG" check guards against the
1935 * unlikely case of an overflow in num_operands * max_bits. */
1936 if (num_operands <= 8 * SIZEOF_LONG &&
1937 num_operands * max_bits <= 8 * SIZEOF_LONG) {
1938 unsigned long j, total;
1939 for (total = start, j = start + 2; j < stop; j += 2)
1940 total *= j;
1941 return PyLong_FromUnsignedLong(total);
1942 }
1943
1944 /* find midpoint of range(start, stop), rounded up to next odd number. */
1945 midpoint = (start + num_operands) | 1;
1946 left = factorial_partial_product(start, midpoint,
Niklas Fiekasc5b79002020-01-16 15:09:19 +01001947 _Py_bit_length(midpoint - 2));
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001948 if (left == NULL)
1949 goto error;
1950 right = factorial_partial_product(midpoint, stop, max_bits);
1951 if (right == NULL)
1952 goto error;
1953 result = PyNumber_Multiply(left, right);
1954
1955 error:
1956 Py_XDECREF(left);
1957 Py_XDECREF(right);
1958 return result;
1959}
1960
1961/* factorial_odd_part: compute the odd part of factorial(n). */
1962
1963static PyObject *
1964factorial_odd_part(unsigned long n)
1965{
1966 long i;
1967 unsigned long v, lower, upper;
1968 PyObject *partial, *tmp, *inner, *outer;
1969
1970 inner = PyLong_FromLong(1);
1971 if (inner == NULL)
1972 return NULL;
1973 outer = inner;
1974 Py_INCREF(outer);
1975
1976 upper = 3;
Niklas Fiekasc5b79002020-01-16 15:09:19 +01001977 for (i = _Py_bit_length(n) - 2; i >= 0; i--) {
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001978 v = n >> i;
1979 if (v <= 2)
1980 continue;
1981 lower = upper;
1982 /* (v + 1) | 1 = least odd integer strictly larger than n / 2**i */
1983 upper = (v + 1) | 1;
1984 /* Here inner is the product of all odd integers j in the range (0,
1985 n/2**(i+1)]. The factorial_partial_product call below gives the
1986 product of all odd integers j in the range (n/2**(i+1), n/2**i]. */
Niklas Fiekasc5b79002020-01-16 15:09:19 +01001987 partial = factorial_partial_product(lower, upper, _Py_bit_length(upper-2));
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001988 /* inner *= partial */
1989 if (partial == NULL)
1990 goto error;
1991 tmp = PyNumber_Multiply(inner, partial);
1992 Py_DECREF(partial);
1993 if (tmp == NULL)
1994 goto error;
1995 Py_DECREF(inner);
1996 inner = tmp;
1997 /* Now inner is the product of all odd integers j in the range (0,
1998 n/2**i], giving the inner product in the formula above. */
1999
2000 /* outer *= inner; */
2001 tmp = PyNumber_Multiply(outer, inner);
2002 if (tmp == NULL)
2003 goto error;
2004 Py_DECREF(outer);
2005 outer = tmp;
2006 }
Mark Dickinson76464492012-10-25 10:46:28 +01002007 Py_DECREF(inner);
2008 return outer;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002009
2010 error:
2011 Py_DECREF(outer);
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002012 Py_DECREF(inner);
Mark Dickinson76464492012-10-25 10:46:28 +01002013 return NULL;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002014}
2015
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002016
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002017/* Lookup table for small factorial values */
2018
2019static const unsigned long SmallFactorials[] = {
2020 1, 1, 2, 6, 24, 120, 720, 5040, 40320,
2021 362880, 3628800, 39916800, 479001600,
2022#if SIZEOF_LONG >= 8
2023 6227020800, 87178291200, 1307674368000,
2024 20922789888000, 355687428096000, 6402373705728000,
2025 121645100408832000, 2432902008176640000
2026#endif
2027};
2028
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002029/*[clinic input]
2030math.factorial
2031
2032 x as arg: object
2033 /
2034
2035Find x!.
2036
2037Raise a ValueError if x is negative or non-integral.
2038[clinic start generated code]*/
2039
Barry Warsaw8b43b191996-12-09 22:32:36 +00002040static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002041math_factorial(PyObject *module, PyObject *arg)
2042/*[clinic end generated code: output=6686f26fae00e9ca input=6d1c8105c0d91fb4]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002043{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03002044 long x, two_valuation;
Mark Dickinson5990d282014-04-10 09:29:39 -04002045 int overflow;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03002046 PyObject *result, *odd_part, *pyint_form;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 if (PyFloat_Check(arg)) {
Serhiy Storchaka231aad32019-06-17 16:57:27 +03002049 if (PyErr_WarnEx(PyExc_DeprecationWarning,
2050 "Using factorial() with floats is deprecated",
2051 1) < 0)
2052 {
2053 return NULL;
2054 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 PyObject *lx;
2056 double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
2057 if (!(Py_IS_FINITE(dx) && dx == floor(dx))) {
2058 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002059 "factorial() only accepts integral values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 return NULL;
2061 }
2062 lx = PyLong_FromDouble(dx);
2063 if (lx == NULL)
2064 return NULL;
Mark Dickinson5990d282014-04-10 09:29:39 -04002065 x = PyLong_AsLongAndOverflow(lx, &overflow);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 Py_DECREF(lx);
2067 }
Pablo Galindoe9ba3702018-09-03 22:20:06 +01002068 else {
2069 pyint_form = PyNumber_Index(arg);
2070 if (pyint_form == NULL) {
2071 return NULL;
2072 }
2073 x = PyLong_AsLongAndOverflow(pyint_form, &overflow);
2074 Py_DECREF(pyint_form);
2075 }
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002076
Mark Dickinson5990d282014-04-10 09:29:39 -04002077 if (x == -1 && PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 return NULL;
Mark Dickinson5990d282014-04-10 09:29:39 -04002079 }
2080 else if (overflow == 1) {
2081 PyErr_Format(PyExc_OverflowError,
2082 "factorial() argument should not exceed %ld",
2083 LONG_MAX);
2084 return NULL;
2085 }
2086 else if (overflow == -1 || x < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002088 "factorial() not defined for negative values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 return NULL;
2090 }
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002091
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002092 /* use lookup table if x is small */
Victor Stinner63941882011-09-29 00:42:28 +02002093 if (x < (long)Py_ARRAY_LENGTH(SmallFactorials))
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002094 return PyLong_FromUnsignedLong(SmallFactorials[x]);
2095
2096 /* else express in the form odd_part * 2**two_valuation, and compute as
2097 odd_part << two_valuation. */
2098 odd_part = factorial_odd_part(x);
2099 if (odd_part == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03002101 two_valuation = x - count_set_bits(x);
2102 result = _PyLong_Lshift(odd_part, two_valuation);
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002103 Py_DECREF(odd_part);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 return result;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002105}
2106
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002107
2108/*[clinic input]
2109math.trunc
2110
2111 x: object
2112 /
2113
2114Truncates the Real x to the nearest Integral toward 0.
2115
2116Uses the __trunc__ magic method.
2117[clinic start generated code]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002118
2119static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002120math_trunc(PyObject *module, PyObject *x)
2121/*[clinic end generated code: output=34b9697b707e1031 input=2168b34e0a09134d]*/
Christian Heimes400adb02008-02-01 08:12:03 +00002122{
Benjamin Petersonce798522012-01-22 11:24:29 -05002123 _Py_IDENTIFIER(__trunc__);
Benjamin Petersonb0125892010-07-02 13:35:17 +00002124 PyObject *trunc, *result;
Christian Heimes400adb02008-02-01 08:12:03 +00002125
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02002126 if (PyFloat_CheckExact(x)) {
2127 return PyFloat_Type.tp_as_number->nb_int(x);
2128 }
2129
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002130 if (Py_TYPE(x)->tp_dict == NULL) {
2131 if (PyType_Ready(Py_TYPE(x)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 return NULL;
2133 }
Christian Heimes400adb02008-02-01 08:12:03 +00002134
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002135 trunc = _PyObject_LookupSpecial(x, &PyId___trunc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 if (trunc == NULL) {
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00002137 if (!PyErr_Occurred())
2138 PyErr_Format(PyExc_TypeError,
2139 "type %.100s doesn't define __trunc__ method",
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002140 Py_TYPE(x)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 return NULL;
2142 }
Victor Stinnerf17c3de2016-12-06 18:46:19 +01002143 result = _PyObject_CallNoArg(trunc);
Benjamin Petersonb0125892010-07-02 13:35:17 +00002144 Py_DECREF(trunc);
2145 return result;
Christian Heimes400adb02008-02-01 08:12:03 +00002146}
2147
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002148
2149/*[clinic input]
2150math.frexp
2151
2152 x: double
2153 /
2154
2155Return the mantissa and exponent of x, as pair (m, e).
2156
2157m is a float and e is an int, such that x = m * 2.**e.
2158If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.
2159[clinic start generated code]*/
Christian Heimes400adb02008-02-01 08:12:03 +00002160
2161static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002162math_frexp_impl(PyObject *module, double x)
2163/*[clinic end generated code: output=03e30d252a15ad4a input=96251c9e208bc6e9]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00002164{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 /* deal with special cases directly, to sidestep platform
2167 differences */
2168 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
2169 i = 0;
2170 }
2171 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 x = frexp(x, &i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 }
2174 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +00002175}
2176
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002177
2178/*[clinic input]
2179math.ldexp
2180
2181 x: double
2182 i: object
2183 /
2184
2185Return x * (2**i).
2186
2187This is essentially the inverse of frexp().
2188[clinic start generated code]*/
Guido van Rossumc6e22901998-12-04 19:26:43 +00002189
Barry Warsaw8b43b191996-12-09 22:32:36 +00002190static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002191math_ldexp_impl(PyObject *module, double x, PyObject *i)
2192/*[clinic end generated code: output=b6892f3c2df9cc6a input=17d5970c1a40a8c1]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00002193{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002194 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 long exp;
2196 int overflow;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00002197
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002198 if (PyLong_Check(i)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 /* on overflow, replace exponent with either LONG_MAX
2200 or LONG_MIN, depending on the sign. */
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002201 exp = PyLong_AsLongAndOverflow(i, &overflow);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 if (exp == -1 && PyErr_Occurred())
2203 return NULL;
2204 if (overflow)
2205 exp = overflow < 0 ? LONG_MIN : LONG_MAX;
2206 }
2207 else {
2208 PyErr_SetString(PyExc_TypeError,
Serhiy Storchaka95949422013-08-27 19:40:23 +03002209 "Expected an int as second argument to ldexp.");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 return NULL;
2211 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00002212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 if (x == 0. || !Py_IS_FINITE(x)) {
2214 /* NaNs, zeros and infinities are returned unchanged */
2215 r = x;
2216 errno = 0;
2217 } else if (exp > INT_MAX) {
2218 /* overflow */
2219 r = copysign(Py_HUGE_VAL, x);
2220 errno = ERANGE;
2221 } else if (exp < INT_MIN) {
2222 /* underflow to +-0 */
2223 r = copysign(0., x);
2224 errno = 0;
2225 } else {
2226 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 r = ldexp(x, (int)exp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 if (Py_IS_INFINITY(r))
2229 errno = ERANGE;
2230 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00002231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 if (errno && is_error(r))
2233 return NULL;
2234 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +00002235}
2236
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002237
2238/*[clinic input]
2239math.modf
2240
2241 x: double
2242 /
2243
2244Return the fractional and integer parts of x.
2245
2246Both results carry the sign of x and are floats.
2247[clinic start generated code]*/
Guido van Rossumc6e22901998-12-04 19:26:43 +00002248
Barry Warsaw8b43b191996-12-09 22:32:36 +00002249static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002250math_modf_impl(PyObject *module, double x)
2251/*[clinic end generated code: output=90cee0260014c3c0 input=b4cfb6786afd9035]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00002252{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002253 double y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 /* some platforms don't do the right thing for NaNs and
2255 infinities, so we take care of special cases directly. */
2256 if (!Py_IS_FINITE(x)) {
2257 if (Py_IS_INFINITY(x))
2258 return Py_BuildValue("(dd)", copysign(0., x), x);
2259 else if (Py_IS_NAN(x))
2260 return Py_BuildValue("(dd)", x, x);
2261 }
Christian Heimesa342c012008-04-20 21:01:16 +00002262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 x = modf(x, &y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +00002266}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002267
Guido van Rossumc6e22901998-12-04 19:26:43 +00002268
Serhiy Storchaka95949422013-08-27 19:40:23 +03002269/* A decent logarithm is easy to compute even for huge ints, but libm can't
Tim Peters78526162001-09-05 00:53:45 +00002270 do that by itself -- loghelper can. func is log or log10, and name is
Serhiy Storchaka95949422013-08-27 19:40:23 +03002271 "log" or "log10". Note that overflow of the result isn't possible: an int
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002272 can contain no more than INT_MAX * SHIFT bits, so has value certainly less
2273 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 +00002274 small enough to fit in an IEEE single. log and log10 are even smaller.
Serhiy Storchaka95949422013-08-27 19:40:23 +03002275 However, intermediate overflow is possible for an int if the number of bits
2276 in that int is larger than PY_SSIZE_T_MAX. */
Tim Peters78526162001-09-05 00:53:45 +00002277
2278static PyObject*
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002279loghelper(PyObject* arg, double (*func)(double), const char *funcname)
Tim Peters78526162001-09-05 00:53:45 +00002280{
Serhiy Storchaka95949422013-08-27 19:40:23 +03002281 /* If it is int, do it ourselves. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 if (PyLong_Check(arg)) {
Mark Dickinsonc6037172010-09-29 19:06:36 +00002283 double x, result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 Py_ssize_t e;
Mark Dickinsonc6037172010-09-29 19:06:36 +00002285
2286 /* Negative or zero inputs give a ValueError. */
2287 if (Py_SIZE(arg) <= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 PyErr_SetString(PyExc_ValueError,
2289 "math domain error");
2290 return NULL;
2291 }
Mark Dickinsonfa41e602010-09-28 07:22:27 +00002292
Mark Dickinsonc6037172010-09-29 19:06:36 +00002293 x = PyLong_AsDouble(arg);
2294 if (x == -1.0 && PyErr_Occurred()) {
2295 if (!PyErr_ExceptionMatches(PyExc_OverflowError))
2296 return NULL;
2297 /* Here the conversion to double overflowed, but it's possible
2298 to compute the log anyway. Clear the exception and continue. */
2299 PyErr_Clear();
2300 x = _PyLong_Frexp((PyLongObject *)arg, &e);
2301 if (x == -1.0 && PyErr_Occurred())
2302 return NULL;
2303 /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */
2304 result = func(x) + func(2.0) * e;
2305 }
2306 else
2307 /* Successfully converted x to a double. */
2308 result = func(x);
2309 return PyFloat_FromDouble(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 }
Tim Peters78526162001-09-05 00:53:45 +00002311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 /* Else let libm handle it by itself. */
2313 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +00002314}
2315
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002316
2317/*[clinic input]
2318math.log
2319
2320 x: object
2321 [
2322 base: object(c_default="NULL") = math.e
2323 ]
2324 /
2325
2326Return the logarithm of x to the given base.
2327
2328If the base not specified, returns the natural logarithm (base e) of x.
2329[clinic start generated code]*/
2330
Tim Peters78526162001-09-05 00:53:45 +00002331static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002332math_log_impl(PyObject *module, PyObject *x, int group_right_1,
2333 PyObject *base)
2334/*[clinic end generated code: output=7b5a39e526b73fc9 input=0f62d5726cbfebbd]*/
Tim Peters78526162001-09-05 00:53:45 +00002335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 PyObject *num, *den;
2337 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +00002338
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002339 num = loghelper(x, m_log, "log");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 if (num == NULL || base == NULL)
2341 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +00002342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002343 den = loghelper(base, m_log, "log");
2344 if (den == NULL) {
2345 Py_DECREF(num);
2346 return NULL;
2347 }
Raymond Hettinger866964c2002-12-14 19:51:34 +00002348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 ans = PyNumber_TrueDivide(num, den);
2350 Py_DECREF(num);
2351 Py_DECREF(den);
2352 return ans;
Tim Peters78526162001-09-05 00:53:45 +00002353}
2354
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002355
2356/*[clinic input]
2357math.log2
2358
2359 x: object
2360 /
2361
2362Return the base 2 logarithm of x.
2363[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002364
2365static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002366math_log2(PyObject *module, PyObject *x)
2367/*[clinic end generated code: output=5425899a4d5d6acb input=08321262bae4f39b]*/
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02002368{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002369 return loghelper(x, m_log2, "log2");
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02002370}
2371
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002372
2373/*[clinic input]
2374math.log10
2375
2376 x: object
2377 /
2378
2379Return the base 10 logarithm of x.
2380[clinic start generated code]*/
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02002381
2382static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002383math_log10(PyObject *module, PyObject *x)
2384/*[clinic end generated code: output=be72a64617df9c6f input=b2469d02c6469e53]*/
Tim Peters78526162001-09-05 00:53:45 +00002385{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002386 return loghelper(x, m_log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +00002387}
2388
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002389
2390/*[clinic input]
2391math.fmod
2392
2393 x: double
2394 y: double
2395 /
2396
2397Return fmod(x, y), according to platform C.
2398
2399x % y may differ.
2400[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002401
Christian Heimes53876d92008-04-19 00:31:39 +00002402static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002403math_fmod_impl(PyObject *module, double x, double y)
2404/*[clinic end generated code: output=7559d794343a27b5 input=4f84caa8cfc26a03]*/
Christian Heimes53876d92008-04-19 00:31:39 +00002405{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002406 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 /* fmod(x, +/-Inf) returns x for finite x. */
2408 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
2409 return PyFloat_FromDouble(x);
2410 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 r = fmod(x, y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 if (Py_IS_NAN(r)) {
2413 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
2414 errno = EDOM;
2415 else
2416 errno = 0;
2417 }
2418 if (errno && is_error(r))
2419 return NULL;
2420 else
2421 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00002422}
2423
Raymond Hettinger13990742018-08-11 11:26:36 -07002424/*
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002425Given an *n* length *vec* of values and a value *max*, compute:
Raymond Hettinger13990742018-08-11 11:26:36 -07002426
Raymond Hettingerc630e102018-08-11 18:39:05 -07002427 max * sqrt(sum((x / max) ** 2 for x in vec))
Raymond Hettinger13990742018-08-11 11:26:36 -07002428
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002429The value of the *max* variable must be non-negative and
Raymond Hettinger216aaaa2018-11-09 01:06:02 -08002430equal to the absolute value of the largest magnitude
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002431entry in the vector. If n==0, then *max* should be 0.0.
2432If an infinity is present in the vec, *max* should be INF.
Raymond Hettingerc630e102018-08-11 18:39:05 -07002433
2434The *found_nan* variable indicates whether some member of
2435the *vec* is a NaN.
Raymond Hettinger21786f52018-08-28 22:47:24 -07002436
2437To improve accuracy and to increase the number of cases where
2438vector_norm() is commutative, we use a variant of Neumaier
2439summation specialized to exploit that we always know that
2440|csum| >= |x|.
2441
2442The *csum* variable tracks the cumulative sum and *frac* tracks
2443the cumulative fractional errors at each step. Since this
2444variant assumes that |csum| >= |x| at each step, we establish
2445the precondition by starting the accumulation from 1.0 which
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002446represents the largest possible value of (x/max)**2.
2447
2448After the loop is finished, the initial 1.0 is subtracted out
2449for a net zero effect on the final sum. Since *csum* will be
2450greater than 1.0, the subtraction of 1.0 will not cause
2451fractional digits to be dropped from *csum*.
Raymond Hettinger21786f52018-08-28 22:47:24 -07002452
Raymond Hettinger13990742018-08-11 11:26:36 -07002453*/
2454
2455static inline double
Raymond Hettingerc630e102018-08-11 18:39:05 -07002456vector_norm(Py_ssize_t n, double *vec, double max, int found_nan)
Raymond Hettinger13990742018-08-11 11:26:36 -07002457{
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002458 double x, csum = 1.0, oldcsum, frac = 0.0;
Raymond Hettinger13990742018-08-11 11:26:36 -07002459 Py_ssize_t i;
2460
Raymond Hettingerc630e102018-08-11 18:39:05 -07002461 if (Py_IS_INFINITY(max)) {
2462 return max;
2463 }
2464 if (found_nan) {
2465 return Py_NAN;
2466 }
Raymond Hettingerf3267142018-09-02 13:34:21 -07002467 if (max == 0.0 || n <= 1) {
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002468 return max;
Raymond Hettinger13990742018-08-11 11:26:36 -07002469 }
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002470 for (i=0 ; i < n ; i++) {
Raymond Hettinger13990742018-08-11 11:26:36 -07002471 x = vec[i];
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002472 assert(Py_IS_FINITE(x) && fabs(x) <= max);
Raymond Hettinger13990742018-08-11 11:26:36 -07002473 x /= max;
Raymond Hettinger21786f52018-08-28 22:47:24 -07002474 x = x*x;
Raymond Hettinger13990742018-08-11 11:26:36 -07002475 oldcsum = csum;
2476 csum += x;
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002477 assert(csum >= x);
Raymond Hettinger21786f52018-08-28 22:47:24 -07002478 frac += (oldcsum - csum) + x;
Raymond Hettinger13990742018-08-11 11:26:36 -07002479 }
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002480 return max * sqrt(csum - 1.0 + frac);
Raymond Hettinger13990742018-08-11 11:26:36 -07002481}
2482
Raymond Hettingerc630e102018-08-11 18:39:05 -07002483#define NUM_STACK_ELEMS 16
2484
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002485/*[clinic input]
2486math.dist
2487
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002488 p: object
2489 q: object
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002490 /
2491
2492Return the Euclidean distance between two points p and q.
2493
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002494The points should be specified as sequences (or iterables) of
2495coordinates. Both inputs must have the same dimension.
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002496
2497Roughly equivalent to:
2498 sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
2499[clinic start generated code]*/
2500
2501static PyObject *
2502math_dist_impl(PyObject *module, PyObject *p, PyObject *q)
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002503/*[clinic end generated code: output=56bd9538d06bbcfe input=74e85e1b6092e68e]*/
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002504{
2505 PyObject *item;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002506 double max = 0.0;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002507 double x, px, qx, result;
2508 Py_ssize_t i, m, n;
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002509 int found_nan = 0, p_allocated = 0, q_allocated = 0;
Raymond Hettingerc630e102018-08-11 18:39:05 -07002510 double diffs_on_stack[NUM_STACK_ELEMS];
2511 double *diffs = diffs_on_stack;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002512
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002513 if (!PyTuple_Check(p)) {
2514 p = PySequence_Tuple(p);
2515 if (p == NULL) {
2516 return NULL;
2517 }
2518 p_allocated = 1;
2519 }
2520 if (!PyTuple_Check(q)) {
2521 q = PySequence_Tuple(q);
2522 if (q == NULL) {
2523 if (p_allocated) {
2524 Py_DECREF(p);
2525 }
2526 return NULL;
2527 }
2528 q_allocated = 1;
2529 }
2530
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002531 m = PyTuple_GET_SIZE(p);
2532 n = PyTuple_GET_SIZE(q);
2533 if (m != n) {
2534 PyErr_SetString(PyExc_ValueError,
2535 "both points must have the same number of dimensions");
2536 return NULL;
2537
2538 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002539 if (n > NUM_STACK_ELEMS) {
2540 diffs = (double *) PyObject_Malloc(n * sizeof(double));
2541 if (diffs == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07002542 return PyErr_NoMemory();
Raymond Hettingerc630e102018-08-11 18:39:05 -07002543 }
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002544 }
2545 for (i=0 ; i<n ; i++) {
2546 item = PyTuple_GET_ITEM(p, i);
Raymond Hettingercfd735e2019-01-29 20:39:53 -08002547 ASSIGN_DOUBLE(px, item, error_exit);
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002548 item = PyTuple_GET_ITEM(q, i);
Raymond Hettingercfd735e2019-01-29 20:39:53 -08002549 ASSIGN_DOUBLE(qx, item, error_exit);
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002550 x = fabs(px - qx);
2551 diffs[i] = x;
2552 found_nan |= Py_IS_NAN(x);
2553 if (x > max) {
2554 max = x;
2555 }
2556 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002557 result = vector_norm(n, diffs, max, found_nan);
2558 if (diffs != diffs_on_stack) {
2559 PyObject_Free(diffs);
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002560 }
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002561 if (p_allocated) {
2562 Py_DECREF(p);
2563 }
2564 if (q_allocated) {
2565 Py_DECREF(q);
2566 }
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002567 return PyFloat_FromDouble(result);
Raymond Hettingerc630e102018-08-11 18:39:05 -07002568
2569 error_exit:
2570 if (diffs != diffs_on_stack) {
2571 PyObject_Free(diffs);
2572 }
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002573 if (p_allocated) {
2574 Py_DECREF(p);
2575 }
2576 if (q_allocated) {
2577 Py_DECREF(q);
2578 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002579 return NULL;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002580}
2581
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002582/* AC: cannot convert yet, waiting for *args support */
Christian Heimes53876d92008-04-19 00:31:39 +00002583static PyObject *
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002584math_hypot(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Christian Heimes53876d92008-04-19 00:31:39 +00002585{
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002586 Py_ssize_t i;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002587 PyObject *item;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002588 double max = 0.0;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002589 double x, result;
2590 int found_nan = 0;
Raymond Hettingerc630e102018-08-11 18:39:05 -07002591 double coord_on_stack[NUM_STACK_ELEMS];
2592 double *coordinates = coord_on_stack;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002593
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002594 if (nargs > NUM_STACK_ELEMS) {
2595 coordinates = (double *) PyObject_Malloc(nargs * sizeof(double));
Zackery Spytz4c49da02018-12-07 03:11:30 -07002596 if (coordinates == NULL) {
2597 return PyErr_NoMemory();
2598 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002599 }
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002600 for (i = 0; i < nargs; i++) {
2601 item = args[i];
Raymond Hettingercfd735e2019-01-29 20:39:53 -08002602 ASSIGN_DOUBLE(x, item, error_exit);
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002603 x = fabs(x);
2604 coordinates[i] = x;
2605 found_nan |= Py_IS_NAN(x);
2606 if (x > max) {
2607 max = x;
2608 }
2609 }
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002610 result = vector_norm(nargs, coordinates, max, found_nan);
Raymond Hettingerc630e102018-08-11 18:39:05 -07002611 if (coordinates != coord_on_stack) {
2612 PyObject_Free(coordinates);
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002613 }
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002614 return PyFloat_FromDouble(result);
Raymond Hettingerc630e102018-08-11 18:39:05 -07002615
2616 error_exit:
2617 if (coordinates != coord_on_stack) {
2618 PyObject_Free(coordinates);
2619 }
2620 return NULL;
Christian Heimes53876d92008-04-19 00:31:39 +00002621}
2622
Raymond Hettingerc630e102018-08-11 18:39:05 -07002623#undef NUM_STACK_ELEMS
2624
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002625PyDoc_STRVAR(math_hypot_doc,
2626 "hypot(*coordinates) -> value\n\n\
2627Multidimensional Euclidean distance from the origin to a point.\n\
2628\n\
2629Roughly equivalent to:\n\
2630 sqrt(sum(x**2 for x in coordinates))\n\
2631\n\
2632For a two dimensional point (x, y), gives the hypotenuse\n\
2633using the Pythagorean theorem: sqrt(x*x + y*y).\n\
2634\n\
2635For example, the hypotenuse of a 3/4/5 right triangle is:\n\
2636\n\
2637 >>> hypot(3.0, 4.0)\n\
2638 5.0\n\
2639");
Christian Heimes53876d92008-04-19 00:31:39 +00002640
2641/* pow can't use math_2, but needs its own wrapper: the problem is
2642 that an infinite result can arise either as a result of overflow
2643 (in which case OverflowError should be raised) or as a result of
2644 e.g. 0.**-5. (for which ValueError needs to be raised.)
2645*/
2646
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002647/*[clinic input]
2648math.pow
Christian Heimes53876d92008-04-19 00:31:39 +00002649
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002650 x: double
2651 y: double
2652 /
2653
2654Return x**y (x to the power of y).
2655[clinic start generated code]*/
2656
2657static PyObject *
2658math_pow_impl(PyObject *module, double x, double y)
2659/*[clinic end generated code: output=fff93e65abccd6b0 input=c26f1f6075088bfd]*/
2660{
2661 double r;
2662 int odd_y;
Christian Heimesa342c012008-04-20 21:01:16 +00002663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 /* deal directly with IEEE specials, to cope with problems on various
2665 platforms whose semantics don't exactly match C99 */
2666 r = 0.; /* silence compiler warning */
2667 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
2668 errno = 0;
2669 if (Py_IS_NAN(x))
2670 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
2671 else if (Py_IS_NAN(y))
2672 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
2673 else if (Py_IS_INFINITY(x)) {
2674 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
2675 if (y > 0.)
2676 r = odd_y ? x : fabs(x);
2677 else if (y == 0.)
2678 r = 1.;
2679 else /* y < 0. */
2680 r = odd_y ? copysign(0., x) : 0.;
2681 }
2682 else if (Py_IS_INFINITY(y)) {
2683 if (fabs(x) == 1.0)
2684 r = 1.;
2685 else if (y > 0. && fabs(x) > 1.0)
2686 r = y;
2687 else if (y < 0. && fabs(x) < 1.0) {
2688 r = -y; /* result is +inf */
2689 if (x == 0.) /* 0**-inf: divide-by-zero */
2690 errno = EDOM;
2691 }
2692 else
2693 r = 0.;
2694 }
2695 }
2696 else {
2697 /* let libm handle finite**finite */
2698 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002699 r = pow(x, y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002700 /* a NaN result should arise only from (-ve)**(finite
2701 non-integer); in this case we want to raise ValueError. */
2702 if (!Py_IS_FINITE(r)) {
2703 if (Py_IS_NAN(r)) {
2704 errno = EDOM;
2705 }
2706 /*
2707 an infinite result here arises either from:
2708 (A) (+/-0.)**negative (-> divide-by-zero)
2709 (B) overflow of x**y with x and y finite
2710 */
2711 else if (Py_IS_INFINITY(r)) {
2712 if (x == 0.)
2713 errno = EDOM;
2714 else
2715 errno = ERANGE;
2716 }
2717 }
2718 }
Christian Heimes53876d92008-04-19 00:31:39 +00002719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002720 if (errno && is_error(r))
2721 return NULL;
2722 else
2723 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00002724}
2725
Christian Heimes53876d92008-04-19 00:31:39 +00002726
Christian Heimes072c0f12008-01-03 23:01:04 +00002727static const double degToRad = Py_MATH_PI / 180.0;
2728static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002729
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002730/*[clinic input]
2731math.degrees
2732
2733 x: double
2734 /
2735
2736Convert angle x from radians to degrees.
2737[clinic start generated code]*/
2738
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002739static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002740math_degrees_impl(PyObject *module, double x)
2741/*[clinic end generated code: output=7fea78b294acd12f input=81e016555d6e3660]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002742{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002743 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002744}
2745
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002746
2747/*[clinic input]
2748math.radians
2749
2750 x: double
2751 /
2752
2753Convert angle x from degrees to radians.
2754[clinic start generated code]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002755
2756static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002757math_radians_impl(PyObject *module, double x)
2758/*[clinic end generated code: output=34daa47caf9b1590 input=91626fc489fe3d63]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002760 return PyFloat_FromDouble(x * degToRad);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002761}
2762
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002763
2764/*[clinic input]
2765math.isfinite
2766
2767 x: double
2768 /
2769
2770Return True if x is neither an infinity nor a NaN, and False otherwise.
2771[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002772
Christian Heimes072c0f12008-01-03 23:01:04 +00002773static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002774math_isfinite_impl(PyObject *module, double x)
2775/*[clinic end generated code: output=8ba1f396440c9901 input=46967d254812e54a]*/
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002776{
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002777 return PyBool_FromLong((long)Py_IS_FINITE(x));
2778}
2779
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002780
2781/*[clinic input]
2782math.isnan
2783
2784 x: double
2785 /
2786
2787Return True if x is a NaN (not a number), and False otherwise.
2788[clinic start generated code]*/
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002789
2790static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002791math_isnan_impl(PyObject *module, double x)
2792/*[clinic end generated code: output=f537b4d6df878c3e input=935891e66083f46a]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002793{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002794 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00002795}
2796
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002797
2798/*[clinic input]
2799math.isinf
2800
2801 x: double
2802 /
2803
2804Return True if x is a positive or negative infinity, and False otherwise.
2805[clinic start generated code]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002806
2807static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002808math_isinf_impl(PyObject *module, double x)
2809/*[clinic end generated code: output=9f00cbec4de7b06b input=32630e4212cf961f]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002810{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002811 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00002812}
2813
Christian Heimes072c0f12008-01-03 23:01:04 +00002814
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002815/*[clinic input]
2816math.isclose -> bool
2817
2818 a: double
2819 b: double
2820 *
2821 rel_tol: double = 1e-09
2822 maximum difference for being considered "close", relative to the
2823 magnitude of the input values
2824 abs_tol: double = 0.0
2825 maximum difference for being considered "close", regardless of the
2826 magnitude of the input values
2827
2828Determine whether two floating point numbers are close in value.
2829
2830Return True if a is close in value to b, and False otherwise.
2831
2832For the values to be considered close, the difference between them
2833must be smaller than at least one of the tolerances.
2834
2835-inf, inf and NaN behave similarly to the IEEE 754 Standard. That
2836is, NaN is not close to anything, even itself. inf and -inf are
2837only close to themselves.
2838[clinic start generated code]*/
2839
2840static int
2841math_isclose_impl(PyObject *module, double a, double b, double rel_tol,
2842 double abs_tol)
2843/*[clinic end generated code: output=b73070207511952d input=f28671871ea5bfba]*/
Tal Einatd5519ed2015-05-31 22:05:00 +03002844{
Tal Einatd5519ed2015-05-31 22:05:00 +03002845 double diff = 0.0;
Tal Einatd5519ed2015-05-31 22:05:00 +03002846
2847 /* sanity check on the inputs */
2848 if (rel_tol < 0.0 || abs_tol < 0.0 ) {
2849 PyErr_SetString(PyExc_ValueError,
2850 "tolerances must be non-negative");
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002851 return -1;
Tal Einatd5519ed2015-05-31 22:05:00 +03002852 }
2853
2854 if ( a == b ) {
2855 /* short circuit exact equality -- needed to catch two infinities of
2856 the same sign. And perhaps speeds things up a bit sometimes.
2857 */
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002858 return 1;
Tal Einatd5519ed2015-05-31 22:05:00 +03002859 }
2860
2861 /* This catches the case of two infinities of opposite sign, or
2862 one infinity and one finite number. Two infinities of opposite
2863 sign would otherwise have an infinite relative tolerance.
2864 Two infinities of the same sign are caught by the equality check
2865 above.
2866 */
2867
2868 if (Py_IS_INFINITY(a) || Py_IS_INFINITY(b)) {
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002869 return 0;
Tal Einatd5519ed2015-05-31 22:05:00 +03002870 }
2871
2872 /* now do the regular computation
2873 this is essentially the "weak" test from the Boost library
2874 */
2875
2876 diff = fabs(b - a);
2877
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002878 return (((diff <= fabs(rel_tol * b)) ||
2879 (diff <= fabs(rel_tol * a))) ||
2880 (diff <= abs_tol));
Tal Einatd5519ed2015-05-31 22:05:00 +03002881}
2882
Pablo Galindo04114112019-03-09 19:18:08 +00002883static inline int
2884_check_long_mult_overflow(long a, long b) {
2885
2886 /* From Python2's int_mul code:
2887
2888 Integer overflow checking for * is painful: Python tried a couple ways, but
2889 they didn't work on all platforms, or failed in endcases (a product of
2890 -sys.maxint-1 has been a particular pain).
2891
2892 Here's another way:
2893
2894 The native long product x*y is either exactly right or *way* off, being
2895 just the last n bits of the true product, where n is the number of bits
2896 in a long (the delivered product is the true product plus i*2**n for
2897 some integer i).
2898
2899 The native double product (double)x * (double)y is subject to three
2900 rounding errors: on a sizeof(long)==8 box, each cast to double can lose
2901 info, and even on a sizeof(long)==4 box, the multiplication can lose info.
2902 But, unlike the native long product, it's not in *range* trouble: even
2903 if sizeof(long)==32 (256-bit longs), the product easily fits in the
2904 dynamic range of a double. So the leading 50 (or so) bits of the double
2905 product are correct.
2906
2907 We check these two ways against each other, and declare victory if they're
2908 approximately the same. Else, because the native long product is the only
2909 one that can lose catastrophic amounts of information, it's the native long
2910 product that must have overflowed.
2911
2912 */
2913
2914 long longprod = (long)((unsigned long)a * b);
2915 double doubleprod = (double)a * (double)b;
2916 double doubled_longprod = (double)longprod;
2917
2918 if (doubled_longprod == doubleprod) {
2919 return 0;
2920 }
2921
2922 const double diff = doubled_longprod - doubleprod;
2923 const double absdiff = diff >= 0.0 ? diff : -diff;
2924 const double absprod = doubleprod >= 0.0 ? doubleprod : -doubleprod;
2925
2926 if (32.0 * absdiff <= absprod) {
2927 return 0;
2928 }
2929
2930 return 1;
2931}
Tal Einatd5519ed2015-05-31 22:05:00 +03002932
Pablo Galindobc098512019-02-07 07:04:02 +00002933/*[clinic input]
2934math.prod
2935
2936 iterable: object
2937 /
2938 *
2939 start: object(c_default="NULL") = 1
2940
2941Calculate the product of all the elements in the input iterable.
2942
2943The default start value for the product is 1.
2944
2945When the iterable is empty, return the start value. This function is
2946intended specifically for use with numeric values and may reject
2947non-numeric types.
2948[clinic start generated code]*/
2949
2950static PyObject *
2951math_prod_impl(PyObject *module, PyObject *iterable, PyObject *start)
2952/*[clinic end generated code: output=36153bedac74a198 input=4c5ab0682782ed54]*/
2953{
2954 PyObject *result = start;
2955 PyObject *temp, *item, *iter;
2956
2957 iter = PyObject_GetIter(iterable);
2958 if (iter == NULL) {
2959 return NULL;
2960 }
2961
2962 if (result == NULL) {
2963 result = PyLong_FromLong(1);
2964 if (result == NULL) {
2965 Py_DECREF(iter);
2966 return NULL;
2967 }
2968 } else {
2969 Py_INCREF(result);
2970 }
2971#ifndef SLOW_PROD
2972 /* Fast paths for integers keeping temporary products in C.
2973 * Assumes all inputs are the same type.
2974 * If the assumption fails, default to use PyObjects instead.
2975 */
2976 if (PyLong_CheckExact(result)) {
2977 int overflow;
2978 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2979 /* If this already overflowed, don't even enter the loop. */
2980 if (overflow == 0) {
2981 Py_DECREF(result);
2982 result = NULL;
2983 }
2984 /* Loop over all the items in the iterable until we finish, we overflow
2985 * or we found a non integer element */
2986 while(result == NULL) {
2987 item = PyIter_Next(iter);
2988 if (item == NULL) {
2989 Py_DECREF(iter);
2990 if (PyErr_Occurred()) {
2991 return NULL;
2992 }
2993 return PyLong_FromLong(i_result);
2994 }
2995 if (PyLong_CheckExact(item)) {
2996 long b = PyLong_AsLongAndOverflow(item, &overflow);
Pablo Galindo04114112019-03-09 19:18:08 +00002997 if (overflow == 0 && !_check_long_mult_overflow(i_result, b)) {
2998 long x = i_result * b;
Pablo Galindobc098512019-02-07 07:04:02 +00002999 i_result = x;
3000 Py_DECREF(item);
3001 continue;
3002 }
3003 }
3004 /* Either overflowed or is not an int.
3005 * Restore real objects and process normally */
3006 result = PyLong_FromLong(i_result);
3007 if (result == NULL) {
3008 Py_DECREF(item);
3009 Py_DECREF(iter);
3010 return NULL;
3011 }
3012 temp = PyNumber_Multiply(result, item);
3013 Py_DECREF(result);
3014 Py_DECREF(item);
3015 result = temp;
3016 if (result == NULL) {
3017 Py_DECREF(iter);
3018 return NULL;
3019 }
3020 }
3021 }
3022
3023 /* Fast paths for floats keeping temporary products in C.
3024 * Assumes all inputs are the same type.
3025 * If the assumption fails, default to use PyObjects instead.
3026 */
3027 if (PyFloat_CheckExact(result)) {
3028 double f_result = PyFloat_AS_DOUBLE(result);
3029 Py_DECREF(result);
3030 result = NULL;
3031 while(result == NULL) {
3032 item = PyIter_Next(iter);
3033 if (item == NULL) {
3034 Py_DECREF(iter);
3035 if (PyErr_Occurred()) {
3036 return NULL;
3037 }
3038 return PyFloat_FromDouble(f_result);
3039 }
3040 if (PyFloat_CheckExact(item)) {
3041 f_result *= PyFloat_AS_DOUBLE(item);
3042 Py_DECREF(item);
3043 continue;
3044 }
3045 if (PyLong_CheckExact(item)) {
3046 long value;
3047 int overflow;
3048 value = PyLong_AsLongAndOverflow(item, &overflow);
3049 if (!overflow) {
3050 f_result *= (double)value;
3051 Py_DECREF(item);
3052 continue;
3053 }
3054 }
3055 result = PyFloat_FromDouble(f_result);
3056 if (result == NULL) {
3057 Py_DECREF(item);
3058 Py_DECREF(iter);
3059 return NULL;
3060 }
3061 temp = PyNumber_Multiply(result, item);
3062 Py_DECREF(result);
3063 Py_DECREF(item);
3064 result = temp;
3065 if (result == NULL) {
3066 Py_DECREF(iter);
3067 return NULL;
3068 }
3069 }
3070 }
3071#endif
3072 /* Consume rest of the iterable (if any) that could not be handled
3073 * by specialized functions above.*/
3074 for(;;) {
3075 item = PyIter_Next(iter);
3076 if (item == NULL) {
3077 /* error, or end-of-sequence */
3078 if (PyErr_Occurred()) {
3079 Py_DECREF(result);
3080 result = NULL;
3081 }
3082 break;
3083 }
3084 temp = PyNumber_Multiply(result, item);
3085 Py_DECREF(result);
3086 Py_DECREF(item);
3087 result = temp;
3088 if (result == NULL)
3089 break;
3090 }
3091 Py_DECREF(iter);
3092 return result;
3093}
3094
3095
Yash Aggarwal4a686502019-06-01 12:51:27 +05303096/*[clinic input]
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003097math.perm
3098
3099 n: object
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003100 k: object = None
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003101 /
3102
3103Number of ways to choose k items from n items without repetition and with order.
3104
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003105Evaluates to n! / (n - k)! when k <= n and evaluates
3106to zero when k > n.
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003107
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003108If k is not specified or is None, then k defaults to n
3109and the function returns n!.
3110
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003111Raises TypeError if either of the arguments are not integers.
3112Raises ValueError if either of the arguments are negative.
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003113[clinic start generated code]*/
3114
3115static PyObject *
3116math_perm_impl(PyObject *module, PyObject *n, PyObject *k)
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003117/*[clinic end generated code: output=e021a25469653e23 input=5311c5a00f359b53]*/
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003118{
3119 PyObject *result = NULL, *factor = NULL;
3120 int overflow, cmp;
3121 long long i, factors;
3122
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003123 if (k == Py_None) {
3124 return math_factorial(module, n);
3125 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003126 n = PyNumber_Index(n);
3127 if (n == NULL) {
3128 return NULL;
3129 }
3130 if (!PyLong_CheckExact(n)) {
3131 Py_SETREF(n, _PyLong_Copy((PyLongObject *)n));
3132 if (n == NULL) {
3133 return NULL;
3134 }
3135 }
3136 k = PyNumber_Index(k);
3137 if (k == NULL) {
3138 Py_DECREF(n);
3139 return NULL;
3140 }
3141 if (!PyLong_CheckExact(k)) {
3142 Py_SETREF(k, _PyLong_Copy((PyLongObject *)k));
3143 if (k == NULL) {
3144 Py_DECREF(n);
3145 return NULL;
3146 }
3147 }
3148
3149 if (Py_SIZE(n) < 0) {
3150 PyErr_SetString(PyExc_ValueError,
3151 "n must be a non-negative integer");
3152 goto error;
3153 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003154 if (Py_SIZE(k) < 0) {
3155 PyErr_SetString(PyExc_ValueError,
3156 "k must be a non-negative integer");
3157 goto error;
3158 }
3159
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003160 cmp = PyObject_RichCompareBool(n, k, Py_LT);
3161 if (cmp != 0) {
3162 if (cmp > 0) {
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003163 result = PyLong_FromLong(0);
3164 goto done;
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003165 }
3166 goto error;
3167 }
3168
3169 factors = PyLong_AsLongLongAndOverflow(k, &overflow);
3170 if (overflow > 0) {
3171 PyErr_Format(PyExc_OverflowError,
3172 "k must not exceed %lld",
3173 LLONG_MAX);
3174 goto error;
3175 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003176 else if (factors == -1) {
3177 /* k is nonnegative, so a return value of -1 can only indicate error */
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003178 goto error;
3179 }
3180
3181 if (factors == 0) {
3182 result = PyLong_FromLong(1);
3183 goto done;
3184 }
3185
3186 result = n;
3187 Py_INCREF(result);
3188 if (factors == 1) {
3189 goto done;
3190 }
3191
3192 factor = n;
3193 Py_INCREF(factor);
3194 for (i = 1; i < factors; ++i) {
3195 Py_SETREF(factor, PyNumber_Subtract(factor, _PyLong_One));
3196 if (factor == NULL) {
3197 goto error;
3198 }
3199 Py_SETREF(result, PyNumber_Multiply(result, factor));
3200 if (result == NULL) {
3201 goto error;
3202 }
3203 }
3204 Py_DECREF(factor);
3205
3206done:
3207 Py_DECREF(n);
3208 Py_DECREF(k);
3209 return result;
3210
3211error:
3212 Py_XDECREF(factor);
3213 Py_XDECREF(result);
3214 Py_DECREF(n);
3215 Py_DECREF(k);
3216 return NULL;
3217}
3218
3219
3220/*[clinic input]
Yash Aggarwal4a686502019-06-01 12:51:27 +05303221math.comb
3222
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003223 n: object
3224 k: object
3225 /
Yash Aggarwal4a686502019-06-01 12:51:27 +05303226
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003227Number of ways to choose k items from n items without repetition and without order.
Yash Aggarwal4a686502019-06-01 12:51:27 +05303228
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003229Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates
3230to zero when k > n.
Yash Aggarwal4a686502019-06-01 12:51:27 +05303231
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003232Also called the binomial coefficient because it is equivalent
3233to the coefficient of k-th term in polynomial expansion of the
3234expression (1 + x)**n.
3235
3236Raises TypeError if either of the arguments are not integers.
3237Raises ValueError if either of the arguments are negative.
Yash Aggarwal4a686502019-06-01 12:51:27 +05303238
3239[clinic start generated code]*/
3240
3241static PyObject *
3242math_comb_impl(PyObject *module, PyObject *n, PyObject *k)
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003243/*[clinic end generated code: output=bd2cec8d854f3493 input=9a05315af2518709]*/
Yash Aggarwal4a686502019-06-01 12:51:27 +05303244{
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003245 PyObject *result = NULL, *factor = NULL, *temp;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303246 int overflow, cmp;
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003247 long long i, factors;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303248
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003249 n = PyNumber_Index(n);
3250 if (n == NULL) {
3251 return NULL;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303252 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003253 if (!PyLong_CheckExact(n)) {
3254 Py_SETREF(n, _PyLong_Copy((PyLongObject *)n));
3255 if (n == NULL) {
3256 return NULL;
3257 }
3258 }
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003259 k = PyNumber_Index(k);
3260 if (k == NULL) {
3261 Py_DECREF(n);
3262 return NULL;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303263 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003264 if (!PyLong_CheckExact(k)) {
3265 Py_SETREF(k, _PyLong_Copy((PyLongObject *)k));
3266 if (k == NULL) {
3267 Py_DECREF(n);
3268 return NULL;
3269 }
3270 }
Yash Aggarwal4a686502019-06-01 12:51:27 +05303271
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003272 if (Py_SIZE(n) < 0) {
3273 PyErr_SetString(PyExc_ValueError,
3274 "n must be a non-negative integer");
3275 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303276 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003277 if (Py_SIZE(k) < 0) {
3278 PyErr_SetString(PyExc_ValueError,
3279 "k must be a non-negative integer");
3280 goto error;
3281 }
3282
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003283 /* k = min(k, n - k) */
3284 temp = PyNumber_Subtract(n, k);
3285 if (temp == NULL) {
3286 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303287 }
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003288 if (Py_SIZE(temp) < 0) {
3289 Py_DECREF(temp);
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003290 result = PyLong_FromLong(0);
3291 goto done;
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003292 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003293 cmp = PyObject_RichCompareBool(temp, k, Py_LT);
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003294 if (cmp > 0) {
3295 Py_SETREF(k, temp);
Yash Aggarwal4a686502019-06-01 12:51:27 +05303296 }
3297 else {
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003298 Py_DECREF(temp);
3299 if (cmp < 0) {
3300 goto error;
3301 }
Yash Aggarwal4a686502019-06-01 12:51:27 +05303302 }
3303
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003304 factors = PyLong_AsLongLongAndOverflow(k, &overflow);
3305 if (overflow > 0) {
Yash Aggarwal4a686502019-06-01 12:51:27 +05303306 PyErr_Format(PyExc_OverflowError,
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003307 "min(n - k, k) must not exceed %lld",
Yash Aggarwal4a686502019-06-01 12:51:27 +05303308 LLONG_MAX);
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003309 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303310 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003311 if (factors == -1) {
3312 /* k is nonnegative, so a return value of -1 can only indicate error */
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003313 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303314 }
3315
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003316 if (factors == 0) {
3317 result = PyLong_FromLong(1);
3318 goto done;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303319 }
3320
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003321 result = n;
3322 Py_INCREF(result);
3323 if (factors == 1) {
3324 goto done;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303325 }
3326
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003327 factor = n;
3328 Py_INCREF(factor);
3329 for (i = 1; i < factors; ++i) {
3330 Py_SETREF(factor, PyNumber_Subtract(factor, _PyLong_One));
3331 if (factor == NULL) {
3332 goto error;
3333 }
3334 Py_SETREF(result, PyNumber_Multiply(result, factor));
3335 if (result == NULL) {
3336 goto error;
3337 }
Yash Aggarwal4a686502019-06-01 12:51:27 +05303338
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003339 temp = PyLong_FromUnsignedLongLong((unsigned long long)i + 1);
3340 if (temp == NULL) {
3341 goto error;
3342 }
3343 Py_SETREF(result, PyNumber_FloorDivide(result, temp));
3344 Py_DECREF(temp);
3345 if (result == NULL) {
3346 goto error;
3347 }
3348 }
3349 Py_DECREF(factor);
Yash Aggarwal4a686502019-06-01 12:51:27 +05303350
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003351done:
3352 Py_DECREF(n);
3353 Py_DECREF(k);
3354 return result;
3355
3356error:
3357 Py_XDECREF(factor);
3358 Py_XDECREF(result);
3359 Py_DECREF(n);
3360 Py_DECREF(k);
Yash Aggarwal4a686502019-06-01 12:51:27 +05303361 return NULL;
3362}
3363
3364
Victor Stinner100fafc2020-01-12 02:15:42 +01003365/*[clinic input]
3366math.nextafter
3367
3368 x: double
3369 y: double
3370 /
3371
3372Return the next floating-point value after x towards y.
3373[clinic start generated code]*/
3374
3375static PyObject *
3376math_nextafter_impl(PyObject *module, double x, double y)
3377/*[clinic end generated code: output=750c8266c1c540ce input=02b2d50cd1d9f9b6]*/
3378{
Victor Stinner85ead4f2020-01-21 11:14:10 +01003379#if defined(_AIX)
3380 if (x == y) {
3381 /* On AIX 7.1, libm nextafter(-0.0, +0.0) returns -0.0.
3382 Bug fixed in bos.adt.libm 7.2.2.0 by APAR IV95512. */
3383 return PyFloat_FromDouble(y);
3384 }
3385#endif
3386 return PyFloat_FromDouble(nextafter(x, y));
Victor Stinner100fafc2020-01-12 02:15:42 +01003387}
3388
3389
Victor Stinner0b2ab212020-01-13 12:44:35 +01003390/*[clinic input]
3391math.ulp -> double
3392
3393 x: double
3394 /
3395
3396Return the value of the least significant bit of the float x.
3397[clinic start generated code]*/
3398
3399static double
3400math_ulp_impl(PyObject *module, double x)
3401/*[clinic end generated code: output=f5207867a9384dd4 input=31f9bfbbe373fcaa]*/
3402{
3403 if (Py_IS_NAN(x)) {
3404 return x;
3405 }
3406 x = fabs(x);
3407 if (Py_IS_INFINITY(x)) {
3408 return x;
3409 }
3410 double inf = m_inf();
3411 double x2 = nextafter(x, inf);
3412 if (Py_IS_INFINITY(x2)) {
3413 /* special case: x is the largest positive representable float */
3414 x2 = nextafter(x, -inf);
3415 return x - x2;
3416 }
3417 return x2 - x;
3418}
3419
3420
Barry Warsaw8b43b191996-12-09 22:32:36 +00003421static PyMethodDef math_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003422 {"acos", math_acos, METH_O, math_acos_doc},
3423 {"acosh", math_acosh, METH_O, math_acosh_doc},
3424 {"asin", math_asin, METH_O, math_asin_doc},
3425 {"asinh", math_asinh, METH_O, math_asinh_doc},
3426 {"atan", math_atan, METH_O, math_atan_doc},
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003427 {"atan2", (PyCFunction)(void(*)(void))math_atan2, METH_FASTCALL, math_atan2_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003428 {"atanh", math_atanh, METH_O, math_atanh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003429 MATH_CEIL_METHODDEF
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003430 {"copysign", (PyCFunction)(void(*)(void))math_copysign, METH_FASTCALL, math_copysign_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003431 {"cos", math_cos, METH_O, math_cos_doc},
3432 {"cosh", math_cosh, METH_O, math_cosh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003433 MATH_DEGREES_METHODDEF
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07003434 MATH_DIST_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003435 {"erf", math_erf, METH_O, math_erf_doc},
3436 {"erfc", math_erfc, METH_O, math_erfc_doc},
3437 {"exp", math_exp, METH_O, math_exp_doc},
3438 {"expm1", math_expm1, METH_O, math_expm1_doc},
3439 {"fabs", math_fabs, METH_O, math_fabs_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003440 MATH_FACTORIAL_METHODDEF
3441 MATH_FLOOR_METHODDEF
3442 MATH_FMOD_METHODDEF
3443 MATH_FREXP_METHODDEF
3444 MATH_FSUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003445 {"gamma", math_gamma, METH_O, math_gamma_doc},
Serhiy Storchaka559e7f12020-02-23 13:21:29 +02003446 {"gcd", (PyCFunction)(void(*)(void))math_gcd, METH_FASTCALL, math_gcd_doc},
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003447 {"hypot", (PyCFunction)(void(*)(void))math_hypot, METH_FASTCALL, math_hypot_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003448 MATH_ISCLOSE_METHODDEF
3449 MATH_ISFINITE_METHODDEF
3450 MATH_ISINF_METHODDEF
3451 MATH_ISNAN_METHODDEF
Mark Dickinson73934b92019-05-18 12:29:50 +01003452 MATH_ISQRT_METHODDEF
Serhiy Storchaka559e7f12020-02-23 13:21:29 +02003453 {"lcm", (PyCFunction)(void(*)(void))math_lcm, METH_FASTCALL, math_lcm_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003454 MATH_LDEXP_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003455 {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003456 MATH_LOG_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003457 {"log1p", math_log1p, METH_O, math_log1p_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003458 MATH_LOG10_METHODDEF
3459 MATH_LOG2_METHODDEF
3460 MATH_MODF_METHODDEF
3461 MATH_POW_METHODDEF
3462 MATH_RADIANS_METHODDEF
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003463 {"remainder", (PyCFunction)(void(*)(void))math_remainder, METH_FASTCALL, math_remainder_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003464 {"sin", math_sin, METH_O, math_sin_doc},
3465 {"sinh", math_sinh, METH_O, math_sinh_doc},
3466 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
3467 {"tan", math_tan, METH_O, math_tan_doc},
3468 {"tanh", math_tanh, METH_O, math_tanh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003469 MATH_TRUNC_METHODDEF
Pablo Galindobc098512019-02-07 07:04:02 +00003470 MATH_PROD_METHODDEF
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003471 MATH_PERM_METHODDEF
Yash Aggarwal4a686502019-06-01 12:51:27 +05303472 MATH_COMB_METHODDEF
Victor Stinner100fafc2020-01-12 02:15:42 +01003473 MATH_NEXTAFTER_METHODDEF
Victor Stinner0b2ab212020-01-13 12:44:35 +01003474 MATH_ULP_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003475 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003476};
3477
Guido van Rossumc6e22901998-12-04 19:26:43 +00003478
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003479PyDoc_STRVAR(module_doc,
Ned Batchelder6faad352019-05-17 05:59:14 -04003480"This module provides access to the mathematical functions\n"
3481"defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00003482
Martin v. Löwis1a214512008-06-11 05:26:20 +00003483
3484static struct PyModuleDef mathmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003485 PyModuleDef_HEAD_INIT,
3486 "math",
3487 module_doc,
3488 -1,
3489 math_methods,
3490 NULL,
3491 NULL,
3492 NULL,
3493 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003494};
3495
Mark Hammondfe51c6d2002-08-02 02:27:13 +00003496PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003497PyInit_math(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003499 PyObject *m;
Tim Petersfe71f812001-08-07 22:10:00 +00003500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003501 m = PyModule_Create(&mathmodule);
3502 if (m == NULL)
3503 goto finally;
Barry Warsawfc93f751996-12-17 00:47:03 +00003504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003505 PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
3506 PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
Guido van Rossum0a891d72016-08-15 09:12:52 -07003507 PyModule_AddObject(m, "tau", PyFloat_FromDouble(Py_MATH_TAU)); /* 2pi */
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +00003508 PyModule_AddObject(m, "inf", PyFloat_FromDouble(m_inf()));
3509#if !defined(PY_NO_SHORT_FLOAT_REPR) || defined(Py_NAN)
3510 PyModule_AddObject(m, "nan", PyFloat_FromDouble(m_nan()));
3511#endif
Barry Warsawfc93f751996-12-17 00:47:03 +00003512
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +00003513 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003514 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003515}