blob: 2a73a983f56d2d656966ece1ca9c2bbdbe13c61e [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]);
Zackery Spytz5208b4b2020-03-14 04:45:32 -06001109 if (x == -1.0 && PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 return NULL;
Zackery Spytz5208b4b2020-03-14 04:45:32 -06001111 }
1112 y = PyFloat_AsDouble(args[1]);
1113 if (y == -1.0 && PyErr_Occurred()) {
1114 return NULL;
1115 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 r = (*func)(x, y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 if (Py_IS_NAN(r)) {
1119 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1120 errno = EDOM;
1121 else
1122 errno = 0;
1123 }
1124 else if (Py_IS_INFINITY(r)) {
1125 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
1126 errno = ERANGE;
1127 else
1128 errno = 0;
1129 }
1130 if (errno && is_error(r))
1131 return NULL;
1132 else
1133 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001134}
1135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136#define FUNC1(funcname, func, can_overflow, docstring) \
1137 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
1138 return math_1(args, func, can_overflow); \
1139 }\
1140 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142#define FUNC1A(funcname, func, docstring) \
1143 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
1144 return math_1a(args, func); \
1145 }\
1146 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001147
Fred Drake40c48682000-07-03 18:11:56 +00001148#define FUNC2(funcname, func, docstring) \
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02001149 static PyObject * math_##funcname(PyObject *self, PyObject *const *args, Py_ssize_t nargs) { \
1150 return math_2(args, nargs, func, #funcname); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 }\
1152 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001153
Christian Heimes53876d92008-04-19 00:31:39 +00001154FUNC1(acos, acos, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001155 "acos($module, x, /)\n--\n\n"
Giovanni Cappellottodc3f99f2019-07-13 09:59:55 -04001156 "Return the arc cosine (measured in radians) of x.\n\n"
1157 "The result is between 0 and pi.")
Mark Dickinsonf3718592009-12-21 15:27:41 +00001158FUNC1(acosh, m_acosh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001159 "acosh($module, x, /)\n--\n\n"
1160 "Return the inverse hyperbolic cosine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001161FUNC1(asin, asin, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001162 "asin($module, x, /)\n--\n\n"
Giovanni Cappellottodc3f99f2019-07-13 09:59:55 -04001163 "Return the arc sine (measured in radians) of x.\n\n"
1164 "The result is between -pi/2 and pi/2.")
Mark Dickinsonf3718592009-12-21 15:27:41 +00001165FUNC1(asinh, m_asinh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001166 "asinh($module, x, /)\n--\n\n"
1167 "Return the inverse hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001168FUNC1(atan, atan, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001169 "atan($module, x, /)\n--\n\n"
Giovanni Cappellottodc3f99f2019-07-13 09:59:55 -04001170 "Return the arc tangent (measured in radians) of x.\n\n"
1171 "The result is between -pi/2 and pi/2.")
Christian Heimese57950f2008-04-21 13:08:03 +00001172FUNC2(atan2, m_atan2,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001173 "atan2($module, y, x, /)\n--\n\n"
1174 "Return the arc tangent (measured in radians) of y/x.\n\n"
Tim Petersfe71f812001-08-07 22:10:00 +00001175 "Unlike atan(y/x), the signs of both x and y are considered.")
Mark Dickinsonf3718592009-12-21 15:27:41 +00001176FUNC1(atanh, m_atanh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001177 "atanh($module, x, /)\n--\n\n"
1178 "Return the inverse hyperbolic tangent of x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +00001179
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001180/*[clinic input]
1181math.ceil
1182
1183 x as number: object
1184 /
1185
1186Return the ceiling of x as an Integral.
1187
1188This is the smallest integer >= x.
1189[clinic start generated code]*/
1190
1191static PyObject *
1192math_ceil(PyObject *module, PyObject *number)
1193/*[clinic end generated code: output=6c3b8a78bc201c67 input=2725352806399cab]*/
1194{
Benjamin Petersonce798522012-01-22 11:24:29 -05001195 _Py_IDENTIFIER(__ceil__);
Guido van Rossum13e05de2007-08-23 22:56:55 +00001196
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001197 if (!PyFloat_CheckExact(number)) {
1198 PyObject *method = _PyObject_LookupSpecial(number, &PyId___ceil__);
1199 if (method != NULL) {
1200 PyObject *result = _PyObject_CallNoArg(method);
1201 Py_DECREF(method);
1202 return result;
1203 }
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001204 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 return NULL;
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001206 }
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001207 double x = PyFloat_AsDouble(number);
1208 if (x == -1.0 && PyErr_Occurred())
1209 return NULL;
1210
1211 return PyLong_FromDouble(ceil(x));
Guido van Rossum13e05de2007-08-23 22:56:55 +00001212}
1213
Christian Heimes072c0f12008-01-03 23:01:04 +00001214FUNC2(copysign, copysign,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001215 "copysign($module, x, y, /)\n--\n\n"
1216 "Return a float with the magnitude (absolute value) of x but the sign of y.\n\n"
1217 "On platforms that support signed zeros, copysign(1.0, -0.0)\n"
1218 "returns -1.0.\n")
Christian Heimes53876d92008-04-19 00:31:39 +00001219FUNC1(cos, cos, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001220 "cos($module, x, /)\n--\n\n"
1221 "Return the cosine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001222FUNC1(cosh, cosh, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001223 "cosh($module, x, /)\n--\n\n"
1224 "Return the hyperbolic cosine of x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +00001225FUNC1A(erf, m_erf,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001226 "erf($module, x, /)\n--\n\n"
1227 "Error function at x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +00001228FUNC1A(erfc, m_erfc,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001229 "erfc($module, x, /)\n--\n\n"
1230 "Complementary error function at x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001231FUNC1(exp, exp, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001232 "exp($module, x, /)\n--\n\n"
1233 "Return e raised to the power of x.")
Mark Dickinson664b5112009-12-16 20:23:42 +00001234FUNC1(expm1, m_expm1, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001235 "expm1($module, x, /)\n--\n\n"
1236 "Return exp(x)-1.\n\n"
Mark Dickinson664b5112009-12-16 20:23:42 +00001237 "This function avoids the loss of precision involved in the direct "
1238 "evaluation of exp(x)-1 for small x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001239FUNC1(fabs, fabs, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001240 "fabs($module, x, /)\n--\n\n"
1241 "Return the absolute value of the float x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +00001242
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001243/*[clinic input]
1244math.floor
1245
1246 x as number: object
1247 /
1248
1249Return the floor of x as an Integral.
1250
1251This is the largest integer <= x.
1252[clinic start generated code]*/
1253
1254static PyObject *
1255math_floor(PyObject *module, PyObject *number)
1256/*[clinic end generated code: output=c6a65c4884884b8a input=63af6b5d7ebcc3d6]*/
1257{
Benjamin Petersonce798522012-01-22 11:24:29 -05001258 _Py_IDENTIFIER(__floor__);
Guido van Rossum13e05de2007-08-23 22:56:55 +00001259
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001260 if (!PyFloat_CheckExact(number)) {
1261 PyObject *method = _PyObject_LookupSpecial(number, &PyId___floor__);
1262 if (method != NULL) {
1263 PyObject *result = _PyObject_CallNoArg(method);
1264 Py_DECREF(method);
1265 return result;
1266 }
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001267 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 return NULL;
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001269 }
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001270 double x = PyFloat_AsDouble(number);
1271 if (x == -1.0 && PyErr_Occurred())
1272 return NULL;
1273
1274 return PyLong_FromDouble(floor(x));
Guido van Rossum13e05de2007-08-23 22:56:55 +00001275}
1276
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001277FUNC1A(gamma, m_tgamma,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001278 "gamma($module, x, /)\n--\n\n"
1279 "Gamma function at x.")
Mark Dickinson05d2e082009-12-11 20:17:17 +00001280FUNC1A(lgamma, m_lgamma,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001281 "lgamma($module, x, /)\n--\n\n"
1282 "Natural logarithm of absolute value of Gamma function at x.")
Mark Dickinsonbe64d952010-07-07 16:21:29 +00001283FUNC1(log1p, m_log1p, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001284 "log1p($module, x, /)\n--\n\n"
1285 "Return the natural logarithm of 1+x (base e).\n\n"
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001286 "The result is computed in a way which is accurate for x near zero.")
Mark Dickinsona0ce3752017-04-05 18:34:27 +01001287FUNC2(remainder, m_remainder,
1288 "remainder($module, x, y, /)\n--\n\n"
1289 "Difference between x and the closest integer multiple of y.\n\n"
1290 "Return x - n*y where n*y is the closest integer multiple of y.\n"
1291 "In the case where x is exactly halfway between two multiples of\n"
1292 "y, the nearest even value of n is used. The result is always exact.")
Christian Heimes53876d92008-04-19 00:31:39 +00001293FUNC1(sin, sin, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001294 "sin($module, x, /)\n--\n\n"
1295 "Return the sine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001296FUNC1(sinh, sinh, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001297 "sinh($module, x, /)\n--\n\n"
1298 "Return the hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001299FUNC1(sqrt, sqrt, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001300 "sqrt($module, x, /)\n--\n\n"
1301 "Return the square root of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001302FUNC1(tan, tan, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001303 "tan($module, x, /)\n--\n\n"
1304 "Return the tangent of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001305FUNC1(tanh, tanh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001306 "tanh($module, x, /)\n--\n\n"
1307 "Return the hyperbolic tangent of x.")
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001308
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001309/* Precision summation function as msum() by Raymond Hettinger in
1310 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
1311 enhanced with the exact partials sum and roundoff from Mark
1312 Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
1313 See those links for more details, proofs and other references.
1314
1315 Note 1: IEEE 754R floating point semantics are assumed,
1316 but the current implementation does not re-establish special
1317 value semantics across iterations (i.e. handling -Inf + Inf).
1318
1319 Note 2: No provision is made for intermediate overflow handling;
Georg Brandlf78e02b2008-06-10 17:40:04 +00001320 therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001321 sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
1322 overflow of the first partial sum.
1323
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001324 Note 3: The intermediate values lo, yr, and hi are declared volatile so
1325 aggressive compilers won't algebraically reduce lo to always be exactly 0.0.
Georg Brandlf78e02b2008-06-10 17:40:04 +00001326 Also, the volatile declaration forces the values to be stored in memory as
1327 regular doubles instead of extended long precision (80-bit) values. This
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001328 prevents double rounding because any addition or subtraction of two doubles
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 can be resolved exactly into double-sized hi and lo values. As long as the
Georg Brandlf78e02b2008-06-10 17:40:04 +00001330 hi value gets forced into a double before yr and lo are computed, the extra
1331 bits in downstream extended precision operations (x87 for example) will be
1332 exactly zero and therefore can be losslessly stored back into a double,
1333 thereby preventing double rounding.
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001334
1335 Note 4: A similar implementation is in Modules/cmathmodule.c.
1336 Be sure to update both when making changes.
1337
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001338 Note 5: The signature of math.fsum() differs from builtins.sum()
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001339 because the start argument doesn't make sense in the context of
1340 accurate summation. Since the partials table is collapsed before
1341 returning a result, sum(seq2, start=sum(seq1)) may not equal the
1342 accurate result returned by sum(itertools.chain(seq1, seq2)).
1343*/
1344
1345#define NUM_PARTIALS 32 /* initial partials array size, on stack */
1346
1347/* Extend the partials array p[] by doubling its size. */
1348static int /* non-zero on error */
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001349_fsum_realloc(double **p_ptr, Py_ssize_t n,
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001350 double *ps, Py_ssize_t *m_ptr)
1351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 void *v = NULL;
1353 Py_ssize_t m = *m_ptr;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 m += m; /* double */
Victor Stinner049e5092014-08-17 22:20:00 +02001356 if (n < m && (size_t)m < ((size_t)PY_SSIZE_T_MAX / sizeof(double))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 double *p = *p_ptr;
1358 if (p == ps) {
1359 v = PyMem_Malloc(sizeof(double) * m);
1360 if (v != NULL)
1361 memcpy(v, ps, sizeof(double) * n);
1362 }
1363 else
1364 v = PyMem_Realloc(p, sizeof(double) * m);
1365 }
1366 if (v == NULL) { /* size overflow or no memory */
1367 PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
1368 return 1;
1369 }
1370 *p_ptr = (double*) v;
1371 *m_ptr = m;
1372 return 0;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001373}
1374
1375/* Full precision summation of a sequence of floats.
1376
1377 def msum(iterable):
1378 partials = [] # sorted, non-overlapping partial sums
1379 for x in iterable:
Mark Dickinsonfdb0acc2010-06-25 20:22:24 +00001380 i = 0
1381 for y in partials:
1382 if abs(x) < abs(y):
1383 x, y = y, x
1384 hi = x + y
1385 lo = y - (hi - x)
1386 if lo:
1387 partials[i] = lo
1388 i += 1
1389 x = hi
1390 partials[i:] = [x]
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001391 return sum_exact(partials)
1392
1393 Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
1394 are exactly equal to x+y. The inner loop applies hi/lo summation to each
1395 partial so that the list of partial sums remains exact.
1396
1397 Sum_exact() adds the partial sums exactly and correctly rounds the final
1398 result (using the round-half-to-even rule). The items in partials remain
1399 non-zero, non-special, non-overlapping and strictly increasing in
1400 magnitude, but possibly not all having the same sign.
1401
1402 Depends on IEEE 754 arithmetic guarantees and half-even rounding.
1403*/
1404
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001405/*[clinic input]
1406math.fsum
1407
1408 seq: object
1409 /
1410
1411Return an accurate floating point sum of values in the iterable seq.
1412
1413Assumes IEEE-754 floating point arithmetic.
1414[clinic start generated code]*/
1415
1416static PyObject *
1417math_fsum(PyObject *module, PyObject *seq)
1418/*[clinic end generated code: output=ba5c672b87fe34fc input=c51b7d8caf6f6e82]*/
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 PyObject *item, *iter, *sum = NULL;
1421 Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
1422 double x, y, t, ps[NUM_PARTIALS], *p = ps;
1423 double xsave, special_sum = 0.0, inf_sum = 0.0;
1424 volatile double hi, yr, lo;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 iter = PyObject_GetIter(seq);
1427 if (iter == NULL)
1428 return NULL;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 for(;;) { /* for x in iterable */
1431 assert(0 <= n && n <= m);
1432 assert((m == NUM_PARTIALS && p == ps) ||
1433 (m > NUM_PARTIALS && p != NULL));
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 item = PyIter_Next(iter);
1436 if (item == NULL) {
1437 if (PyErr_Occurred())
1438 goto _fsum_error;
1439 break;
1440 }
Raymond Hettingercfd735e2019-01-29 20:39:53 -08001441 ASSIGN_DOUBLE(x, item, error_with_item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 Py_DECREF(item);
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 xsave = x;
1445 for (i = j = 0; j < n; j++) { /* for y in partials */
1446 y = p[j];
1447 if (fabs(x) < fabs(y)) {
1448 t = x; x = y; y = t;
1449 }
1450 hi = x + y;
1451 yr = hi - x;
1452 lo = y - yr;
1453 if (lo != 0.0)
1454 p[i++] = lo;
1455 x = hi;
1456 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 n = i; /* ps[i:] = [x] */
1459 if (x != 0.0) {
1460 if (! Py_IS_FINITE(x)) {
1461 /* a nonfinite x could arise either as
1462 a result of intermediate overflow, or
1463 as a result of a nan or inf in the
1464 summands */
1465 if (Py_IS_FINITE(xsave)) {
1466 PyErr_SetString(PyExc_OverflowError,
1467 "intermediate overflow in fsum");
1468 goto _fsum_error;
1469 }
1470 if (Py_IS_INFINITY(xsave))
1471 inf_sum += xsave;
1472 special_sum += xsave;
1473 /* reset partials */
1474 n = 0;
1475 }
1476 else if (n >= m && _fsum_realloc(&p, n, ps, &m))
1477 goto _fsum_error;
1478 else
1479 p[n++] = x;
1480 }
1481 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 if (special_sum != 0.0) {
1484 if (Py_IS_NAN(inf_sum))
1485 PyErr_SetString(PyExc_ValueError,
1486 "-inf + inf in fsum");
1487 else
1488 sum = PyFloat_FromDouble(special_sum);
1489 goto _fsum_error;
1490 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 hi = 0.0;
1493 if (n > 0) {
1494 hi = p[--n];
1495 /* sum_exact(ps, hi) from the top, stop when the sum becomes
1496 inexact. */
1497 while (n > 0) {
1498 x = hi;
1499 y = p[--n];
1500 assert(fabs(y) < fabs(x));
1501 hi = x + y;
1502 yr = hi - x;
1503 lo = y - yr;
1504 if (lo != 0.0)
1505 break;
1506 }
1507 /* Make half-even rounding work across multiple partials.
1508 Needed so that sum([1e-16, 1, 1e16]) will round-up the last
1509 digit to two instead of down to zero (the 1e-16 makes the 1
1510 slightly closer to two). With a potential 1 ULP rounding
1511 error fixed-up, math.fsum() can guarantee commutativity. */
1512 if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
1513 (lo > 0.0 && p[n-1] > 0.0))) {
1514 y = lo * 2.0;
1515 x = hi + y;
1516 yr = x - hi;
1517 if (y == yr)
1518 hi = x;
1519 }
1520 }
1521 sum = PyFloat_FromDouble(hi);
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001522
Raymond Hettingercfd735e2019-01-29 20:39:53 -08001523 _fsum_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 Py_DECREF(iter);
1525 if (p != ps)
1526 PyMem_Free(p);
1527 return sum;
Raymond Hettingercfd735e2019-01-29 20:39:53 -08001528
1529 error_with_item:
1530 Py_DECREF(item);
1531 goto _fsum_error;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001532}
1533
1534#undef NUM_PARTIALS
1535
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001536
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001537static unsigned long
1538count_set_bits(unsigned long n)
1539{
1540 unsigned long count = 0;
1541 while (n != 0) {
1542 ++count;
1543 n &= n - 1; /* clear least significant bit */
1544 }
1545 return count;
1546}
1547
Mark Dickinson73934b92019-05-18 12:29:50 +01001548/* Integer square root
1549
1550Given a nonnegative integer `n`, we want to compute the largest integer
1551`a` for which `a * a <= n`, or equivalently the integer part of the exact
1552square root of `n`.
1553
1554We use an adaptive-precision pure-integer version of Newton's iteration. Given
1555a positive integer `n`, the algorithm produces at each iteration an integer
1556approximation `a` to the square root of `n >> s` for some even integer `s`,
1557with `s` decreasing as the iterations progress. On the final iteration, `s` is
1558zero and we have an approximation to the square root of `n` itself.
1559
1560At every step, the approximation `a` is strictly within 1.0 of the true square
1561root, so we have
1562
1563 (a - 1)**2 < (n >> s) < (a + 1)**2
1564
1565After the final iteration, a check-and-correct step is needed to determine
1566whether `a` or `a - 1` gives the desired integer square root of `n`.
1567
1568The algorithm is remarkable in its simplicity. There's no need for a
1569per-iteration check-and-correct step, and termination is straightforward: the
1570number of iterations is known in advance (it's exactly `floor(log2(log2(n)))`
1571for `n > 1`). The only tricky part of the correctness proof is in establishing
1572that the bound `(a - 1)**2 < (n >> s) < (a + 1)**2` is maintained from one
1573iteration to the next. A sketch of the proof of this is given below.
1574
1575In addition to the proof sketch, a formal, computer-verified proof
1576of correctness (using Lean) of an equivalent recursive algorithm can be found
1577here:
1578
1579 https://github.com/mdickinson/snippets/blob/master/proofs/isqrt/src/isqrt.lean
1580
1581
1582Here's Python code equivalent to the C implementation below:
1583
1584 def isqrt(n):
1585 """
1586 Return the integer part of the square root of the input.
1587 """
1588 n = operator.index(n)
1589
1590 if n < 0:
1591 raise ValueError("isqrt() argument must be nonnegative")
1592 if n == 0:
1593 return 0
1594
1595 c = (n.bit_length() - 1) // 2
1596 a = 1
1597 d = 0
1598 for s in reversed(range(c.bit_length())):
Mark Dickinson2dfeaa92019-06-16 17:53:21 +01001599 # Loop invariant: (a-1)**2 < (n >> 2*(c - d)) < (a+1)**2
Mark Dickinson73934b92019-05-18 12:29:50 +01001600 e = d
1601 d = c >> s
1602 a = (a << d - e - 1) + (n >> 2*c - e - d + 1) // a
Mark Dickinson73934b92019-05-18 12:29:50 +01001603
1604 return a - (a*a > n)
1605
1606
1607Sketch of proof of correctness
1608------------------------------
1609
1610The delicate part of the correctness proof is showing that the loop invariant
1611is preserved from one iteration to the next. That is, just before the line
1612
1613 a = (a << d - e - 1) + (n >> 2*c - e - d + 1) // a
1614
1615is executed in the above code, we know that
1616
1617 (1) (a - 1)**2 < (n >> 2*(c - e)) < (a + 1)**2.
1618
1619(since `e` is always the value of `d` from the previous iteration). We must
1620prove that after that line is executed, we have
1621
1622 (a - 1)**2 < (n >> 2*(c - d)) < (a + 1)**2
1623
Min ho Kimf7d72e42019-07-06 07:39:32 +10001624To facilitate the proof, we make some changes of notation. Write `m` for
Mark Dickinson73934b92019-05-18 12:29:50 +01001625`n >> 2*(c-d)`, and write `b` for the new value of `a`, so
1626
1627 b = (a << d - e - 1) + (n >> 2*c - e - d + 1) // a
1628
1629or equivalently:
1630
1631 (2) b = (a << d - e - 1) + (m >> d - e + 1) // a
1632
1633Then we can rewrite (1) as:
1634
1635 (3) (a - 1)**2 < (m >> 2*(d - e)) < (a + 1)**2
1636
1637and we must show that (b - 1)**2 < m < (b + 1)**2.
1638
1639From this point on, we switch to mathematical notation, so `/` means exact
1640division rather than integer division and `^` is used for exponentiation. We
1641use the `√` symbol for the exact square root. In (3), we can remove the
1642implicit floor operation to give:
1643
1644 (4) (a - 1)^2 < m / 4^(d - e) < (a + 1)^2
1645
1646Taking square roots throughout (4), scaling by `2^(d-e)`, and rearranging gives
1647
1648 (5) 0 <= | 2^(d-e)a - √m | < 2^(d-e)
1649
1650Squaring and dividing through by `2^(d-e+1) a` gives
1651
1652 (6) 0 <= 2^(d-e-1) a + m / (2^(d-e+1) a) - √m < 2^(d-e-1) / a
1653
1654We'll show below that `2^(d-e-1) <= a`. Given that, we can replace the
1655right-hand side of (6) with `1`, and now replacing the central
1656term `m / (2^(d-e+1) a)` with its floor in (6) gives
1657
1658 (7) -1 < 2^(d-e-1) a + m // 2^(d-e+1) a - √m < 1
1659
1660Or equivalently, from (2):
1661
1662 (7) -1 < b - √m < 1
1663
1664and rearranging gives that `(b-1)^2 < m < (b+1)^2`, which is what we needed
1665to prove.
1666
1667We're not quite done: we still have to prove the inequality `2^(d - e - 1) <=
1668a` that was used to get line (7) above. From the definition of `c`, we have
1669`4^c <= n`, which implies
1670
1671 (8) 4^d <= m
1672
1673also, since `e == d >> 1`, `d` is at most `2e + 1`, from which it follows
1674that `2d - 2e - 1 <= d` and hence that
1675
1676 (9) 4^(2d - 2e - 1) <= m
1677
1678Dividing both sides by `4^(d - e)` gives
1679
1680 (10) 4^(d - e - 1) <= m / 4^(d - e)
1681
1682But we know from (4) that `m / 4^(d-e) < (a + 1)^2`, hence
1683
1684 (11) 4^(d - e - 1) < (a + 1)^2
1685
1686Now taking square roots of both sides and observing that both `2^(d-e-1)` and
1687`a` are integers gives `2^(d - e - 1) <= a`, which is what we needed. This
1688completes the proof sketch.
1689
1690*/
1691
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001692
1693/* Approximate square root of a large 64-bit integer.
1694
1695 Given `n` satisfying `2**62 <= n < 2**64`, return `a`
1696 satisfying `(a - 1)**2 < n < (a + 1)**2`. */
1697
1698static uint64_t
1699_approximate_isqrt(uint64_t n)
1700{
1701 uint32_t u = 1U + (n >> 62);
1702 u = (u << 1) + (n >> 59) / u;
1703 u = (u << 3) + (n >> 53) / u;
1704 u = (u << 7) + (n >> 41) / u;
1705 return (u << 15) + (n >> 17) / u;
1706}
1707
Mark Dickinson73934b92019-05-18 12:29:50 +01001708/*[clinic input]
1709math.isqrt
1710
1711 n: object
1712 /
1713
1714Return the integer part of the square root of the input.
1715[clinic start generated code]*/
1716
1717static PyObject *
1718math_isqrt(PyObject *module, PyObject *n)
1719/*[clinic end generated code: output=35a6f7f980beab26 input=5b6e7ae4fa6c43d6]*/
1720{
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001721 int a_too_large, c_bit_length;
Mark Dickinson73934b92019-05-18 12:29:50 +01001722 size_t c, d;
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001723 uint64_t m, u;
Mark Dickinson73934b92019-05-18 12:29:50 +01001724 PyObject *a = NULL, *b;
1725
1726 n = PyNumber_Index(n);
1727 if (n == NULL) {
1728 return NULL;
1729 }
1730
1731 if (_PyLong_Sign(n) < 0) {
1732 PyErr_SetString(
1733 PyExc_ValueError,
1734 "isqrt() argument must be nonnegative");
1735 goto error;
1736 }
1737 if (_PyLong_Sign(n) == 0) {
1738 Py_DECREF(n);
1739 return PyLong_FromLong(0);
1740 }
1741
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001742 /* c = (n.bit_length() - 1) // 2 */
Mark Dickinson73934b92019-05-18 12:29:50 +01001743 c = _PyLong_NumBits(n);
1744 if (c == (size_t)(-1)) {
1745 goto error;
1746 }
1747 c = (c - 1U) / 2U;
1748
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001749 /* Fast path: if c <= 31 then n < 2**64 and we can compute directly with a
1750 fast, almost branch-free algorithm. In the final correction, we use `u*u
1751 - 1 >= m` instead of the simpler `u*u > m` in order to get the correct
1752 result in the corner case where `u=2**32`. */
1753 if (c <= 31U) {
1754 m = (uint64_t)PyLong_AsUnsignedLongLong(n);
1755 Py_DECREF(n);
1756 if (m == (uint64_t)(-1) && PyErr_Occurred()) {
1757 return NULL;
1758 }
1759 u = _approximate_isqrt(m << (62U - 2U*c)) >> (31U - c);
1760 u -= u * u - 1U >= m;
1761 return PyLong_FromUnsignedLongLong((unsigned long long)u);
Mark Dickinson73934b92019-05-18 12:29:50 +01001762 }
1763
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001764 /* Slow path: n >= 2**64. We perform the first five iterations in C integer
1765 arithmetic, then switch to using Python long integers. */
1766
1767 /* From n >= 2**64 it follows that c.bit_length() >= 6. */
1768 c_bit_length = 6;
1769 while ((c >> c_bit_length) > 0U) {
1770 ++c_bit_length;
1771 }
1772
1773 /* Initialise d and a. */
1774 d = c >> (c_bit_length - 5);
1775 b = _PyLong_Rshift(n, 2U*c - 62U);
1776 if (b == NULL) {
1777 goto error;
1778 }
1779 m = (uint64_t)PyLong_AsUnsignedLongLong(b);
1780 Py_DECREF(b);
1781 if (m == (uint64_t)(-1) && PyErr_Occurred()) {
1782 goto error;
1783 }
1784 u = _approximate_isqrt(m) >> (31U - d);
1785 a = PyLong_FromUnsignedLongLong((unsigned long long)u);
Mark Dickinson73934b92019-05-18 12:29:50 +01001786 if (a == NULL) {
1787 goto error;
1788 }
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001789
1790 for (int s = c_bit_length - 6; s >= 0; --s) {
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03001791 PyObject *q;
Mark Dickinson73934b92019-05-18 12:29:50 +01001792 size_t e = d;
1793
1794 d = c >> s;
1795
1796 /* q = (n >> 2*c - e - d + 1) // a */
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03001797 q = _PyLong_Rshift(n, 2U*c - d - e + 1U);
Mark Dickinson73934b92019-05-18 12:29:50 +01001798 if (q == NULL) {
1799 goto error;
1800 }
1801 Py_SETREF(q, PyNumber_FloorDivide(q, a));
1802 if (q == NULL) {
1803 goto error;
1804 }
1805
1806 /* a = (a << d - 1 - e) + q */
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03001807 Py_SETREF(a, _PyLong_Lshift(a, d - 1U - e));
Mark Dickinson73934b92019-05-18 12:29:50 +01001808 if (a == NULL) {
1809 Py_DECREF(q);
1810 goto error;
1811 }
1812 Py_SETREF(a, PyNumber_Add(a, q));
1813 Py_DECREF(q);
1814 if (a == NULL) {
1815 goto error;
1816 }
1817 }
1818
1819 /* The correct result is either a or a - 1. Figure out which, and
1820 decrement a if necessary. */
1821
1822 /* a_too_large = n < a * a */
1823 b = PyNumber_Multiply(a, a);
1824 if (b == NULL) {
1825 goto error;
1826 }
1827 a_too_large = PyObject_RichCompareBool(n, b, Py_LT);
1828 Py_DECREF(b);
1829 if (a_too_large == -1) {
1830 goto error;
1831 }
1832
1833 if (a_too_large) {
1834 Py_SETREF(a, PyNumber_Subtract(a, _PyLong_One));
1835 }
1836 Py_DECREF(n);
1837 return a;
1838
1839 error:
1840 Py_XDECREF(a);
1841 Py_DECREF(n);
1842 return NULL;
1843}
1844
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001845/* Divide-and-conquer factorial algorithm
1846 *
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07001847 * Based on the formula and pseudo-code provided at:
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001848 * http://www.luschny.de/math/factorial/binarysplitfact.html
1849 *
1850 * Faster algorithms exist, but they're more complicated and depend on
Ezio Melotti9527afd2010-07-08 15:03:02 +00001851 * a fast prime factorization algorithm.
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001852 *
1853 * Notes on the algorithm
1854 * ----------------------
1855 *
1856 * factorial(n) is written in the form 2**k * m, with m odd. k and m are
1857 * computed separately, and then combined using a left shift.
1858 *
1859 * The function factorial_odd_part computes the odd part m (i.e., the greatest
1860 * odd divisor) of factorial(n), using the formula:
1861 *
1862 * factorial_odd_part(n) =
1863 *
1864 * product_{i >= 0} product_{0 < j <= n / 2**i, j odd} j
1865 *
1866 * Example: factorial_odd_part(20) =
1867 *
1868 * (1) *
1869 * (1) *
1870 * (1 * 3 * 5) *
1871 * (1 * 3 * 5 * 7 * 9)
1872 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1873 *
1874 * Here i goes from large to small: the first term corresponds to i=4 (any
1875 * larger i gives an empty product), and the last term corresponds to i=0.
1876 * Each term can be computed from the last by multiplying by the extra odd
1877 * numbers required: e.g., to get from the penultimate term to the last one,
1878 * we multiply by (11 * 13 * 15 * 17 * 19).
1879 *
1880 * To see a hint of why this formula works, here are the same numbers as above
1881 * but with the even parts (i.e., the appropriate powers of 2) included. For
1882 * each subterm in the product for i, we multiply that subterm by 2**i:
1883 *
1884 * factorial(20) =
1885 *
1886 * (16) *
1887 * (8) *
1888 * (4 * 12 * 20) *
1889 * (2 * 6 * 10 * 14 * 18) *
1890 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1891 *
1892 * The factorial_partial_product function computes the product of all odd j in
1893 * range(start, stop) for given start and stop. It's used to compute the
1894 * partial products like (11 * 13 * 15 * 17 * 19) in the example above. It
1895 * operates recursively, repeatedly splitting the range into two roughly equal
1896 * pieces until the subranges are small enough to be computed using only C
1897 * integer arithmetic.
1898 *
1899 * The two-valuation k (i.e., the exponent of the largest power of 2 dividing
1900 * the factorial) is computed independently in the main math_factorial
1901 * function. By standard results, its value is:
1902 *
1903 * two_valuation = n//2 + n//4 + n//8 + ....
1904 *
1905 * It can be shown (e.g., by complete induction on n) that two_valuation is
1906 * equal to n - count_set_bits(n), where count_set_bits(n) gives the number of
1907 * '1'-bits in the binary expansion of n.
1908 */
1909
1910/* factorial_partial_product: Compute product(range(start, stop, 2)) using
1911 * divide and conquer. Assumes start and stop are odd and stop > start.
1912 * max_bits must be >= bit_length(stop - 2). */
1913
1914static PyObject *
1915factorial_partial_product(unsigned long start, unsigned long stop,
1916 unsigned long max_bits)
1917{
1918 unsigned long midpoint, num_operands;
1919 PyObject *left = NULL, *right = NULL, *result = NULL;
1920
1921 /* If the return value will fit an unsigned long, then we can
1922 * multiply in a tight, fast loop where each multiply is O(1).
1923 * Compute an upper bound on the number of bits required to store
1924 * the answer.
1925 *
1926 * Storing some integer z requires floor(lg(z))+1 bits, which is
1927 * conveniently the value returned by bit_length(z). The
1928 * product x*y will require at most
1929 * bit_length(x) + bit_length(y) bits to store, based
1930 * on the idea that lg product = lg x + lg y.
1931 *
1932 * We know that stop - 2 is the largest number to be multiplied. From
1933 * there, we have: bit_length(answer) <= num_operands *
1934 * bit_length(stop - 2)
1935 */
1936
1937 num_operands = (stop - start) / 2;
1938 /* The "num_operands <= 8 * SIZEOF_LONG" check guards against the
1939 * unlikely case of an overflow in num_operands * max_bits. */
1940 if (num_operands <= 8 * SIZEOF_LONG &&
1941 num_operands * max_bits <= 8 * SIZEOF_LONG) {
1942 unsigned long j, total;
1943 for (total = start, j = start + 2; j < stop; j += 2)
1944 total *= j;
1945 return PyLong_FromUnsignedLong(total);
1946 }
1947
1948 /* find midpoint of range(start, stop), rounded up to next odd number. */
1949 midpoint = (start + num_operands) | 1;
1950 left = factorial_partial_product(start, midpoint,
Niklas Fiekasc5b79002020-01-16 15:09:19 +01001951 _Py_bit_length(midpoint - 2));
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001952 if (left == NULL)
1953 goto error;
1954 right = factorial_partial_product(midpoint, stop, max_bits);
1955 if (right == NULL)
1956 goto error;
1957 result = PyNumber_Multiply(left, right);
1958
1959 error:
1960 Py_XDECREF(left);
1961 Py_XDECREF(right);
1962 return result;
1963}
1964
1965/* factorial_odd_part: compute the odd part of factorial(n). */
1966
1967static PyObject *
1968factorial_odd_part(unsigned long n)
1969{
1970 long i;
1971 unsigned long v, lower, upper;
1972 PyObject *partial, *tmp, *inner, *outer;
1973
1974 inner = PyLong_FromLong(1);
1975 if (inner == NULL)
1976 return NULL;
1977 outer = inner;
1978 Py_INCREF(outer);
1979
1980 upper = 3;
Niklas Fiekasc5b79002020-01-16 15:09:19 +01001981 for (i = _Py_bit_length(n) - 2; i >= 0; i--) {
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001982 v = n >> i;
1983 if (v <= 2)
1984 continue;
1985 lower = upper;
1986 /* (v + 1) | 1 = least odd integer strictly larger than n / 2**i */
1987 upper = (v + 1) | 1;
1988 /* Here inner is the product of all odd integers j in the range (0,
1989 n/2**(i+1)]. The factorial_partial_product call below gives the
1990 product of all odd integers j in the range (n/2**(i+1), n/2**i]. */
Niklas Fiekasc5b79002020-01-16 15:09:19 +01001991 partial = factorial_partial_product(lower, upper, _Py_bit_length(upper-2));
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001992 /* inner *= partial */
1993 if (partial == NULL)
1994 goto error;
1995 tmp = PyNumber_Multiply(inner, partial);
1996 Py_DECREF(partial);
1997 if (tmp == NULL)
1998 goto error;
1999 Py_DECREF(inner);
2000 inner = tmp;
2001 /* Now inner is the product of all odd integers j in the range (0,
2002 n/2**i], giving the inner product in the formula above. */
2003
2004 /* outer *= inner; */
2005 tmp = PyNumber_Multiply(outer, inner);
2006 if (tmp == NULL)
2007 goto error;
2008 Py_DECREF(outer);
2009 outer = tmp;
2010 }
Mark Dickinson76464492012-10-25 10:46:28 +01002011 Py_DECREF(inner);
2012 return outer;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002013
2014 error:
2015 Py_DECREF(outer);
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002016 Py_DECREF(inner);
Mark Dickinson76464492012-10-25 10:46:28 +01002017 return NULL;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002018}
2019
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002020
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002021/* Lookup table for small factorial values */
2022
2023static const unsigned long SmallFactorials[] = {
2024 1, 1, 2, 6, 24, 120, 720, 5040, 40320,
2025 362880, 3628800, 39916800, 479001600,
2026#if SIZEOF_LONG >= 8
2027 6227020800, 87178291200, 1307674368000,
2028 20922789888000, 355687428096000, 6402373705728000,
2029 121645100408832000, 2432902008176640000
2030#endif
2031};
2032
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002033/*[clinic input]
2034math.factorial
2035
2036 x as arg: object
2037 /
2038
2039Find x!.
2040
2041Raise a ValueError if x is negative or non-integral.
2042[clinic start generated code]*/
2043
Barry Warsaw8b43b191996-12-09 22:32:36 +00002044static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002045math_factorial(PyObject *module, PyObject *arg)
2046/*[clinic end generated code: output=6686f26fae00e9ca input=6d1c8105c0d91fb4]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002047{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03002048 long x, two_valuation;
Mark Dickinson5990d282014-04-10 09:29:39 -04002049 int overflow;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03002050 PyObject *result, *odd_part, *pyint_form;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 if (PyFloat_Check(arg)) {
Serhiy Storchaka231aad32019-06-17 16:57:27 +03002053 if (PyErr_WarnEx(PyExc_DeprecationWarning,
2054 "Using factorial() with floats is deprecated",
2055 1) < 0)
2056 {
2057 return NULL;
2058 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 PyObject *lx;
2060 double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
2061 if (!(Py_IS_FINITE(dx) && dx == floor(dx))) {
2062 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002063 "factorial() only accepts integral values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 return NULL;
2065 }
2066 lx = PyLong_FromDouble(dx);
2067 if (lx == NULL)
2068 return NULL;
Mark Dickinson5990d282014-04-10 09:29:39 -04002069 x = PyLong_AsLongAndOverflow(lx, &overflow);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 Py_DECREF(lx);
2071 }
Pablo Galindoe9ba3702018-09-03 22:20:06 +01002072 else {
2073 pyint_form = PyNumber_Index(arg);
2074 if (pyint_form == NULL) {
2075 return NULL;
2076 }
2077 x = PyLong_AsLongAndOverflow(pyint_form, &overflow);
2078 Py_DECREF(pyint_form);
2079 }
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002080
Mark Dickinson5990d282014-04-10 09:29:39 -04002081 if (x == -1 && PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 return NULL;
Mark Dickinson5990d282014-04-10 09:29:39 -04002083 }
2084 else if (overflow == 1) {
2085 PyErr_Format(PyExc_OverflowError,
2086 "factorial() argument should not exceed %ld",
2087 LONG_MAX);
2088 return NULL;
2089 }
2090 else if (overflow == -1 || x < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002092 "factorial() not defined for negative values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 return NULL;
2094 }
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002095
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002096 /* use lookup table if x is small */
Victor Stinner63941882011-09-29 00:42:28 +02002097 if (x < (long)Py_ARRAY_LENGTH(SmallFactorials))
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002098 return PyLong_FromUnsignedLong(SmallFactorials[x]);
2099
2100 /* else express in the form odd_part * 2**two_valuation, and compute as
2101 odd_part << two_valuation. */
2102 odd_part = factorial_odd_part(x);
2103 if (odd_part == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03002105 two_valuation = x - count_set_bits(x);
2106 result = _PyLong_Lshift(odd_part, two_valuation);
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002107 Py_DECREF(odd_part);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 return result;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002109}
2110
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002111
2112/*[clinic input]
2113math.trunc
2114
2115 x: object
2116 /
2117
2118Truncates the Real x to the nearest Integral toward 0.
2119
2120Uses the __trunc__ magic method.
2121[clinic start generated code]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002122
2123static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002124math_trunc(PyObject *module, PyObject *x)
2125/*[clinic end generated code: output=34b9697b707e1031 input=2168b34e0a09134d]*/
Christian Heimes400adb02008-02-01 08:12:03 +00002126{
Benjamin Petersonce798522012-01-22 11:24:29 -05002127 _Py_IDENTIFIER(__trunc__);
Benjamin Petersonb0125892010-07-02 13:35:17 +00002128 PyObject *trunc, *result;
Christian Heimes400adb02008-02-01 08:12:03 +00002129
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02002130 if (PyFloat_CheckExact(x)) {
2131 return PyFloat_Type.tp_as_number->nb_int(x);
2132 }
2133
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002134 if (Py_TYPE(x)->tp_dict == NULL) {
2135 if (PyType_Ready(Py_TYPE(x)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 return NULL;
2137 }
Christian Heimes400adb02008-02-01 08:12:03 +00002138
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002139 trunc = _PyObject_LookupSpecial(x, &PyId___trunc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 if (trunc == NULL) {
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00002141 if (!PyErr_Occurred())
2142 PyErr_Format(PyExc_TypeError,
2143 "type %.100s doesn't define __trunc__ method",
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002144 Py_TYPE(x)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 return NULL;
2146 }
Victor Stinnerf17c3de2016-12-06 18:46:19 +01002147 result = _PyObject_CallNoArg(trunc);
Benjamin Petersonb0125892010-07-02 13:35:17 +00002148 Py_DECREF(trunc);
2149 return result;
Christian Heimes400adb02008-02-01 08:12:03 +00002150}
2151
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002152
2153/*[clinic input]
2154math.frexp
2155
2156 x: double
2157 /
2158
2159Return the mantissa and exponent of x, as pair (m, e).
2160
2161m is a float and e is an int, such that x = m * 2.**e.
2162If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.
2163[clinic start generated code]*/
Christian Heimes400adb02008-02-01 08:12:03 +00002164
2165static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002166math_frexp_impl(PyObject *module, double x)
2167/*[clinic end generated code: output=03e30d252a15ad4a input=96251c9e208bc6e9]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00002168{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 /* deal with special cases directly, to sidestep platform
2171 differences */
2172 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
2173 i = 0;
2174 }
2175 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 x = frexp(x, &i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 }
2178 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +00002179}
2180
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002181
2182/*[clinic input]
2183math.ldexp
2184
2185 x: double
2186 i: object
2187 /
2188
2189Return x * (2**i).
2190
2191This is essentially the inverse of frexp().
2192[clinic start generated code]*/
Guido van Rossumc6e22901998-12-04 19:26:43 +00002193
Barry Warsaw8b43b191996-12-09 22:32:36 +00002194static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002195math_ldexp_impl(PyObject *module, double x, PyObject *i)
2196/*[clinic end generated code: output=b6892f3c2df9cc6a input=17d5970c1a40a8c1]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00002197{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002198 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 long exp;
2200 int overflow;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00002201
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002202 if (PyLong_Check(i)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 /* on overflow, replace exponent with either LONG_MAX
2204 or LONG_MIN, depending on the sign. */
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002205 exp = PyLong_AsLongAndOverflow(i, &overflow);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 if (exp == -1 && PyErr_Occurred())
2207 return NULL;
2208 if (overflow)
2209 exp = overflow < 0 ? LONG_MIN : LONG_MAX;
2210 }
2211 else {
2212 PyErr_SetString(PyExc_TypeError,
Serhiy Storchaka95949422013-08-27 19:40:23 +03002213 "Expected an int as second argument to ldexp.");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 return NULL;
2215 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00002216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 if (x == 0. || !Py_IS_FINITE(x)) {
2218 /* NaNs, zeros and infinities are returned unchanged */
2219 r = x;
2220 errno = 0;
2221 } else if (exp > INT_MAX) {
2222 /* overflow */
2223 r = copysign(Py_HUGE_VAL, x);
2224 errno = ERANGE;
2225 } else if (exp < INT_MIN) {
2226 /* underflow to +-0 */
2227 r = copysign(0., x);
2228 errno = 0;
2229 } else {
2230 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 r = ldexp(x, (int)exp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 if (Py_IS_INFINITY(r))
2233 errno = ERANGE;
2234 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00002235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 if (errno && is_error(r))
2237 return NULL;
2238 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +00002239}
2240
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002241
2242/*[clinic input]
2243math.modf
2244
2245 x: double
2246 /
2247
2248Return the fractional and integer parts of x.
2249
2250Both results carry the sign of x and are floats.
2251[clinic start generated code]*/
Guido van Rossumc6e22901998-12-04 19:26:43 +00002252
Barry Warsaw8b43b191996-12-09 22:32:36 +00002253static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002254math_modf_impl(PyObject *module, double x)
2255/*[clinic end generated code: output=90cee0260014c3c0 input=b4cfb6786afd9035]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00002256{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002257 double y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 /* some platforms don't do the right thing for NaNs and
2259 infinities, so we take care of special cases directly. */
2260 if (!Py_IS_FINITE(x)) {
2261 if (Py_IS_INFINITY(x))
2262 return Py_BuildValue("(dd)", copysign(0., x), x);
2263 else if (Py_IS_NAN(x))
2264 return Py_BuildValue("(dd)", x, x);
2265 }
Christian Heimesa342c012008-04-20 21:01:16 +00002266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 x = modf(x, &y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +00002270}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002271
Guido van Rossumc6e22901998-12-04 19:26:43 +00002272
Serhiy Storchaka95949422013-08-27 19:40:23 +03002273/* A decent logarithm is easy to compute even for huge ints, but libm can't
Tim Peters78526162001-09-05 00:53:45 +00002274 do that by itself -- loghelper can. func is log or log10, and name is
Serhiy Storchaka95949422013-08-27 19:40:23 +03002275 "log" or "log10". Note that overflow of the result isn't possible: an int
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002276 can contain no more than INT_MAX * SHIFT bits, so has value certainly less
2277 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 +00002278 small enough to fit in an IEEE single. log and log10 are even smaller.
Serhiy Storchaka95949422013-08-27 19:40:23 +03002279 However, intermediate overflow is possible for an int if the number of bits
2280 in that int is larger than PY_SSIZE_T_MAX. */
Tim Peters78526162001-09-05 00:53:45 +00002281
2282static PyObject*
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002283loghelper(PyObject* arg, double (*func)(double), const char *funcname)
Tim Peters78526162001-09-05 00:53:45 +00002284{
Serhiy Storchaka95949422013-08-27 19:40:23 +03002285 /* If it is int, do it ourselves. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 if (PyLong_Check(arg)) {
Mark Dickinsonc6037172010-09-29 19:06:36 +00002287 double x, result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 Py_ssize_t e;
Mark Dickinsonc6037172010-09-29 19:06:36 +00002289
2290 /* Negative or zero inputs give a ValueError. */
2291 if (Py_SIZE(arg) <= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 PyErr_SetString(PyExc_ValueError,
2293 "math domain error");
2294 return NULL;
2295 }
Mark Dickinsonfa41e602010-09-28 07:22:27 +00002296
Mark Dickinsonc6037172010-09-29 19:06:36 +00002297 x = PyLong_AsDouble(arg);
2298 if (x == -1.0 && PyErr_Occurred()) {
2299 if (!PyErr_ExceptionMatches(PyExc_OverflowError))
2300 return NULL;
2301 /* Here the conversion to double overflowed, but it's possible
2302 to compute the log anyway. Clear the exception and continue. */
2303 PyErr_Clear();
2304 x = _PyLong_Frexp((PyLongObject *)arg, &e);
2305 if (x == -1.0 && PyErr_Occurred())
2306 return NULL;
2307 /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */
2308 result = func(x) + func(2.0) * e;
2309 }
2310 else
2311 /* Successfully converted x to a double. */
2312 result = func(x);
2313 return PyFloat_FromDouble(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 }
Tim Peters78526162001-09-05 00:53:45 +00002315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 /* Else let libm handle it by itself. */
2317 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +00002318}
2319
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002320
2321/*[clinic input]
2322math.log
2323
2324 x: object
2325 [
2326 base: object(c_default="NULL") = math.e
2327 ]
2328 /
2329
2330Return the logarithm of x to the given base.
2331
2332If the base not specified, returns the natural logarithm (base e) of x.
2333[clinic start generated code]*/
2334
Tim Peters78526162001-09-05 00:53:45 +00002335static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002336math_log_impl(PyObject *module, PyObject *x, int group_right_1,
2337 PyObject *base)
2338/*[clinic end generated code: output=7b5a39e526b73fc9 input=0f62d5726cbfebbd]*/
Tim Peters78526162001-09-05 00:53:45 +00002339{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 PyObject *num, *den;
2341 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +00002342
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002343 num = loghelper(x, m_log, "log");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 if (num == NULL || base == NULL)
2345 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +00002346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 den = loghelper(base, m_log, "log");
2348 if (den == NULL) {
2349 Py_DECREF(num);
2350 return NULL;
2351 }
Raymond Hettinger866964c2002-12-14 19:51:34 +00002352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 ans = PyNumber_TrueDivide(num, den);
2354 Py_DECREF(num);
2355 Py_DECREF(den);
2356 return ans;
Tim Peters78526162001-09-05 00:53:45 +00002357}
2358
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002359
2360/*[clinic input]
2361math.log2
2362
2363 x: object
2364 /
2365
2366Return the base 2 logarithm of x.
2367[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002368
2369static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002370math_log2(PyObject *module, PyObject *x)
2371/*[clinic end generated code: output=5425899a4d5d6acb input=08321262bae4f39b]*/
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02002372{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002373 return loghelper(x, m_log2, "log2");
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02002374}
2375
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002376
2377/*[clinic input]
2378math.log10
2379
2380 x: object
2381 /
2382
2383Return the base 10 logarithm of x.
2384[clinic start generated code]*/
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02002385
2386static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002387math_log10(PyObject *module, PyObject *x)
2388/*[clinic end generated code: output=be72a64617df9c6f input=b2469d02c6469e53]*/
Tim Peters78526162001-09-05 00:53:45 +00002389{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002390 return loghelper(x, m_log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +00002391}
2392
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002393
2394/*[clinic input]
2395math.fmod
2396
2397 x: double
2398 y: double
2399 /
2400
2401Return fmod(x, y), according to platform C.
2402
2403x % y may differ.
2404[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002405
Christian Heimes53876d92008-04-19 00:31:39 +00002406static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002407math_fmod_impl(PyObject *module, double x, double y)
2408/*[clinic end generated code: output=7559d794343a27b5 input=4f84caa8cfc26a03]*/
Christian Heimes53876d92008-04-19 00:31:39 +00002409{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002410 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 /* fmod(x, +/-Inf) returns x for finite x. */
2412 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
2413 return PyFloat_FromDouble(x);
2414 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 r = fmod(x, y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 if (Py_IS_NAN(r)) {
2417 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
2418 errno = EDOM;
2419 else
2420 errno = 0;
2421 }
2422 if (errno && is_error(r))
2423 return NULL;
2424 else
2425 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00002426}
2427
Raymond Hettinger13990742018-08-11 11:26:36 -07002428/*
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002429Given an *n* length *vec* of values and a value *max*, compute:
Raymond Hettinger13990742018-08-11 11:26:36 -07002430
Raymond Hettingerc630e102018-08-11 18:39:05 -07002431 max * sqrt(sum((x / max) ** 2 for x in vec))
Raymond Hettinger13990742018-08-11 11:26:36 -07002432
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002433The value of the *max* variable must be non-negative and
Raymond Hettinger216aaaa2018-11-09 01:06:02 -08002434equal to the absolute value of the largest magnitude
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002435entry in the vector. If n==0, then *max* should be 0.0.
2436If an infinity is present in the vec, *max* should be INF.
Raymond Hettingerc630e102018-08-11 18:39:05 -07002437
2438The *found_nan* variable indicates whether some member of
2439the *vec* is a NaN.
Raymond Hettinger21786f52018-08-28 22:47:24 -07002440
2441To improve accuracy and to increase the number of cases where
2442vector_norm() is commutative, we use a variant of Neumaier
2443summation specialized to exploit that we always know that
2444|csum| >= |x|.
2445
2446The *csum* variable tracks the cumulative sum and *frac* tracks
2447the cumulative fractional errors at each step. Since this
2448variant assumes that |csum| >= |x| at each step, we establish
2449the precondition by starting the accumulation from 1.0 which
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002450represents the largest possible value of (x/max)**2.
2451
2452After the loop is finished, the initial 1.0 is subtracted out
2453for a net zero effect on the final sum. Since *csum* will be
2454greater than 1.0, the subtraction of 1.0 will not cause
2455fractional digits to be dropped from *csum*.
Raymond Hettinger21786f52018-08-28 22:47:24 -07002456
Raymond Hettinger13990742018-08-11 11:26:36 -07002457*/
2458
2459static inline double
Raymond Hettingerc630e102018-08-11 18:39:05 -07002460vector_norm(Py_ssize_t n, double *vec, double max, int found_nan)
Raymond Hettinger13990742018-08-11 11:26:36 -07002461{
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002462 double x, csum = 1.0, oldcsum, frac = 0.0;
Raymond Hettinger13990742018-08-11 11:26:36 -07002463 Py_ssize_t i;
2464
Raymond Hettingerc630e102018-08-11 18:39:05 -07002465 if (Py_IS_INFINITY(max)) {
2466 return max;
2467 }
2468 if (found_nan) {
2469 return Py_NAN;
2470 }
Raymond Hettingerf3267142018-09-02 13:34:21 -07002471 if (max == 0.0 || n <= 1) {
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002472 return max;
Raymond Hettinger13990742018-08-11 11:26:36 -07002473 }
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002474 for (i=0 ; i < n ; i++) {
Raymond Hettinger13990742018-08-11 11:26:36 -07002475 x = vec[i];
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002476 assert(Py_IS_FINITE(x) && fabs(x) <= max);
Raymond Hettinger13990742018-08-11 11:26:36 -07002477 x /= max;
Raymond Hettinger21786f52018-08-28 22:47:24 -07002478 x = x*x;
Raymond Hettinger13990742018-08-11 11:26:36 -07002479 oldcsum = csum;
2480 csum += x;
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002481 assert(csum >= x);
Raymond Hettinger21786f52018-08-28 22:47:24 -07002482 frac += (oldcsum - csum) + x;
Raymond Hettinger13990742018-08-11 11:26:36 -07002483 }
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002484 return max * sqrt(csum - 1.0 + frac);
Raymond Hettinger13990742018-08-11 11:26:36 -07002485}
2486
Raymond Hettingerc630e102018-08-11 18:39:05 -07002487#define NUM_STACK_ELEMS 16
2488
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002489/*[clinic input]
2490math.dist
2491
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002492 p: object
2493 q: object
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002494 /
2495
2496Return the Euclidean distance between two points p and q.
2497
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002498The points should be specified as sequences (or iterables) of
2499coordinates. Both inputs must have the same dimension.
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002500
2501Roughly equivalent to:
2502 sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
2503[clinic start generated code]*/
2504
2505static PyObject *
2506math_dist_impl(PyObject *module, PyObject *p, PyObject *q)
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002507/*[clinic end generated code: output=56bd9538d06bbcfe input=74e85e1b6092e68e]*/
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002508{
2509 PyObject *item;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002510 double max = 0.0;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002511 double x, px, qx, result;
2512 Py_ssize_t i, m, n;
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002513 int found_nan = 0, p_allocated = 0, q_allocated = 0;
Raymond Hettingerc630e102018-08-11 18:39:05 -07002514 double diffs_on_stack[NUM_STACK_ELEMS];
2515 double *diffs = diffs_on_stack;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002516
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002517 if (!PyTuple_Check(p)) {
2518 p = PySequence_Tuple(p);
2519 if (p == NULL) {
2520 return NULL;
2521 }
2522 p_allocated = 1;
2523 }
2524 if (!PyTuple_Check(q)) {
2525 q = PySequence_Tuple(q);
2526 if (q == NULL) {
2527 if (p_allocated) {
2528 Py_DECREF(p);
2529 }
2530 return NULL;
2531 }
2532 q_allocated = 1;
2533 }
2534
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002535 m = PyTuple_GET_SIZE(p);
2536 n = PyTuple_GET_SIZE(q);
2537 if (m != n) {
2538 PyErr_SetString(PyExc_ValueError,
2539 "both points must have the same number of dimensions");
2540 return NULL;
2541
2542 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002543 if (n > NUM_STACK_ELEMS) {
2544 diffs = (double *) PyObject_Malloc(n * sizeof(double));
2545 if (diffs == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07002546 return PyErr_NoMemory();
Raymond Hettingerc630e102018-08-11 18:39:05 -07002547 }
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002548 }
2549 for (i=0 ; i<n ; i++) {
2550 item = PyTuple_GET_ITEM(p, i);
Raymond Hettingercfd735e2019-01-29 20:39:53 -08002551 ASSIGN_DOUBLE(px, item, error_exit);
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002552 item = PyTuple_GET_ITEM(q, i);
Raymond Hettingercfd735e2019-01-29 20:39:53 -08002553 ASSIGN_DOUBLE(qx, item, error_exit);
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002554 x = fabs(px - qx);
2555 diffs[i] = x;
2556 found_nan |= Py_IS_NAN(x);
2557 if (x > max) {
2558 max = x;
2559 }
2560 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002561 result = vector_norm(n, diffs, max, found_nan);
2562 if (diffs != diffs_on_stack) {
2563 PyObject_Free(diffs);
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002564 }
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002565 if (p_allocated) {
2566 Py_DECREF(p);
2567 }
2568 if (q_allocated) {
2569 Py_DECREF(q);
2570 }
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002571 return PyFloat_FromDouble(result);
Raymond Hettingerc630e102018-08-11 18:39:05 -07002572
2573 error_exit:
2574 if (diffs != diffs_on_stack) {
2575 PyObject_Free(diffs);
2576 }
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002577 if (p_allocated) {
2578 Py_DECREF(p);
2579 }
2580 if (q_allocated) {
2581 Py_DECREF(q);
2582 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002583 return NULL;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002584}
2585
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002586/* AC: cannot convert yet, waiting for *args support */
Christian Heimes53876d92008-04-19 00:31:39 +00002587static PyObject *
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002588math_hypot(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Christian Heimes53876d92008-04-19 00:31:39 +00002589{
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002590 Py_ssize_t i;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002591 PyObject *item;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002592 double max = 0.0;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002593 double x, result;
2594 int found_nan = 0;
Raymond Hettingerc630e102018-08-11 18:39:05 -07002595 double coord_on_stack[NUM_STACK_ELEMS];
2596 double *coordinates = coord_on_stack;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002597
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002598 if (nargs > NUM_STACK_ELEMS) {
2599 coordinates = (double *) PyObject_Malloc(nargs * sizeof(double));
Zackery Spytz4c49da02018-12-07 03:11:30 -07002600 if (coordinates == NULL) {
2601 return PyErr_NoMemory();
2602 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002603 }
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002604 for (i = 0; i < nargs; i++) {
2605 item = args[i];
Raymond Hettingercfd735e2019-01-29 20:39:53 -08002606 ASSIGN_DOUBLE(x, item, error_exit);
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002607 x = fabs(x);
2608 coordinates[i] = x;
2609 found_nan |= Py_IS_NAN(x);
2610 if (x > max) {
2611 max = x;
2612 }
2613 }
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002614 result = vector_norm(nargs, coordinates, max, found_nan);
Raymond Hettingerc630e102018-08-11 18:39:05 -07002615 if (coordinates != coord_on_stack) {
2616 PyObject_Free(coordinates);
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002617 }
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002618 return PyFloat_FromDouble(result);
Raymond Hettingerc630e102018-08-11 18:39:05 -07002619
2620 error_exit:
2621 if (coordinates != coord_on_stack) {
2622 PyObject_Free(coordinates);
2623 }
2624 return NULL;
Christian Heimes53876d92008-04-19 00:31:39 +00002625}
2626
Raymond Hettingerc630e102018-08-11 18:39:05 -07002627#undef NUM_STACK_ELEMS
2628
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002629PyDoc_STRVAR(math_hypot_doc,
2630 "hypot(*coordinates) -> value\n\n\
2631Multidimensional Euclidean distance from the origin to a point.\n\
2632\n\
2633Roughly equivalent to:\n\
2634 sqrt(sum(x**2 for x in coordinates))\n\
2635\n\
2636For a two dimensional point (x, y), gives the hypotenuse\n\
2637using the Pythagorean theorem: sqrt(x*x + y*y).\n\
2638\n\
2639For example, the hypotenuse of a 3/4/5 right triangle is:\n\
2640\n\
2641 >>> hypot(3.0, 4.0)\n\
2642 5.0\n\
2643");
Christian Heimes53876d92008-04-19 00:31:39 +00002644
2645/* pow can't use math_2, but needs its own wrapper: the problem is
2646 that an infinite result can arise either as a result of overflow
2647 (in which case OverflowError should be raised) or as a result of
2648 e.g. 0.**-5. (for which ValueError needs to be raised.)
2649*/
2650
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002651/*[clinic input]
2652math.pow
Christian Heimes53876d92008-04-19 00:31:39 +00002653
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002654 x: double
2655 y: double
2656 /
2657
2658Return x**y (x to the power of y).
2659[clinic start generated code]*/
2660
2661static PyObject *
2662math_pow_impl(PyObject *module, double x, double y)
2663/*[clinic end generated code: output=fff93e65abccd6b0 input=c26f1f6075088bfd]*/
2664{
2665 double r;
2666 int odd_y;
Christian Heimesa342c012008-04-20 21:01:16 +00002667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668 /* deal directly with IEEE specials, to cope with problems on various
2669 platforms whose semantics don't exactly match C99 */
2670 r = 0.; /* silence compiler warning */
2671 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
2672 errno = 0;
2673 if (Py_IS_NAN(x))
2674 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
2675 else if (Py_IS_NAN(y))
2676 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
2677 else if (Py_IS_INFINITY(x)) {
2678 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
2679 if (y > 0.)
2680 r = odd_y ? x : fabs(x);
2681 else if (y == 0.)
2682 r = 1.;
2683 else /* y < 0. */
2684 r = odd_y ? copysign(0., x) : 0.;
2685 }
2686 else if (Py_IS_INFINITY(y)) {
2687 if (fabs(x) == 1.0)
2688 r = 1.;
2689 else if (y > 0. && fabs(x) > 1.0)
2690 r = y;
2691 else if (y < 0. && fabs(x) < 1.0) {
2692 r = -y; /* result is +inf */
2693 if (x == 0.) /* 0**-inf: divide-by-zero */
2694 errno = EDOM;
2695 }
2696 else
2697 r = 0.;
2698 }
2699 }
2700 else {
2701 /* let libm handle finite**finite */
2702 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 r = pow(x, y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 /* a NaN result should arise only from (-ve)**(finite
2705 non-integer); in this case we want to raise ValueError. */
2706 if (!Py_IS_FINITE(r)) {
2707 if (Py_IS_NAN(r)) {
2708 errno = EDOM;
2709 }
2710 /*
2711 an infinite result here arises either from:
2712 (A) (+/-0.)**negative (-> divide-by-zero)
2713 (B) overflow of x**y with x and y finite
2714 */
2715 else if (Py_IS_INFINITY(r)) {
2716 if (x == 0.)
2717 errno = EDOM;
2718 else
2719 errno = ERANGE;
2720 }
2721 }
2722 }
Christian Heimes53876d92008-04-19 00:31:39 +00002723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002724 if (errno && is_error(r))
2725 return NULL;
2726 else
2727 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00002728}
2729
Christian Heimes53876d92008-04-19 00:31:39 +00002730
Christian Heimes072c0f12008-01-03 23:01:04 +00002731static const double degToRad = Py_MATH_PI / 180.0;
2732static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002733
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002734/*[clinic input]
2735math.degrees
2736
2737 x: double
2738 /
2739
2740Convert angle x from radians to degrees.
2741[clinic start generated code]*/
2742
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002743static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002744math_degrees_impl(PyObject *module, double x)
2745/*[clinic end generated code: output=7fea78b294acd12f input=81e016555d6e3660]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002746{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002747 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002748}
2749
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002750
2751/*[clinic input]
2752math.radians
2753
2754 x: double
2755 /
2756
2757Convert angle x from degrees to radians.
2758[clinic start generated code]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002759
2760static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002761math_radians_impl(PyObject *module, double x)
2762/*[clinic end generated code: output=34daa47caf9b1590 input=91626fc489fe3d63]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002763{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002764 return PyFloat_FromDouble(x * degToRad);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002765}
2766
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002767
2768/*[clinic input]
2769math.isfinite
2770
2771 x: double
2772 /
2773
2774Return True if x is neither an infinity nor a NaN, and False otherwise.
2775[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002776
Christian Heimes072c0f12008-01-03 23:01:04 +00002777static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002778math_isfinite_impl(PyObject *module, double x)
2779/*[clinic end generated code: output=8ba1f396440c9901 input=46967d254812e54a]*/
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002780{
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002781 return PyBool_FromLong((long)Py_IS_FINITE(x));
2782}
2783
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002784
2785/*[clinic input]
2786math.isnan
2787
2788 x: double
2789 /
2790
2791Return True if x is a NaN (not a number), and False otherwise.
2792[clinic start generated code]*/
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002793
2794static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002795math_isnan_impl(PyObject *module, double x)
2796/*[clinic end generated code: output=f537b4d6df878c3e input=935891e66083f46a]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002797{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002798 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00002799}
2800
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002801
2802/*[clinic input]
2803math.isinf
2804
2805 x: double
2806 /
2807
2808Return True if x is a positive or negative infinity, and False otherwise.
2809[clinic start generated code]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002810
2811static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002812math_isinf_impl(PyObject *module, double x)
2813/*[clinic end generated code: output=9f00cbec4de7b06b input=32630e4212cf961f]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002814{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002815 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00002816}
2817
Christian Heimes072c0f12008-01-03 23:01:04 +00002818
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002819/*[clinic input]
2820math.isclose -> bool
2821
2822 a: double
2823 b: double
2824 *
2825 rel_tol: double = 1e-09
2826 maximum difference for being considered "close", relative to the
2827 magnitude of the input values
2828 abs_tol: double = 0.0
2829 maximum difference for being considered "close", regardless of the
2830 magnitude of the input values
2831
2832Determine whether two floating point numbers are close in value.
2833
2834Return True if a is close in value to b, and False otherwise.
2835
2836For the values to be considered close, the difference between them
2837must be smaller than at least one of the tolerances.
2838
2839-inf, inf and NaN behave similarly to the IEEE 754 Standard. That
2840is, NaN is not close to anything, even itself. inf and -inf are
2841only close to themselves.
2842[clinic start generated code]*/
2843
2844static int
2845math_isclose_impl(PyObject *module, double a, double b, double rel_tol,
2846 double abs_tol)
2847/*[clinic end generated code: output=b73070207511952d input=f28671871ea5bfba]*/
Tal Einatd5519ed2015-05-31 22:05:00 +03002848{
Tal Einatd5519ed2015-05-31 22:05:00 +03002849 double diff = 0.0;
Tal Einatd5519ed2015-05-31 22:05:00 +03002850
2851 /* sanity check on the inputs */
2852 if (rel_tol < 0.0 || abs_tol < 0.0 ) {
2853 PyErr_SetString(PyExc_ValueError,
2854 "tolerances must be non-negative");
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002855 return -1;
Tal Einatd5519ed2015-05-31 22:05:00 +03002856 }
2857
2858 if ( a == b ) {
2859 /* short circuit exact equality -- needed to catch two infinities of
2860 the same sign. And perhaps speeds things up a bit sometimes.
2861 */
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002862 return 1;
Tal Einatd5519ed2015-05-31 22:05:00 +03002863 }
2864
2865 /* This catches the case of two infinities of opposite sign, or
2866 one infinity and one finite number. Two infinities of opposite
2867 sign would otherwise have an infinite relative tolerance.
2868 Two infinities of the same sign are caught by the equality check
2869 above.
2870 */
2871
2872 if (Py_IS_INFINITY(a) || Py_IS_INFINITY(b)) {
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002873 return 0;
Tal Einatd5519ed2015-05-31 22:05:00 +03002874 }
2875
2876 /* now do the regular computation
2877 this is essentially the "weak" test from the Boost library
2878 */
2879
2880 diff = fabs(b - a);
2881
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002882 return (((diff <= fabs(rel_tol * b)) ||
2883 (diff <= fabs(rel_tol * a))) ||
2884 (diff <= abs_tol));
Tal Einatd5519ed2015-05-31 22:05:00 +03002885}
2886
Pablo Galindo04114112019-03-09 19:18:08 +00002887static inline int
2888_check_long_mult_overflow(long a, long b) {
2889
2890 /* From Python2's int_mul code:
2891
2892 Integer overflow checking for * is painful: Python tried a couple ways, but
2893 they didn't work on all platforms, or failed in endcases (a product of
2894 -sys.maxint-1 has been a particular pain).
2895
2896 Here's another way:
2897
2898 The native long product x*y is either exactly right or *way* off, being
2899 just the last n bits of the true product, where n is the number of bits
2900 in a long (the delivered product is the true product plus i*2**n for
2901 some integer i).
2902
2903 The native double product (double)x * (double)y is subject to three
2904 rounding errors: on a sizeof(long)==8 box, each cast to double can lose
2905 info, and even on a sizeof(long)==4 box, the multiplication can lose info.
2906 But, unlike the native long product, it's not in *range* trouble: even
2907 if sizeof(long)==32 (256-bit longs), the product easily fits in the
2908 dynamic range of a double. So the leading 50 (or so) bits of the double
2909 product are correct.
2910
2911 We check these two ways against each other, and declare victory if they're
2912 approximately the same. Else, because the native long product is the only
2913 one that can lose catastrophic amounts of information, it's the native long
2914 product that must have overflowed.
2915
2916 */
2917
2918 long longprod = (long)((unsigned long)a * b);
2919 double doubleprod = (double)a * (double)b;
2920 double doubled_longprod = (double)longprod;
2921
2922 if (doubled_longprod == doubleprod) {
2923 return 0;
2924 }
2925
2926 const double diff = doubled_longprod - doubleprod;
2927 const double absdiff = diff >= 0.0 ? diff : -diff;
2928 const double absprod = doubleprod >= 0.0 ? doubleprod : -doubleprod;
2929
2930 if (32.0 * absdiff <= absprod) {
2931 return 0;
2932 }
2933
2934 return 1;
2935}
Tal Einatd5519ed2015-05-31 22:05:00 +03002936
Pablo Galindobc098512019-02-07 07:04:02 +00002937/*[clinic input]
2938math.prod
2939
2940 iterable: object
2941 /
2942 *
2943 start: object(c_default="NULL") = 1
2944
2945Calculate the product of all the elements in the input iterable.
2946
2947The default start value for the product is 1.
2948
2949When the iterable is empty, return the start value. This function is
2950intended specifically for use with numeric values and may reject
2951non-numeric types.
2952[clinic start generated code]*/
2953
2954static PyObject *
2955math_prod_impl(PyObject *module, PyObject *iterable, PyObject *start)
2956/*[clinic end generated code: output=36153bedac74a198 input=4c5ab0682782ed54]*/
2957{
2958 PyObject *result = start;
2959 PyObject *temp, *item, *iter;
2960
2961 iter = PyObject_GetIter(iterable);
2962 if (iter == NULL) {
2963 return NULL;
2964 }
2965
2966 if (result == NULL) {
2967 result = PyLong_FromLong(1);
2968 if (result == NULL) {
2969 Py_DECREF(iter);
2970 return NULL;
2971 }
2972 } else {
2973 Py_INCREF(result);
2974 }
2975#ifndef SLOW_PROD
2976 /* Fast paths for integers keeping temporary products in C.
2977 * Assumes all inputs are the same type.
2978 * If the assumption fails, default to use PyObjects instead.
2979 */
2980 if (PyLong_CheckExact(result)) {
2981 int overflow;
2982 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2983 /* If this already overflowed, don't even enter the loop. */
2984 if (overflow == 0) {
2985 Py_DECREF(result);
2986 result = NULL;
2987 }
2988 /* Loop over all the items in the iterable until we finish, we overflow
2989 * or we found a non integer element */
2990 while(result == NULL) {
2991 item = PyIter_Next(iter);
2992 if (item == NULL) {
2993 Py_DECREF(iter);
2994 if (PyErr_Occurred()) {
2995 return NULL;
2996 }
2997 return PyLong_FromLong(i_result);
2998 }
2999 if (PyLong_CheckExact(item)) {
3000 long b = PyLong_AsLongAndOverflow(item, &overflow);
Pablo Galindo04114112019-03-09 19:18:08 +00003001 if (overflow == 0 && !_check_long_mult_overflow(i_result, b)) {
3002 long x = i_result * b;
Pablo Galindobc098512019-02-07 07:04:02 +00003003 i_result = x;
3004 Py_DECREF(item);
3005 continue;
3006 }
3007 }
3008 /* Either overflowed or is not an int.
3009 * Restore real objects and process normally */
3010 result = PyLong_FromLong(i_result);
3011 if (result == NULL) {
3012 Py_DECREF(item);
3013 Py_DECREF(iter);
3014 return NULL;
3015 }
3016 temp = PyNumber_Multiply(result, item);
3017 Py_DECREF(result);
3018 Py_DECREF(item);
3019 result = temp;
3020 if (result == NULL) {
3021 Py_DECREF(iter);
3022 return NULL;
3023 }
3024 }
3025 }
3026
3027 /* Fast paths for floats keeping temporary products in C.
3028 * Assumes all inputs are the same type.
3029 * If the assumption fails, default to use PyObjects instead.
3030 */
3031 if (PyFloat_CheckExact(result)) {
3032 double f_result = PyFloat_AS_DOUBLE(result);
3033 Py_DECREF(result);
3034 result = NULL;
3035 while(result == NULL) {
3036 item = PyIter_Next(iter);
3037 if (item == NULL) {
3038 Py_DECREF(iter);
3039 if (PyErr_Occurred()) {
3040 return NULL;
3041 }
3042 return PyFloat_FromDouble(f_result);
3043 }
3044 if (PyFloat_CheckExact(item)) {
3045 f_result *= PyFloat_AS_DOUBLE(item);
3046 Py_DECREF(item);
3047 continue;
3048 }
3049 if (PyLong_CheckExact(item)) {
3050 long value;
3051 int overflow;
3052 value = PyLong_AsLongAndOverflow(item, &overflow);
3053 if (!overflow) {
3054 f_result *= (double)value;
3055 Py_DECREF(item);
3056 continue;
3057 }
3058 }
3059 result = PyFloat_FromDouble(f_result);
3060 if (result == NULL) {
3061 Py_DECREF(item);
3062 Py_DECREF(iter);
3063 return NULL;
3064 }
3065 temp = PyNumber_Multiply(result, item);
3066 Py_DECREF(result);
3067 Py_DECREF(item);
3068 result = temp;
3069 if (result == NULL) {
3070 Py_DECREF(iter);
3071 return NULL;
3072 }
3073 }
3074 }
3075#endif
3076 /* Consume rest of the iterable (if any) that could not be handled
3077 * by specialized functions above.*/
3078 for(;;) {
3079 item = PyIter_Next(iter);
3080 if (item == NULL) {
3081 /* error, or end-of-sequence */
3082 if (PyErr_Occurred()) {
3083 Py_DECREF(result);
3084 result = NULL;
3085 }
3086 break;
3087 }
3088 temp = PyNumber_Multiply(result, item);
3089 Py_DECREF(result);
3090 Py_DECREF(item);
3091 result = temp;
3092 if (result == NULL)
3093 break;
3094 }
3095 Py_DECREF(iter);
3096 return result;
3097}
3098
3099
Yash Aggarwal4a686502019-06-01 12:51:27 +05303100/*[clinic input]
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003101math.perm
3102
3103 n: object
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003104 k: object = None
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003105 /
3106
3107Number of ways to choose k items from n items without repetition and with order.
3108
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003109Evaluates to n! / (n - k)! when k <= n and evaluates
3110to zero when k > n.
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003111
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003112If k is not specified or is None, then k defaults to n
3113and the function returns n!.
3114
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003115Raises TypeError if either of the arguments are not integers.
3116Raises ValueError if either of the arguments are negative.
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003117[clinic start generated code]*/
3118
3119static PyObject *
3120math_perm_impl(PyObject *module, PyObject *n, PyObject *k)
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003121/*[clinic end generated code: output=e021a25469653e23 input=5311c5a00f359b53]*/
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003122{
3123 PyObject *result = NULL, *factor = NULL;
3124 int overflow, cmp;
3125 long long i, factors;
3126
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003127 if (k == Py_None) {
3128 return math_factorial(module, n);
3129 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003130 n = PyNumber_Index(n);
3131 if (n == NULL) {
3132 return NULL;
3133 }
3134 if (!PyLong_CheckExact(n)) {
3135 Py_SETREF(n, _PyLong_Copy((PyLongObject *)n));
3136 if (n == NULL) {
3137 return NULL;
3138 }
3139 }
3140 k = PyNumber_Index(k);
3141 if (k == NULL) {
3142 Py_DECREF(n);
3143 return NULL;
3144 }
3145 if (!PyLong_CheckExact(k)) {
3146 Py_SETREF(k, _PyLong_Copy((PyLongObject *)k));
3147 if (k == NULL) {
3148 Py_DECREF(n);
3149 return NULL;
3150 }
3151 }
3152
3153 if (Py_SIZE(n) < 0) {
3154 PyErr_SetString(PyExc_ValueError,
3155 "n must be a non-negative integer");
3156 goto error;
3157 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003158 if (Py_SIZE(k) < 0) {
3159 PyErr_SetString(PyExc_ValueError,
3160 "k must be a non-negative integer");
3161 goto error;
3162 }
3163
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003164 cmp = PyObject_RichCompareBool(n, k, Py_LT);
3165 if (cmp != 0) {
3166 if (cmp > 0) {
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003167 result = PyLong_FromLong(0);
3168 goto done;
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003169 }
3170 goto error;
3171 }
3172
3173 factors = PyLong_AsLongLongAndOverflow(k, &overflow);
3174 if (overflow > 0) {
3175 PyErr_Format(PyExc_OverflowError,
3176 "k must not exceed %lld",
3177 LLONG_MAX);
3178 goto error;
3179 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003180 else if (factors == -1) {
3181 /* k is nonnegative, so a return value of -1 can only indicate error */
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003182 goto error;
3183 }
3184
3185 if (factors == 0) {
3186 result = PyLong_FromLong(1);
3187 goto done;
3188 }
3189
3190 result = n;
3191 Py_INCREF(result);
3192 if (factors == 1) {
3193 goto done;
3194 }
3195
3196 factor = n;
3197 Py_INCREF(factor);
3198 for (i = 1; i < factors; ++i) {
3199 Py_SETREF(factor, PyNumber_Subtract(factor, _PyLong_One));
3200 if (factor == NULL) {
3201 goto error;
3202 }
3203 Py_SETREF(result, PyNumber_Multiply(result, factor));
3204 if (result == NULL) {
3205 goto error;
3206 }
3207 }
3208 Py_DECREF(factor);
3209
3210done:
3211 Py_DECREF(n);
3212 Py_DECREF(k);
3213 return result;
3214
3215error:
3216 Py_XDECREF(factor);
3217 Py_XDECREF(result);
3218 Py_DECREF(n);
3219 Py_DECREF(k);
3220 return NULL;
3221}
3222
3223
3224/*[clinic input]
Yash Aggarwal4a686502019-06-01 12:51:27 +05303225math.comb
3226
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003227 n: object
3228 k: object
3229 /
Yash Aggarwal4a686502019-06-01 12:51:27 +05303230
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003231Number of ways to choose k items from n items without repetition and without order.
Yash Aggarwal4a686502019-06-01 12:51:27 +05303232
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003233Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates
3234to zero when k > n.
Yash Aggarwal4a686502019-06-01 12:51:27 +05303235
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003236Also called the binomial coefficient because it is equivalent
3237to the coefficient of k-th term in polynomial expansion of the
3238expression (1 + x)**n.
3239
3240Raises TypeError if either of the arguments are not integers.
3241Raises ValueError if either of the arguments are negative.
Yash Aggarwal4a686502019-06-01 12:51:27 +05303242
3243[clinic start generated code]*/
3244
3245static PyObject *
3246math_comb_impl(PyObject *module, PyObject *n, PyObject *k)
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003247/*[clinic end generated code: output=bd2cec8d854f3493 input=9a05315af2518709]*/
Yash Aggarwal4a686502019-06-01 12:51:27 +05303248{
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003249 PyObject *result = NULL, *factor = NULL, *temp;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303250 int overflow, cmp;
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003251 long long i, factors;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303252
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003253 n = PyNumber_Index(n);
3254 if (n == NULL) {
3255 return NULL;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303256 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003257 if (!PyLong_CheckExact(n)) {
3258 Py_SETREF(n, _PyLong_Copy((PyLongObject *)n));
3259 if (n == NULL) {
3260 return NULL;
3261 }
3262 }
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003263 k = PyNumber_Index(k);
3264 if (k == NULL) {
3265 Py_DECREF(n);
3266 return NULL;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303267 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003268 if (!PyLong_CheckExact(k)) {
3269 Py_SETREF(k, _PyLong_Copy((PyLongObject *)k));
3270 if (k == NULL) {
3271 Py_DECREF(n);
3272 return NULL;
3273 }
3274 }
Yash Aggarwal4a686502019-06-01 12:51:27 +05303275
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003276 if (Py_SIZE(n) < 0) {
3277 PyErr_SetString(PyExc_ValueError,
3278 "n must be a non-negative integer");
3279 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303280 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003281 if (Py_SIZE(k) < 0) {
3282 PyErr_SetString(PyExc_ValueError,
3283 "k must be a non-negative integer");
3284 goto error;
3285 }
3286
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003287 /* k = min(k, n - k) */
3288 temp = PyNumber_Subtract(n, k);
3289 if (temp == NULL) {
3290 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303291 }
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003292 if (Py_SIZE(temp) < 0) {
3293 Py_DECREF(temp);
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003294 result = PyLong_FromLong(0);
3295 goto done;
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003296 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003297 cmp = PyObject_RichCompareBool(temp, k, Py_LT);
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003298 if (cmp > 0) {
3299 Py_SETREF(k, temp);
Yash Aggarwal4a686502019-06-01 12:51:27 +05303300 }
3301 else {
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003302 Py_DECREF(temp);
3303 if (cmp < 0) {
3304 goto error;
3305 }
Yash Aggarwal4a686502019-06-01 12:51:27 +05303306 }
3307
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003308 factors = PyLong_AsLongLongAndOverflow(k, &overflow);
3309 if (overflow > 0) {
Yash Aggarwal4a686502019-06-01 12:51:27 +05303310 PyErr_Format(PyExc_OverflowError,
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003311 "min(n - k, k) must not exceed %lld",
Yash Aggarwal4a686502019-06-01 12:51:27 +05303312 LLONG_MAX);
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003313 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303314 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003315 if (factors == -1) {
3316 /* k is nonnegative, so a return value of -1 can only indicate error */
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003317 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303318 }
3319
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003320 if (factors == 0) {
3321 result = PyLong_FromLong(1);
3322 goto done;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303323 }
3324
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003325 result = n;
3326 Py_INCREF(result);
3327 if (factors == 1) {
3328 goto done;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303329 }
3330
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003331 factor = n;
3332 Py_INCREF(factor);
3333 for (i = 1; i < factors; ++i) {
3334 Py_SETREF(factor, PyNumber_Subtract(factor, _PyLong_One));
3335 if (factor == NULL) {
3336 goto error;
3337 }
3338 Py_SETREF(result, PyNumber_Multiply(result, factor));
3339 if (result == NULL) {
3340 goto error;
3341 }
Yash Aggarwal4a686502019-06-01 12:51:27 +05303342
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003343 temp = PyLong_FromUnsignedLongLong((unsigned long long)i + 1);
3344 if (temp == NULL) {
3345 goto error;
3346 }
3347 Py_SETREF(result, PyNumber_FloorDivide(result, temp));
3348 Py_DECREF(temp);
3349 if (result == NULL) {
3350 goto error;
3351 }
3352 }
3353 Py_DECREF(factor);
Yash Aggarwal4a686502019-06-01 12:51:27 +05303354
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003355done:
3356 Py_DECREF(n);
3357 Py_DECREF(k);
3358 return result;
3359
3360error:
3361 Py_XDECREF(factor);
3362 Py_XDECREF(result);
3363 Py_DECREF(n);
3364 Py_DECREF(k);
Yash Aggarwal4a686502019-06-01 12:51:27 +05303365 return NULL;
3366}
3367
3368
Victor Stinner100fafc2020-01-12 02:15:42 +01003369/*[clinic input]
3370math.nextafter
3371
3372 x: double
3373 y: double
3374 /
3375
3376Return the next floating-point value after x towards y.
3377[clinic start generated code]*/
3378
3379static PyObject *
3380math_nextafter_impl(PyObject *module, double x, double y)
3381/*[clinic end generated code: output=750c8266c1c540ce input=02b2d50cd1d9f9b6]*/
3382{
Victor Stinner85ead4f2020-01-21 11:14:10 +01003383#if defined(_AIX)
3384 if (x == y) {
3385 /* On AIX 7.1, libm nextafter(-0.0, +0.0) returns -0.0.
3386 Bug fixed in bos.adt.libm 7.2.2.0 by APAR IV95512. */
3387 return PyFloat_FromDouble(y);
3388 }
3389#endif
3390 return PyFloat_FromDouble(nextafter(x, y));
Victor Stinner100fafc2020-01-12 02:15:42 +01003391}
3392
3393
Victor Stinner0b2ab212020-01-13 12:44:35 +01003394/*[clinic input]
3395math.ulp -> double
3396
3397 x: double
3398 /
3399
3400Return the value of the least significant bit of the float x.
3401[clinic start generated code]*/
3402
3403static double
3404math_ulp_impl(PyObject *module, double x)
3405/*[clinic end generated code: output=f5207867a9384dd4 input=31f9bfbbe373fcaa]*/
3406{
3407 if (Py_IS_NAN(x)) {
3408 return x;
3409 }
3410 x = fabs(x);
3411 if (Py_IS_INFINITY(x)) {
3412 return x;
3413 }
3414 double inf = m_inf();
3415 double x2 = nextafter(x, inf);
3416 if (Py_IS_INFINITY(x2)) {
3417 /* special case: x is the largest positive representable float */
3418 x2 = nextafter(x, -inf);
3419 return x - x2;
3420 }
3421 return x2 - x;
3422}
3423
3424
Barry Warsaw8b43b191996-12-09 22:32:36 +00003425static PyMethodDef math_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003426 {"acos", math_acos, METH_O, math_acos_doc},
3427 {"acosh", math_acosh, METH_O, math_acosh_doc},
3428 {"asin", math_asin, METH_O, math_asin_doc},
3429 {"asinh", math_asinh, METH_O, math_asinh_doc},
3430 {"atan", math_atan, METH_O, math_atan_doc},
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003431 {"atan2", (PyCFunction)(void(*)(void))math_atan2, METH_FASTCALL, math_atan2_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003432 {"atanh", math_atanh, METH_O, math_atanh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003433 MATH_CEIL_METHODDEF
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003434 {"copysign", (PyCFunction)(void(*)(void))math_copysign, METH_FASTCALL, math_copysign_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003435 {"cos", math_cos, METH_O, math_cos_doc},
3436 {"cosh", math_cosh, METH_O, math_cosh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003437 MATH_DEGREES_METHODDEF
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07003438 MATH_DIST_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003439 {"erf", math_erf, METH_O, math_erf_doc},
3440 {"erfc", math_erfc, METH_O, math_erfc_doc},
3441 {"exp", math_exp, METH_O, math_exp_doc},
3442 {"expm1", math_expm1, METH_O, math_expm1_doc},
3443 {"fabs", math_fabs, METH_O, math_fabs_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003444 MATH_FACTORIAL_METHODDEF
3445 MATH_FLOOR_METHODDEF
3446 MATH_FMOD_METHODDEF
3447 MATH_FREXP_METHODDEF
3448 MATH_FSUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003449 {"gamma", math_gamma, METH_O, math_gamma_doc},
Serhiy Storchaka559e7f12020-02-23 13:21:29 +02003450 {"gcd", (PyCFunction)(void(*)(void))math_gcd, METH_FASTCALL, math_gcd_doc},
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003451 {"hypot", (PyCFunction)(void(*)(void))math_hypot, METH_FASTCALL, math_hypot_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003452 MATH_ISCLOSE_METHODDEF
3453 MATH_ISFINITE_METHODDEF
3454 MATH_ISINF_METHODDEF
3455 MATH_ISNAN_METHODDEF
Mark Dickinson73934b92019-05-18 12:29:50 +01003456 MATH_ISQRT_METHODDEF
Serhiy Storchaka559e7f12020-02-23 13:21:29 +02003457 {"lcm", (PyCFunction)(void(*)(void))math_lcm, METH_FASTCALL, math_lcm_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003458 MATH_LDEXP_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003459 {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003460 MATH_LOG_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003461 {"log1p", math_log1p, METH_O, math_log1p_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003462 MATH_LOG10_METHODDEF
3463 MATH_LOG2_METHODDEF
3464 MATH_MODF_METHODDEF
3465 MATH_POW_METHODDEF
3466 MATH_RADIANS_METHODDEF
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003467 {"remainder", (PyCFunction)(void(*)(void))math_remainder, METH_FASTCALL, math_remainder_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003468 {"sin", math_sin, METH_O, math_sin_doc},
3469 {"sinh", math_sinh, METH_O, math_sinh_doc},
3470 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
3471 {"tan", math_tan, METH_O, math_tan_doc},
3472 {"tanh", math_tanh, METH_O, math_tanh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003473 MATH_TRUNC_METHODDEF
Pablo Galindobc098512019-02-07 07:04:02 +00003474 MATH_PROD_METHODDEF
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003475 MATH_PERM_METHODDEF
Yash Aggarwal4a686502019-06-01 12:51:27 +05303476 MATH_COMB_METHODDEF
Victor Stinner100fafc2020-01-12 02:15:42 +01003477 MATH_NEXTAFTER_METHODDEF
Victor Stinner0b2ab212020-01-13 12:44:35 +01003478 MATH_ULP_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003479 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003480};
3481
Guido van Rossumc6e22901998-12-04 19:26:43 +00003482
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003483PyDoc_STRVAR(module_doc,
Ned Batchelder6faad352019-05-17 05:59:14 -04003484"This module provides access to the mathematical functions\n"
3485"defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00003486
Martin v. Löwis1a214512008-06-11 05:26:20 +00003487
3488static struct PyModuleDef mathmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003489 PyModuleDef_HEAD_INIT,
3490 "math",
3491 module_doc,
3492 -1,
3493 math_methods,
3494 NULL,
3495 NULL,
3496 NULL,
3497 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003498};
3499
Mark Hammondfe51c6d2002-08-02 02:27:13 +00003500PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003501PyInit_math(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003503 PyObject *m;
Tim Petersfe71f812001-08-07 22:10:00 +00003504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003505 m = PyModule_Create(&mathmodule);
3506 if (m == NULL)
3507 goto finally;
Barry Warsawfc93f751996-12-17 00:47:03 +00003508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003509 PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
3510 PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
Guido van Rossum0a891d72016-08-15 09:12:52 -07003511 PyModule_AddObject(m, "tau", PyFloat_FromDouble(Py_MATH_TAU)); /* 2pi */
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +00003512 PyModule_AddObject(m, "inf", PyFloat_FromDouble(m_inf()));
3513#if !defined(PY_NO_SHORT_FLOAT_REPR) || defined(Py_NAN)
3514 PyModule_AddObject(m, "nan", PyFloat_FromDouble(m_nan()));
3515#endif
Barry Warsawfc93f751996-12-17 00:47:03 +00003516
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +00003517 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003518 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003519}