blob: 4aa7e6559af557e754bb0e8321549a38092a292f [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{
Miss Islington (bot)242eac12020-09-04 16:12:48 -07001258 double x;
1259
Benjamin Petersonce798522012-01-22 11:24:29 -05001260 _Py_IDENTIFIER(__floor__);
Guido van Rossum13e05de2007-08-23 22:56:55 +00001261
Miss Islington (bot)242eac12020-09-04 16:12:48 -07001262 if (PyFloat_CheckExact(number)) {
1263 x = PyFloat_AS_DOUBLE(number);
1264 }
1265 else
1266 {
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001267 PyObject *method = _PyObject_LookupSpecial(number, &PyId___floor__);
1268 if (method != NULL) {
1269 PyObject *result = _PyObject_CallNoArg(method);
1270 Py_DECREF(method);
1271 return result;
1272 }
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001273 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 return NULL;
Miss Islington (bot)242eac12020-09-04 16:12:48 -07001275 x = PyFloat_AsDouble(number);
1276 if (x == -1.0 && PyErr_Occurred())
1277 return NULL;
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001278 }
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001279 return PyLong_FromDouble(floor(x));
Guido van Rossum13e05de2007-08-23 22:56:55 +00001280}
1281
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001282FUNC1A(gamma, m_tgamma,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001283 "gamma($module, x, /)\n--\n\n"
1284 "Gamma function at x.")
Mark Dickinson05d2e082009-12-11 20:17:17 +00001285FUNC1A(lgamma, m_lgamma,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001286 "lgamma($module, x, /)\n--\n\n"
1287 "Natural logarithm of absolute value of Gamma function at x.")
Mark Dickinsonbe64d952010-07-07 16:21:29 +00001288FUNC1(log1p, m_log1p, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001289 "log1p($module, x, /)\n--\n\n"
1290 "Return the natural logarithm of 1+x (base e).\n\n"
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001291 "The result is computed in a way which is accurate for x near zero.")
Mark Dickinsona0ce3752017-04-05 18:34:27 +01001292FUNC2(remainder, m_remainder,
1293 "remainder($module, x, y, /)\n--\n\n"
1294 "Difference between x and the closest integer multiple of y.\n\n"
1295 "Return x - n*y where n*y is the closest integer multiple of y.\n"
1296 "In the case where x is exactly halfway between two multiples of\n"
1297 "y, the nearest even value of n is used. The result is always exact.")
Christian Heimes53876d92008-04-19 00:31:39 +00001298FUNC1(sin, sin, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001299 "sin($module, x, /)\n--\n\n"
1300 "Return the sine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001301FUNC1(sinh, sinh, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001302 "sinh($module, x, /)\n--\n\n"
1303 "Return the hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001304FUNC1(sqrt, sqrt, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001305 "sqrt($module, x, /)\n--\n\n"
1306 "Return the square root of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001307FUNC1(tan, tan, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001308 "tan($module, x, /)\n--\n\n"
1309 "Return the tangent of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001310FUNC1(tanh, tanh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001311 "tanh($module, x, /)\n--\n\n"
1312 "Return the hyperbolic tangent of x.")
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001313
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001314/* Precision summation function as msum() by Raymond Hettinger in
1315 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
1316 enhanced with the exact partials sum and roundoff from Mark
1317 Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
1318 See those links for more details, proofs and other references.
1319
1320 Note 1: IEEE 754R floating point semantics are assumed,
1321 but the current implementation does not re-establish special
1322 value semantics across iterations (i.e. handling -Inf + Inf).
1323
1324 Note 2: No provision is made for intermediate overflow handling;
Georg Brandlf78e02b2008-06-10 17:40:04 +00001325 therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001326 sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
1327 overflow of the first partial sum.
1328
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001329 Note 3: The intermediate values lo, yr, and hi are declared volatile so
1330 aggressive compilers won't algebraically reduce lo to always be exactly 0.0.
Georg Brandlf78e02b2008-06-10 17:40:04 +00001331 Also, the volatile declaration forces the values to be stored in memory as
1332 regular doubles instead of extended long precision (80-bit) values. This
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001333 prevents double rounding because any addition or subtraction of two doubles
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 can be resolved exactly into double-sized hi and lo values. As long as the
Georg Brandlf78e02b2008-06-10 17:40:04 +00001335 hi value gets forced into a double before yr and lo are computed, the extra
1336 bits in downstream extended precision operations (x87 for example) will be
1337 exactly zero and therefore can be losslessly stored back into a double,
1338 thereby preventing double rounding.
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001339
1340 Note 4: A similar implementation is in Modules/cmathmodule.c.
1341 Be sure to update both when making changes.
1342
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001343 Note 5: The signature of math.fsum() differs from builtins.sum()
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001344 because the start argument doesn't make sense in the context of
1345 accurate summation. Since the partials table is collapsed before
1346 returning a result, sum(seq2, start=sum(seq1)) may not equal the
1347 accurate result returned by sum(itertools.chain(seq1, seq2)).
1348*/
1349
1350#define NUM_PARTIALS 32 /* initial partials array size, on stack */
1351
1352/* Extend the partials array p[] by doubling its size. */
1353static int /* non-zero on error */
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001354_fsum_realloc(double **p_ptr, Py_ssize_t n,
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001355 double *ps, Py_ssize_t *m_ptr)
1356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 void *v = NULL;
1358 Py_ssize_t m = *m_ptr;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 m += m; /* double */
Victor Stinner049e5092014-08-17 22:20:00 +02001361 if (n < m && (size_t)m < ((size_t)PY_SSIZE_T_MAX / sizeof(double))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 double *p = *p_ptr;
1363 if (p == ps) {
1364 v = PyMem_Malloc(sizeof(double) * m);
1365 if (v != NULL)
1366 memcpy(v, ps, sizeof(double) * n);
1367 }
1368 else
1369 v = PyMem_Realloc(p, sizeof(double) * m);
1370 }
1371 if (v == NULL) { /* size overflow or no memory */
1372 PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
1373 return 1;
1374 }
1375 *p_ptr = (double*) v;
1376 *m_ptr = m;
1377 return 0;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001378}
1379
1380/* Full precision summation of a sequence of floats.
1381
1382 def msum(iterable):
1383 partials = [] # sorted, non-overlapping partial sums
1384 for x in iterable:
Mark Dickinsonfdb0acc2010-06-25 20:22:24 +00001385 i = 0
1386 for y in partials:
1387 if abs(x) < abs(y):
1388 x, y = y, x
1389 hi = x + y
1390 lo = y - (hi - x)
1391 if lo:
1392 partials[i] = lo
1393 i += 1
1394 x = hi
1395 partials[i:] = [x]
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001396 return sum_exact(partials)
1397
1398 Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
1399 are exactly equal to x+y. The inner loop applies hi/lo summation to each
1400 partial so that the list of partial sums remains exact.
1401
1402 Sum_exact() adds the partial sums exactly and correctly rounds the final
1403 result (using the round-half-to-even rule). The items in partials remain
1404 non-zero, non-special, non-overlapping and strictly increasing in
1405 magnitude, but possibly not all having the same sign.
1406
1407 Depends on IEEE 754 arithmetic guarantees and half-even rounding.
1408*/
1409
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001410/*[clinic input]
1411math.fsum
1412
1413 seq: object
1414 /
1415
1416Return an accurate floating point sum of values in the iterable seq.
1417
1418Assumes IEEE-754 floating point arithmetic.
1419[clinic start generated code]*/
1420
1421static PyObject *
1422math_fsum(PyObject *module, PyObject *seq)
1423/*[clinic end generated code: output=ba5c672b87fe34fc input=c51b7d8caf6f6e82]*/
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 PyObject *item, *iter, *sum = NULL;
1426 Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
1427 double x, y, t, ps[NUM_PARTIALS], *p = ps;
1428 double xsave, special_sum = 0.0, inf_sum = 0.0;
1429 volatile double hi, yr, lo;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 iter = PyObject_GetIter(seq);
1432 if (iter == NULL)
1433 return NULL;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 for(;;) { /* for x in iterable */
1436 assert(0 <= n && n <= m);
1437 assert((m == NUM_PARTIALS && p == ps) ||
1438 (m > NUM_PARTIALS && p != NULL));
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 item = PyIter_Next(iter);
1441 if (item == NULL) {
1442 if (PyErr_Occurred())
1443 goto _fsum_error;
1444 break;
1445 }
Raymond Hettingercfd735e2019-01-29 20:39:53 -08001446 ASSIGN_DOUBLE(x, item, error_with_item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 Py_DECREF(item);
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 xsave = x;
1450 for (i = j = 0; j < n; j++) { /* for y in partials */
1451 y = p[j];
1452 if (fabs(x) < fabs(y)) {
1453 t = x; x = y; y = t;
1454 }
1455 hi = x + y;
1456 yr = hi - x;
1457 lo = y - yr;
1458 if (lo != 0.0)
1459 p[i++] = lo;
1460 x = hi;
1461 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 n = i; /* ps[i:] = [x] */
1464 if (x != 0.0) {
1465 if (! Py_IS_FINITE(x)) {
1466 /* a nonfinite x could arise either as
1467 a result of intermediate overflow, or
1468 as a result of a nan or inf in the
1469 summands */
1470 if (Py_IS_FINITE(xsave)) {
1471 PyErr_SetString(PyExc_OverflowError,
1472 "intermediate overflow in fsum");
1473 goto _fsum_error;
1474 }
1475 if (Py_IS_INFINITY(xsave))
1476 inf_sum += xsave;
1477 special_sum += xsave;
1478 /* reset partials */
1479 n = 0;
1480 }
1481 else if (n >= m && _fsum_realloc(&p, n, ps, &m))
1482 goto _fsum_error;
1483 else
1484 p[n++] = x;
1485 }
1486 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 if (special_sum != 0.0) {
1489 if (Py_IS_NAN(inf_sum))
1490 PyErr_SetString(PyExc_ValueError,
1491 "-inf + inf in fsum");
1492 else
1493 sum = PyFloat_FromDouble(special_sum);
1494 goto _fsum_error;
1495 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 hi = 0.0;
1498 if (n > 0) {
1499 hi = p[--n];
1500 /* sum_exact(ps, hi) from the top, stop when the sum becomes
1501 inexact. */
1502 while (n > 0) {
1503 x = hi;
1504 y = p[--n];
1505 assert(fabs(y) < fabs(x));
1506 hi = x + y;
1507 yr = hi - x;
1508 lo = y - yr;
1509 if (lo != 0.0)
1510 break;
1511 }
1512 /* Make half-even rounding work across multiple partials.
1513 Needed so that sum([1e-16, 1, 1e16]) will round-up the last
1514 digit to two instead of down to zero (the 1e-16 makes the 1
1515 slightly closer to two). With a potential 1 ULP rounding
1516 error fixed-up, math.fsum() can guarantee commutativity. */
1517 if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
1518 (lo > 0.0 && p[n-1] > 0.0))) {
1519 y = lo * 2.0;
1520 x = hi + y;
1521 yr = x - hi;
1522 if (y == yr)
1523 hi = x;
1524 }
1525 }
1526 sum = PyFloat_FromDouble(hi);
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001527
Raymond Hettingercfd735e2019-01-29 20:39:53 -08001528 _fsum_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 Py_DECREF(iter);
1530 if (p != ps)
1531 PyMem_Free(p);
1532 return sum;
Raymond Hettingercfd735e2019-01-29 20:39:53 -08001533
1534 error_with_item:
1535 Py_DECREF(item);
1536 goto _fsum_error;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001537}
1538
1539#undef NUM_PARTIALS
1540
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001541
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001542static unsigned long
1543count_set_bits(unsigned long n)
1544{
1545 unsigned long count = 0;
1546 while (n != 0) {
1547 ++count;
1548 n &= n - 1; /* clear least significant bit */
1549 }
1550 return count;
1551}
1552
Mark Dickinson73934b92019-05-18 12:29:50 +01001553/* Integer square root
1554
1555Given a nonnegative integer `n`, we want to compute the largest integer
1556`a` for which `a * a <= n`, or equivalently the integer part of the exact
1557square root of `n`.
1558
1559We use an adaptive-precision pure-integer version of Newton's iteration. Given
1560a positive integer `n`, the algorithm produces at each iteration an integer
1561approximation `a` to the square root of `n >> s` for some even integer `s`,
1562with `s` decreasing as the iterations progress. On the final iteration, `s` is
1563zero and we have an approximation to the square root of `n` itself.
1564
1565At every step, the approximation `a` is strictly within 1.0 of the true square
1566root, so we have
1567
1568 (a - 1)**2 < (n >> s) < (a + 1)**2
1569
1570After the final iteration, a check-and-correct step is needed to determine
1571whether `a` or `a - 1` gives the desired integer square root of `n`.
1572
1573The algorithm is remarkable in its simplicity. There's no need for a
1574per-iteration check-and-correct step, and termination is straightforward: the
1575number of iterations is known in advance (it's exactly `floor(log2(log2(n)))`
1576for `n > 1`). The only tricky part of the correctness proof is in establishing
1577that the bound `(a - 1)**2 < (n >> s) < (a + 1)**2` is maintained from one
1578iteration to the next. A sketch of the proof of this is given below.
1579
1580In addition to the proof sketch, a formal, computer-verified proof
1581of correctness (using Lean) of an equivalent recursive algorithm can be found
1582here:
1583
1584 https://github.com/mdickinson/snippets/blob/master/proofs/isqrt/src/isqrt.lean
1585
1586
1587Here's Python code equivalent to the C implementation below:
1588
1589 def isqrt(n):
1590 """
1591 Return the integer part of the square root of the input.
1592 """
1593 n = operator.index(n)
1594
1595 if n < 0:
1596 raise ValueError("isqrt() argument must be nonnegative")
1597 if n == 0:
1598 return 0
1599
1600 c = (n.bit_length() - 1) // 2
1601 a = 1
1602 d = 0
1603 for s in reversed(range(c.bit_length())):
Mark Dickinson2dfeaa92019-06-16 17:53:21 +01001604 # Loop invariant: (a-1)**2 < (n >> 2*(c - d)) < (a+1)**2
Mark Dickinson73934b92019-05-18 12:29:50 +01001605 e = d
1606 d = c >> s
1607 a = (a << d - e - 1) + (n >> 2*c - e - d + 1) // a
Mark Dickinson73934b92019-05-18 12:29:50 +01001608
1609 return a - (a*a > n)
1610
1611
1612Sketch of proof of correctness
1613------------------------------
1614
1615The delicate part of the correctness proof is showing that the loop invariant
1616is preserved from one iteration to the next. That is, just before the line
1617
1618 a = (a << d - e - 1) + (n >> 2*c - e - d + 1) // a
1619
1620is executed in the above code, we know that
1621
1622 (1) (a - 1)**2 < (n >> 2*(c - e)) < (a + 1)**2.
1623
1624(since `e` is always the value of `d` from the previous iteration). We must
1625prove that after that line is executed, we have
1626
1627 (a - 1)**2 < (n >> 2*(c - d)) < (a + 1)**2
1628
Min ho Kimf7d72e42019-07-06 07:39:32 +10001629To facilitate the proof, we make some changes of notation. Write `m` for
Mark Dickinson73934b92019-05-18 12:29:50 +01001630`n >> 2*(c-d)`, and write `b` for the new value of `a`, so
1631
1632 b = (a << d - e - 1) + (n >> 2*c - e - d + 1) // a
1633
1634or equivalently:
1635
1636 (2) b = (a << d - e - 1) + (m >> d - e + 1) // a
1637
1638Then we can rewrite (1) as:
1639
1640 (3) (a - 1)**2 < (m >> 2*(d - e)) < (a + 1)**2
1641
1642and we must show that (b - 1)**2 < m < (b + 1)**2.
1643
1644From this point on, we switch to mathematical notation, so `/` means exact
1645division rather than integer division and `^` is used for exponentiation. We
1646use the `√` symbol for the exact square root. In (3), we can remove the
1647implicit floor operation to give:
1648
1649 (4) (a - 1)^2 < m / 4^(d - e) < (a + 1)^2
1650
1651Taking square roots throughout (4), scaling by `2^(d-e)`, and rearranging gives
1652
1653 (5) 0 <= | 2^(d-e)a - √m | < 2^(d-e)
1654
1655Squaring and dividing through by `2^(d-e+1) a` gives
1656
1657 (6) 0 <= 2^(d-e-1) a + m / (2^(d-e+1) a) - √m < 2^(d-e-1) / a
1658
1659We'll show below that `2^(d-e-1) <= a`. Given that, we can replace the
1660right-hand side of (6) with `1`, and now replacing the central
1661term `m / (2^(d-e+1) a)` with its floor in (6) gives
1662
1663 (7) -1 < 2^(d-e-1) a + m // 2^(d-e+1) a - √m < 1
1664
1665Or equivalently, from (2):
1666
1667 (7) -1 < b - √m < 1
1668
1669and rearranging gives that `(b-1)^2 < m < (b+1)^2`, which is what we needed
1670to prove.
1671
1672We're not quite done: we still have to prove the inequality `2^(d - e - 1) <=
1673a` that was used to get line (7) above. From the definition of `c`, we have
1674`4^c <= n`, which implies
1675
1676 (8) 4^d <= m
1677
1678also, since `e == d >> 1`, `d` is at most `2e + 1`, from which it follows
1679that `2d - 2e - 1 <= d` and hence that
1680
1681 (9) 4^(2d - 2e - 1) <= m
1682
1683Dividing both sides by `4^(d - e)` gives
1684
1685 (10) 4^(d - e - 1) <= m / 4^(d - e)
1686
1687But we know from (4) that `m / 4^(d-e) < (a + 1)^2`, hence
1688
1689 (11) 4^(d - e - 1) < (a + 1)^2
1690
1691Now taking square roots of both sides and observing that both `2^(d-e-1)` and
1692`a` are integers gives `2^(d - e - 1) <= a`, which is what we needed. This
1693completes the proof sketch.
1694
1695*/
1696
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001697
1698/* Approximate square root of a large 64-bit integer.
1699
1700 Given `n` satisfying `2**62 <= n < 2**64`, return `a`
1701 satisfying `(a - 1)**2 < n < (a + 1)**2`. */
1702
1703static uint64_t
1704_approximate_isqrt(uint64_t n)
1705{
1706 uint32_t u = 1U + (n >> 62);
1707 u = (u << 1) + (n >> 59) / u;
1708 u = (u << 3) + (n >> 53) / u;
1709 u = (u << 7) + (n >> 41) / u;
1710 return (u << 15) + (n >> 17) / u;
1711}
1712
Mark Dickinson73934b92019-05-18 12:29:50 +01001713/*[clinic input]
1714math.isqrt
1715
1716 n: object
1717 /
1718
1719Return the integer part of the square root of the input.
1720[clinic start generated code]*/
1721
1722static PyObject *
1723math_isqrt(PyObject *module, PyObject *n)
1724/*[clinic end generated code: output=35a6f7f980beab26 input=5b6e7ae4fa6c43d6]*/
1725{
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001726 int a_too_large, c_bit_length;
Mark Dickinson73934b92019-05-18 12:29:50 +01001727 size_t c, d;
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001728 uint64_t m, u;
Mark Dickinson73934b92019-05-18 12:29:50 +01001729 PyObject *a = NULL, *b;
1730
1731 n = PyNumber_Index(n);
1732 if (n == NULL) {
1733 return NULL;
1734 }
1735
1736 if (_PyLong_Sign(n) < 0) {
1737 PyErr_SetString(
1738 PyExc_ValueError,
1739 "isqrt() argument must be nonnegative");
1740 goto error;
1741 }
1742 if (_PyLong_Sign(n) == 0) {
1743 Py_DECREF(n);
1744 return PyLong_FromLong(0);
1745 }
1746
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001747 /* c = (n.bit_length() - 1) // 2 */
Mark Dickinson73934b92019-05-18 12:29:50 +01001748 c = _PyLong_NumBits(n);
1749 if (c == (size_t)(-1)) {
1750 goto error;
1751 }
1752 c = (c - 1U) / 2U;
1753
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001754 /* Fast path: if c <= 31 then n < 2**64 and we can compute directly with a
1755 fast, almost branch-free algorithm. In the final correction, we use `u*u
1756 - 1 >= m` instead of the simpler `u*u > m` in order to get the correct
1757 result in the corner case where `u=2**32`. */
1758 if (c <= 31U) {
1759 m = (uint64_t)PyLong_AsUnsignedLongLong(n);
1760 Py_DECREF(n);
1761 if (m == (uint64_t)(-1) && PyErr_Occurred()) {
1762 return NULL;
1763 }
1764 u = _approximate_isqrt(m << (62U - 2U*c)) >> (31U - c);
1765 u -= u * u - 1U >= m;
1766 return PyLong_FromUnsignedLongLong((unsigned long long)u);
Mark Dickinson73934b92019-05-18 12:29:50 +01001767 }
1768
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001769 /* Slow path: n >= 2**64. We perform the first five iterations in C integer
1770 arithmetic, then switch to using Python long integers. */
1771
1772 /* From n >= 2**64 it follows that c.bit_length() >= 6. */
1773 c_bit_length = 6;
1774 while ((c >> c_bit_length) > 0U) {
1775 ++c_bit_length;
1776 }
1777
1778 /* Initialise d and a. */
1779 d = c >> (c_bit_length - 5);
1780 b = _PyLong_Rshift(n, 2U*c - 62U);
1781 if (b == NULL) {
1782 goto error;
1783 }
1784 m = (uint64_t)PyLong_AsUnsignedLongLong(b);
1785 Py_DECREF(b);
1786 if (m == (uint64_t)(-1) && PyErr_Occurred()) {
1787 goto error;
1788 }
1789 u = _approximate_isqrt(m) >> (31U - d);
1790 a = PyLong_FromUnsignedLongLong((unsigned long long)u);
Mark Dickinson73934b92019-05-18 12:29:50 +01001791 if (a == NULL) {
1792 goto error;
1793 }
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001794
1795 for (int s = c_bit_length - 6; s >= 0; --s) {
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03001796 PyObject *q;
Mark Dickinson73934b92019-05-18 12:29:50 +01001797 size_t e = d;
1798
1799 d = c >> s;
1800
1801 /* q = (n >> 2*c - e - d + 1) // a */
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03001802 q = _PyLong_Rshift(n, 2U*c - d - e + 1U);
Mark Dickinson73934b92019-05-18 12:29:50 +01001803 if (q == NULL) {
1804 goto error;
1805 }
1806 Py_SETREF(q, PyNumber_FloorDivide(q, a));
1807 if (q == NULL) {
1808 goto error;
1809 }
1810
1811 /* a = (a << d - 1 - e) + q */
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03001812 Py_SETREF(a, _PyLong_Lshift(a, d - 1U - e));
Mark Dickinson73934b92019-05-18 12:29:50 +01001813 if (a == NULL) {
1814 Py_DECREF(q);
1815 goto error;
1816 }
1817 Py_SETREF(a, PyNumber_Add(a, q));
1818 Py_DECREF(q);
1819 if (a == NULL) {
1820 goto error;
1821 }
1822 }
1823
1824 /* The correct result is either a or a - 1. Figure out which, and
1825 decrement a if necessary. */
1826
1827 /* a_too_large = n < a * a */
1828 b = PyNumber_Multiply(a, a);
1829 if (b == NULL) {
1830 goto error;
1831 }
1832 a_too_large = PyObject_RichCompareBool(n, b, Py_LT);
1833 Py_DECREF(b);
1834 if (a_too_large == -1) {
1835 goto error;
1836 }
1837
1838 if (a_too_large) {
1839 Py_SETREF(a, PyNumber_Subtract(a, _PyLong_One));
1840 }
1841 Py_DECREF(n);
1842 return a;
1843
1844 error:
1845 Py_XDECREF(a);
1846 Py_DECREF(n);
1847 return NULL;
1848}
1849
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001850/* Divide-and-conquer factorial algorithm
1851 *
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07001852 * Based on the formula and pseudo-code provided at:
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001853 * http://www.luschny.de/math/factorial/binarysplitfact.html
1854 *
1855 * Faster algorithms exist, but they're more complicated and depend on
Ezio Melotti9527afd2010-07-08 15:03:02 +00001856 * a fast prime factorization algorithm.
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001857 *
1858 * Notes on the algorithm
1859 * ----------------------
1860 *
1861 * factorial(n) is written in the form 2**k * m, with m odd. k and m are
1862 * computed separately, and then combined using a left shift.
1863 *
1864 * The function factorial_odd_part computes the odd part m (i.e., the greatest
1865 * odd divisor) of factorial(n), using the formula:
1866 *
1867 * factorial_odd_part(n) =
1868 *
1869 * product_{i >= 0} product_{0 < j <= n / 2**i, j odd} j
1870 *
1871 * Example: factorial_odd_part(20) =
1872 *
1873 * (1) *
1874 * (1) *
1875 * (1 * 3 * 5) *
1876 * (1 * 3 * 5 * 7 * 9)
1877 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1878 *
1879 * Here i goes from large to small: the first term corresponds to i=4 (any
1880 * larger i gives an empty product), and the last term corresponds to i=0.
1881 * Each term can be computed from the last by multiplying by the extra odd
1882 * numbers required: e.g., to get from the penultimate term to the last one,
1883 * we multiply by (11 * 13 * 15 * 17 * 19).
1884 *
1885 * To see a hint of why this formula works, here are the same numbers as above
1886 * but with the even parts (i.e., the appropriate powers of 2) included. For
1887 * each subterm in the product for i, we multiply that subterm by 2**i:
1888 *
1889 * factorial(20) =
1890 *
1891 * (16) *
1892 * (8) *
1893 * (4 * 12 * 20) *
1894 * (2 * 6 * 10 * 14 * 18) *
1895 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1896 *
1897 * The factorial_partial_product function computes the product of all odd j in
1898 * range(start, stop) for given start and stop. It's used to compute the
1899 * partial products like (11 * 13 * 15 * 17 * 19) in the example above. It
1900 * operates recursively, repeatedly splitting the range into two roughly equal
1901 * pieces until the subranges are small enough to be computed using only C
1902 * integer arithmetic.
1903 *
1904 * The two-valuation k (i.e., the exponent of the largest power of 2 dividing
1905 * the factorial) is computed independently in the main math_factorial
1906 * function. By standard results, its value is:
1907 *
1908 * two_valuation = n//2 + n//4 + n//8 + ....
1909 *
1910 * It can be shown (e.g., by complete induction on n) that two_valuation is
1911 * equal to n - count_set_bits(n), where count_set_bits(n) gives the number of
1912 * '1'-bits in the binary expansion of n.
1913 */
1914
1915/* factorial_partial_product: Compute product(range(start, stop, 2)) using
1916 * divide and conquer. Assumes start and stop are odd and stop > start.
1917 * max_bits must be >= bit_length(stop - 2). */
1918
1919static PyObject *
1920factorial_partial_product(unsigned long start, unsigned long stop,
1921 unsigned long max_bits)
1922{
1923 unsigned long midpoint, num_operands;
1924 PyObject *left = NULL, *right = NULL, *result = NULL;
1925
1926 /* If the return value will fit an unsigned long, then we can
1927 * multiply in a tight, fast loop where each multiply is O(1).
1928 * Compute an upper bound on the number of bits required to store
1929 * the answer.
1930 *
1931 * Storing some integer z requires floor(lg(z))+1 bits, which is
1932 * conveniently the value returned by bit_length(z). The
1933 * product x*y will require at most
1934 * bit_length(x) + bit_length(y) bits to store, based
1935 * on the idea that lg product = lg x + lg y.
1936 *
1937 * We know that stop - 2 is the largest number to be multiplied. From
1938 * there, we have: bit_length(answer) <= num_operands *
1939 * bit_length(stop - 2)
1940 */
1941
1942 num_operands = (stop - start) / 2;
1943 /* The "num_operands <= 8 * SIZEOF_LONG" check guards against the
1944 * unlikely case of an overflow in num_operands * max_bits. */
1945 if (num_operands <= 8 * SIZEOF_LONG &&
1946 num_operands * max_bits <= 8 * SIZEOF_LONG) {
1947 unsigned long j, total;
1948 for (total = start, j = start + 2; j < stop; j += 2)
1949 total *= j;
1950 return PyLong_FromUnsignedLong(total);
1951 }
1952
1953 /* find midpoint of range(start, stop), rounded up to next odd number. */
1954 midpoint = (start + num_operands) | 1;
1955 left = factorial_partial_product(start, midpoint,
Niklas Fiekasc5b79002020-01-16 15:09:19 +01001956 _Py_bit_length(midpoint - 2));
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001957 if (left == NULL)
1958 goto error;
1959 right = factorial_partial_product(midpoint, stop, max_bits);
1960 if (right == NULL)
1961 goto error;
1962 result = PyNumber_Multiply(left, right);
1963
1964 error:
1965 Py_XDECREF(left);
1966 Py_XDECREF(right);
1967 return result;
1968}
1969
1970/* factorial_odd_part: compute the odd part of factorial(n). */
1971
1972static PyObject *
1973factorial_odd_part(unsigned long n)
1974{
1975 long i;
1976 unsigned long v, lower, upper;
1977 PyObject *partial, *tmp, *inner, *outer;
1978
1979 inner = PyLong_FromLong(1);
1980 if (inner == NULL)
1981 return NULL;
1982 outer = inner;
1983 Py_INCREF(outer);
1984
1985 upper = 3;
Niklas Fiekasc5b79002020-01-16 15:09:19 +01001986 for (i = _Py_bit_length(n) - 2; i >= 0; i--) {
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001987 v = n >> i;
1988 if (v <= 2)
1989 continue;
1990 lower = upper;
1991 /* (v + 1) | 1 = least odd integer strictly larger than n / 2**i */
1992 upper = (v + 1) | 1;
1993 /* Here inner is the product of all odd integers j in the range (0,
1994 n/2**(i+1)]. The factorial_partial_product call below gives the
1995 product of all odd integers j in the range (n/2**(i+1), n/2**i]. */
Niklas Fiekasc5b79002020-01-16 15:09:19 +01001996 partial = factorial_partial_product(lower, upper, _Py_bit_length(upper-2));
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001997 /* inner *= partial */
1998 if (partial == NULL)
1999 goto error;
2000 tmp = PyNumber_Multiply(inner, partial);
2001 Py_DECREF(partial);
2002 if (tmp == NULL)
2003 goto error;
2004 Py_DECREF(inner);
2005 inner = tmp;
2006 /* Now inner is the product of all odd integers j in the range (0,
2007 n/2**i], giving the inner product in the formula above. */
2008
2009 /* outer *= inner; */
2010 tmp = PyNumber_Multiply(outer, inner);
2011 if (tmp == NULL)
2012 goto error;
2013 Py_DECREF(outer);
2014 outer = tmp;
2015 }
Mark Dickinson76464492012-10-25 10:46:28 +01002016 Py_DECREF(inner);
2017 return outer;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002018
2019 error:
2020 Py_DECREF(outer);
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002021 Py_DECREF(inner);
Mark Dickinson76464492012-10-25 10:46:28 +01002022 return NULL;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002023}
2024
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002025
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002026/* Lookup table for small factorial values */
2027
2028static const unsigned long SmallFactorials[] = {
2029 1, 1, 2, 6, 24, 120, 720, 5040, 40320,
2030 362880, 3628800, 39916800, 479001600,
2031#if SIZEOF_LONG >= 8
2032 6227020800, 87178291200, 1307674368000,
2033 20922789888000, 355687428096000, 6402373705728000,
2034 121645100408832000, 2432902008176640000
2035#endif
2036};
2037
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002038/*[clinic input]
2039math.factorial
2040
2041 x as arg: object
2042 /
2043
2044Find x!.
2045
2046Raise a ValueError if x is negative or non-integral.
2047[clinic start generated code]*/
2048
Barry Warsaw8b43b191996-12-09 22:32:36 +00002049static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002050math_factorial(PyObject *module, PyObject *arg)
2051/*[clinic end generated code: output=6686f26fae00e9ca input=6d1c8105c0d91fb4]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002052{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03002053 long x, two_valuation;
Mark Dickinson5990d282014-04-10 09:29:39 -04002054 int overflow;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03002055 PyObject *result, *odd_part, *pyint_form;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 if (PyFloat_Check(arg)) {
Serhiy Storchaka231aad32019-06-17 16:57:27 +03002058 if (PyErr_WarnEx(PyExc_DeprecationWarning,
2059 "Using factorial() with floats is deprecated",
2060 1) < 0)
2061 {
2062 return NULL;
2063 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 PyObject *lx;
2065 double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
2066 if (!(Py_IS_FINITE(dx) && dx == floor(dx))) {
2067 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002068 "factorial() only accepts integral values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 return NULL;
2070 }
2071 lx = PyLong_FromDouble(dx);
2072 if (lx == NULL)
2073 return NULL;
Mark Dickinson5990d282014-04-10 09:29:39 -04002074 x = PyLong_AsLongAndOverflow(lx, &overflow);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 Py_DECREF(lx);
2076 }
Pablo Galindoe9ba3702018-09-03 22:20:06 +01002077 else {
2078 pyint_form = PyNumber_Index(arg);
2079 if (pyint_form == NULL) {
2080 return NULL;
2081 }
2082 x = PyLong_AsLongAndOverflow(pyint_form, &overflow);
2083 Py_DECREF(pyint_form);
2084 }
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002085
Mark Dickinson5990d282014-04-10 09:29:39 -04002086 if (x == -1 && PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 return NULL;
Mark Dickinson5990d282014-04-10 09:29:39 -04002088 }
2089 else if (overflow == 1) {
2090 PyErr_Format(PyExc_OverflowError,
2091 "factorial() argument should not exceed %ld",
2092 LONG_MAX);
2093 return NULL;
2094 }
2095 else if (overflow == -1 || x < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002097 "factorial() not defined for negative values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 return NULL;
2099 }
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002100
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002101 /* use lookup table if x is small */
Victor Stinner63941882011-09-29 00:42:28 +02002102 if (x < (long)Py_ARRAY_LENGTH(SmallFactorials))
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002103 return PyLong_FromUnsignedLong(SmallFactorials[x]);
2104
2105 /* else express in the form odd_part * 2**two_valuation, and compute as
2106 odd_part << two_valuation. */
2107 odd_part = factorial_odd_part(x);
2108 if (odd_part == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03002110 two_valuation = x - count_set_bits(x);
2111 result = _PyLong_Lshift(odd_part, two_valuation);
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002112 Py_DECREF(odd_part);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 return result;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002114}
2115
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002116
2117/*[clinic input]
2118math.trunc
2119
2120 x: object
2121 /
2122
2123Truncates the Real x to the nearest Integral toward 0.
2124
2125Uses the __trunc__ magic method.
2126[clinic start generated code]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002127
2128static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002129math_trunc(PyObject *module, PyObject *x)
2130/*[clinic end generated code: output=34b9697b707e1031 input=2168b34e0a09134d]*/
Christian Heimes400adb02008-02-01 08:12:03 +00002131{
Benjamin Petersonce798522012-01-22 11:24:29 -05002132 _Py_IDENTIFIER(__trunc__);
Benjamin Petersonb0125892010-07-02 13:35:17 +00002133 PyObject *trunc, *result;
Christian Heimes400adb02008-02-01 08:12:03 +00002134
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02002135 if (PyFloat_CheckExact(x)) {
2136 return PyFloat_Type.tp_as_number->nb_int(x);
2137 }
2138
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002139 if (Py_TYPE(x)->tp_dict == NULL) {
2140 if (PyType_Ready(Py_TYPE(x)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 return NULL;
2142 }
Christian Heimes400adb02008-02-01 08:12:03 +00002143
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002144 trunc = _PyObject_LookupSpecial(x, &PyId___trunc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 if (trunc == NULL) {
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00002146 if (!PyErr_Occurred())
2147 PyErr_Format(PyExc_TypeError,
2148 "type %.100s doesn't define __trunc__ method",
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002149 Py_TYPE(x)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 return NULL;
2151 }
Victor Stinnerf17c3de2016-12-06 18:46:19 +01002152 result = _PyObject_CallNoArg(trunc);
Benjamin Petersonb0125892010-07-02 13:35:17 +00002153 Py_DECREF(trunc);
2154 return result;
Christian Heimes400adb02008-02-01 08:12:03 +00002155}
2156
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002157
2158/*[clinic input]
2159math.frexp
2160
2161 x: double
2162 /
2163
2164Return the mantissa and exponent of x, as pair (m, e).
2165
2166m is a float and e is an int, such that x = m * 2.**e.
2167If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.
2168[clinic start generated code]*/
Christian Heimes400adb02008-02-01 08:12:03 +00002169
2170static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002171math_frexp_impl(PyObject *module, double x)
2172/*[clinic end generated code: output=03e30d252a15ad4a input=96251c9e208bc6e9]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00002173{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 /* deal with special cases directly, to sidestep platform
2176 differences */
2177 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
2178 i = 0;
2179 }
2180 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 x = frexp(x, &i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 }
2183 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +00002184}
2185
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002186
2187/*[clinic input]
2188math.ldexp
2189
2190 x: double
2191 i: object
2192 /
2193
2194Return x * (2**i).
2195
2196This is essentially the inverse of frexp().
2197[clinic start generated code]*/
Guido van Rossumc6e22901998-12-04 19:26:43 +00002198
Barry Warsaw8b43b191996-12-09 22:32:36 +00002199static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002200math_ldexp_impl(PyObject *module, double x, PyObject *i)
2201/*[clinic end generated code: output=b6892f3c2df9cc6a input=17d5970c1a40a8c1]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00002202{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002203 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 long exp;
2205 int overflow;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00002206
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002207 if (PyLong_Check(i)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002208 /* on overflow, replace exponent with either LONG_MAX
2209 or LONG_MIN, depending on the sign. */
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002210 exp = PyLong_AsLongAndOverflow(i, &overflow);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 if (exp == -1 && PyErr_Occurred())
2212 return NULL;
2213 if (overflow)
2214 exp = overflow < 0 ? LONG_MIN : LONG_MAX;
2215 }
2216 else {
2217 PyErr_SetString(PyExc_TypeError,
Serhiy Storchaka95949422013-08-27 19:40:23 +03002218 "Expected an int as second argument to ldexp.");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 return NULL;
2220 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00002221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 if (x == 0. || !Py_IS_FINITE(x)) {
2223 /* NaNs, zeros and infinities are returned unchanged */
2224 r = x;
2225 errno = 0;
2226 } else if (exp > INT_MAX) {
2227 /* overflow */
2228 r = copysign(Py_HUGE_VAL, x);
2229 errno = ERANGE;
2230 } else if (exp < INT_MIN) {
2231 /* underflow to +-0 */
2232 r = copysign(0., x);
2233 errno = 0;
2234 } else {
2235 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 r = ldexp(x, (int)exp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 if (Py_IS_INFINITY(r))
2238 errno = ERANGE;
2239 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00002240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 if (errno && is_error(r))
2242 return NULL;
2243 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +00002244}
2245
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002246
2247/*[clinic input]
2248math.modf
2249
2250 x: double
2251 /
2252
2253Return the fractional and integer parts of x.
2254
2255Both results carry the sign of x and are floats.
2256[clinic start generated code]*/
Guido van Rossumc6e22901998-12-04 19:26:43 +00002257
Barry Warsaw8b43b191996-12-09 22:32:36 +00002258static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002259math_modf_impl(PyObject *module, double x)
2260/*[clinic end generated code: output=90cee0260014c3c0 input=b4cfb6786afd9035]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00002261{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002262 double y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 /* some platforms don't do the right thing for NaNs and
2264 infinities, so we take care of special cases directly. */
2265 if (!Py_IS_FINITE(x)) {
2266 if (Py_IS_INFINITY(x))
2267 return Py_BuildValue("(dd)", copysign(0., x), x);
2268 else if (Py_IS_NAN(x))
2269 return Py_BuildValue("(dd)", x, x);
2270 }
Christian Heimesa342c012008-04-20 21:01:16 +00002271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 x = modf(x, &y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +00002275}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002276
Guido van Rossumc6e22901998-12-04 19:26:43 +00002277
Serhiy Storchaka95949422013-08-27 19:40:23 +03002278/* A decent logarithm is easy to compute even for huge ints, but libm can't
Tim Peters78526162001-09-05 00:53:45 +00002279 do that by itself -- loghelper can. func is log or log10, and name is
Serhiy Storchaka95949422013-08-27 19:40:23 +03002280 "log" or "log10". Note that overflow of the result isn't possible: an int
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002281 can contain no more than INT_MAX * SHIFT bits, so has value certainly less
2282 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 +00002283 small enough to fit in an IEEE single. log and log10 are even smaller.
Serhiy Storchaka95949422013-08-27 19:40:23 +03002284 However, intermediate overflow is possible for an int if the number of bits
2285 in that int is larger than PY_SSIZE_T_MAX. */
Tim Peters78526162001-09-05 00:53:45 +00002286
2287static PyObject*
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002288loghelper(PyObject* arg, double (*func)(double), const char *funcname)
Tim Peters78526162001-09-05 00:53:45 +00002289{
Serhiy Storchaka95949422013-08-27 19:40:23 +03002290 /* If it is int, do it ourselves. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 if (PyLong_Check(arg)) {
Mark Dickinsonc6037172010-09-29 19:06:36 +00002292 double x, result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 Py_ssize_t e;
Mark Dickinsonc6037172010-09-29 19:06:36 +00002294
2295 /* Negative or zero inputs give a ValueError. */
2296 if (Py_SIZE(arg) <= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 PyErr_SetString(PyExc_ValueError,
2298 "math domain error");
2299 return NULL;
2300 }
Mark Dickinsonfa41e602010-09-28 07:22:27 +00002301
Mark Dickinsonc6037172010-09-29 19:06:36 +00002302 x = PyLong_AsDouble(arg);
2303 if (x == -1.0 && PyErr_Occurred()) {
2304 if (!PyErr_ExceptionMatches(PyExc_OverflowError))
2305 return NULL;
2306 /* Here the conversion to double overflowed, but it's possible
2307 to compute the log anyway. Clear the exception and continue. */
2308 PyErr_Clear();
2309 x = _PyLong_Frexp((PyLongObject *)arg, &e);
2310 if (x == -1.0 && PyErr_Occurred())
2311 return NULL;
2312 /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */
2313 result = func(x) + func(2.0) * e;
2314 }
2315 else
2316 /* Successfully converted x to a double. */
2317 result = func(x);
2318 return PyFloat_FromDouble(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 }
Tim Peters78526162001-09-05 00:53:45 +00002320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 /* Else let libm handle it by itself. */
2322 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +00002323}
2324
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002325
2326/*[clinic input]
2327math.log
2328
2329 x: object
2330 [
2331 base: object(c_default="NULL") = math.e
2332 ]
2333 /
2334
2335Return the logarithm of x to the given base.
2336
2337If the base not specified, returns the natural logarithm (base e) of x.
2338[clinic start generated code]*/
2339
Tim Peters78526162001-09-05 00:53:45 +00002340static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002341math_log_impl(PyObject *module, PyObject *x, int group_right_1,
2342 PyObject *base)
2343/*[clinic end generated code: output=7b5a39e526b73fc9 input=0f62d5726cbfebbd]*/
Tim Peters78526162001-09-05 00:53:45 +00002344{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 PyObject *num, *den;
2346 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +00002347
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002348 num = loghelper(x, m_log, "log");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 if (num == NULL || base == NULL)
2350 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +00002351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 den = loghelper(base, m_log, "log");
2353 if (den == NULL) {
2354 Py_DECREF(num);
2355 return NULL;
2356 }
Raymond Hettinger866964c2002-12-14 19:51:34 +00002357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 ans = PyNumber_TrueDivide(num, den);
2359 Py_DECREF(num);
2360 Py_DECREF(den);
2361 return ans;
Tim Peters78526162001-09-05 00:53:45 +00002362}
2363
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002364
2365/*[clinic input]
2366math.log2
2367
2368 x: object
2369 /
2370
2371Return the base 2 logarithm of x.
2372[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002373
2374static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002375math_log2(PyObject *module, PyObject *x)
2376/*[clinic end generated code: output=5425899a4d5d6acb input=08321262bae4f39b]*/
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02002377{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002378 return loghelper(x, m_log2, "log2");
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02002379}
2380
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002381
2382/*[clinic input]
2383math.log10
2384
2385 x: object
2386 /
2387
2388Return the base 10 logarithm of x.
2389[clinic start generated code]*/
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02002390
2391static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002392math_log10(PyObject *module, PyObject *x)
2393/*[clinic end generated code: output=be72a64617df9c6f input=b2469d02c6469e53]*/
Tim Peters78526162001-09-05 00:53:45 +00002394{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002395 return loghelper(x, m_log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +00002396}
2397
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002398
2399/*[clinic input]
2400math.fmod
2401
2402 x: double
2403 y: double
2404 /
2405
2406Return fmod(x, y), according to platform C.
2407
2408x % y may differ.
2409[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002410
Christian Heimes53876d92008-04-19 00:31:39 +00002411static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002412math_fmod_impl(PyObject *module, double x, double y)
2413/*[clinic end generated code: output=7559d794343a27b5 input=4f84caa8cfc26a03]*/
Christian Heimes53876d92008-04-19 00:31:39 +00002414{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002415 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 /* fmod(x, +/-Inf) returns x for finite x. */
2417 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
2418 return PyFloat_FromDouble(x);
2419 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 r = fmod(x, y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 if (Py_IS_NAN(r)) {
2422 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
2423 errno = EDOM;
2424 else
2425 errno = 0;
2426 }
2427 if (errno && is_error(r))
2428 return NULL;
2429 else
2430 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00002431}
2432
Raymond Hettinger13990742018-08-11 11:26:36 -07002433/*
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002434Given an *n* length *vec* of values and a value *max*, compute:
Raymond Hettinger13990742018-08-11 11:26:36 -07002435
Raymond Hettingerc630e102018-08-11 18:39:05 -07002436 max * sqrt(sum((x / max) ** 2 for x in vec))
Raymond Hettinger13990742018-08-11 11:26:36 -07002437
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002438The value of the *max* variable must be non-negative and
Raymond Hettinger216aaaa2018-11-09 01:06:02 -08002439equal to the absolute value of the largest magnitude
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002440entry in the vector. If n==0, then *max* should be 0.0.
2441If an infinity is present in the vec, *max* should be INF.
Raymond Hettingerc630e102018-08-11 18:39:05 -07002442
2443The *found_nan* variable indicates whether some member of
2444the *vec* is a NaN.
Raymond Hettinger21786f52018-08-28 22:47:24 -07002445
2446To improve accuracy and to increase the number of cases where
2447vector_norm() is commutative, we use a variant of Neumaier
2448summation specialized to exploit that we always know that
2449|csum| >= |x|.
2450
2451The *csum* variable tracks the cumulative sum and *frac* tracks
2452the cumulative fractional errors at each step. Since this
2453variant assumes that |csum| >= |x| at each step, we establish
2454the precondition by starting the accumulation from 1.0 which
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002455represents the largest possible value of (x/max)**2.
2456
2457After the loop is finished, the initial 1.0 is subtracted out
2458for a net zero effect on the final sum. Since *csum* will be
2459greater than 1.0, the subtraction of 1.0 will not cause
2460fractional digits to be dropped from *csum*.
Raymond Hettinger21786f52018-08-28 22:47:24 -07002461
Raymond Hettinger13990742018-08-11 11:26:36 -07002462*/
2463
2464static inline double
Raymond Hettingerc630e102018-08-11 18:39:05 -07002465vector_norm(Py_ssize_t n, double *vec, double max, int found_nan)
Raymond Hettinger13990742018-08-11 11:26:36 -07002466{
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002467 double x, csum = 1.0, oldcsum, frac = 0.0;
Raymond Hettinger13990742018-08-11 11:26:36 -07002468 Py_ssize_t i;
2469
Raymond Hettingerc630e102018-08-11 18:39:05 -07002470 if (Py_IS_INFINITY(max)) {
2471 return max;
2472 }
2473 if (found_nan) {
2474 return Py_NAN;
2475 }
Raymond Hettingerf3267142018-09-02 13:34:21 -07002476 if (max == 0.0 || n <= 1) {
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002477 return max;
Raymond Hettinger13990742018-08-11 11:26:36 -07002478 }
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002479 for (i=0 ; i < n ; i++) {
Raymond Hettinger13990742018-08-11 11:26:36 -07002480 x = vec[i];
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002481 assert(Py_IS_FINITE(x) && fabs(x) <= max);
Raymond Hettinger13990742018-08-11 11:26:36 -07002482 x /= max;
Raymond Hettinger21786f52018-08-28 22:47:24 -07002483 x = x*x;
Raymond Hettinger13990742018-08-11 11:26:36 -07002484 oldcsum = csum;
2485 csum += x;
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002486 assert(csum >= x);
Raymond Hettinger21786f52018-08-28 22:47:24 -07002487 frac += (oldcsum - csum) + x;
Raymond Hettinger13990742018-08-11 11:26:36 -07002488 }
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002489 return max * sqrt(csum - 1.0 + frac);
Raymond Hettinger13990742018-08-11 11:26:36 -07002490}
2491
Raymond Hettingerc630e102018-08-11 18:39:05 -07002492#define NUM_STACK_ELEMS 16
2493
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002494/*[clinic input]
2495math.dist
2496
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002497 p: object
2498 q: object
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002499 /
2500
2501Return the Euclidean distance between two points p and q.
2502
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002503The points should be specified as sequences (or iterables) of
2504coordinates. Both inputs must have the same dimension.
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002505
2506Roughly equivalent to:
2507 sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
2508[clinic start generated code]*/
2509
2510static PyObject *
2511math_dist_impl(PyObject *module, PyObject *p, PyObject *q)
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002512/*[clinic end generated code: output=56bd9538d06bbcfe input=74e85e1b6092e68e]*/
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002513{
2514 PyObject *item;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002515 double max = 0.0;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002516 double x, px, qx, result;
2517 Py_ssize_t i, m, n;
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002518 int found_nan = 0, p_allocated = 0, q_allocated = 0;
Raymond Hettingerc630e102018-08-11 18:39:05 -07002519 double diffs_on_stack[NUM_STACK_ELEMS];
2520 double *diffs = diffs_on_stack;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002521
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002522 if (!PyTuple_Check(p)) {
2523 p = PySequence_Tuple(p);
2524 if (p == NULL) {
2525 return NULL;
2526 }
2527 p_allocated = 1;
2528 }
2529 if (!PyTuple_Check(q)) {
2530 q = PySequence_Tuple(q);
2531 if (q == NULL) {
2532 if (p_allocated) {
2533 Py_DECREF(p);
2534 }
2535 return NULL;
2536 }
2537 q_allocated = 1;
2538 }
2539
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002540 m = PyTuple_GET_SIZE(p);
2541 n = PyTuple_GET_SIZE(q);
2542 if (m != n) {
2543 PyErr_SetString(PyExc_ValueError,
2544 "both points must have the same number of dimensions");
2545 return NULL;
2546
2547 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002548 if (n > NUM_STACK_ELEMS) {
2549 diffs = (double *) PyObject_Malloc(n * sizeof(double));
2550 if (diffs == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07002551 return PyErr_NoMemory();
Raymond Hettingerc630e102018-08-11 18:39:05 -07002552 }
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002553 }
2554 for (i=0 ; i<n ; i++) {
2555 item = PyTuple_GET_ITEM(p, i);
Raymond Hettingercfd735e2019-01-29 20:39:53 -08002556 ASSIGN_DOUBLE(px, item, error_exit);
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002557 item = PyTuple_GET_ITEM(q, i);
Raymond Hettingercfd735e2019-01-29 20:39:53 -08002558 ASSIGN_DOUBLE(qx, item, error_exit);
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002559 x = fabs(px - qx);
2560 diffs[i] = x;
2561 found_nan |= Py_IS_NAN(x);
2562 if (x > max) {
2563 max = x;
2564 }
2565 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002566 result = vector_norm(n, diffs, max, found_nan);
2567 if (diffs != diffs_on_stack) {
2568 PyObject_Free(diffs);
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002569 }
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002570 if (p_allocated) {
2571 Py_DECREF(p);
2572 }
2573 if (q_allocated) {
2574 Py_DECREF(q);
2575 }
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002576 return PyFloat_FromDouble(result);
Raymond Hettingerc630e102018-08-11 18:39:05 -07002577
2578 error_exit:
2579 if (diffs != diffs_on_stack) {
2580 PyObject_Free(diffs);
2581 }
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002582 if (p_allocated) {
2583 Py_DECREF(p);
2584 }
2585 if (q_allocated) {
2586 Py_DECREF(q);
2587 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002588 return NULL;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002589}
2590
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002591/* AC: cannot convert yet, waiting for *args support */
Christian Heimes53876d92008-04-19 00:31:39 +00002592static PyObject *
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002593math_hypot(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Christian Heimes53876d92008-04-19 00:31:39 +00002594{
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002595 Py_ssize_t i;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002596 PyObject *item;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002597 double max = 0.0;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002598 double x, result;
2599 int found_nan = 0;
Raymond Hettingerc630e102018-08-11 18:39:05 -07002600 double coord_on_stack[NUM_STACK_ELEMS];
2601 double *coordinates = coord_on_stack;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002602
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002603 if (nargs > NUM_STACK_ELEMS) {
2604 coordinates = (double *) PyObject_Malloc(nargs * sizeof(double));
Zackery Spytz4c49da02018-12-07 03:11:30 -07002605 if (coordinates == NULL) {
2606 return PyErr_NoMemory();
2607 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002608 }
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002609 for (i = 0; i < nargs; i++) {
2610 item = args[i];
Raymond Hettingercfd735e2019-01-29 20:39:53 -08002611 ASSIGN_DOUBLE(x, item, error_exit);
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002612 x = fabs(x);
2613 coordinates[i] = x;
2614 found_nan |= Py_IS_NAN(x);
2615 if (x > max) {
2616 max = x;
2617 }
2618 }
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002619 result = vector_norm(nargs, coordinates, max, found_nan);
Raymond Hettingerc630e102018-08-11 18:39:05 -07002620 if (coordinates != coord_on_stack) {
2621 PyObject_Free(coordinates);
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002622 }
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002623 return PyFloat_FromDouble(result);
Raymond Hettingerc630e102018-08-11 18:39:05 -07002624
2625 error_exit:
2626 if (coordinates != coord_on_stack) {
2627 PyObject_Free(coordinates);
2628 }
2629 return NULL;
Christian Heimes53876d92008-04-19 00:31:39 +00002630}
2631
Raymond Hettingerc630e102018-08-11 18:39:05 -07002632#undef NUM_STACK_ELEMS
2633
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002634PyDoc_STRVAR(math_hypot_doc,
2635 "hypot(*coordinates) -> value\n\n\
2636Multidimensional Euclidean distance from the origin to a point.\n\
2637\n\
2638Roughly equivalent to:\n\
2639 sqrt(sum(x**2 for x in coordinates))\n\
2640\n\
2641For a two dimensional point (x, y), gives the hypotenuse\n\
2642using the Pythagorean theorem: sqrt(x*x + y*y).\n\
2643\n\
2644For example, the hypotenuse of a 3/4/5 right triangle is:\n\
2645\n\
2646 >>> hypot(3.0, 4.0)\n\
2647 5.0\n\
2648");
Christian Heimes53876d92008-04-19 00:31:39 +00002649
2650/* pow can't use math_2, but needs its own wrapper: the problem is
2651 that an infinite result can arise either as a result of overflow
2652 (in which case OverflowError should be raised) or as a result of
2653 e.g. 0.**-5. (for which ValueError needs to be raised.)
2654*/
2655
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002656/*[clinic input]
2657math.pow
Christian Heimes53876d92008-04-19 00:31:39 +00002658
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002659 x: double
2660 y: double
2661 /
2662
2663Return x**y (x to the power of y).
2664[clinic start generated code]*/
2665
2666static PyObject *
2667math_pow_impl(PyObject *module, double x, double y)
2668/*[clinic end generated code: output=fff93e65abccd6b0 input=c26f1f6075088bfd]*/
2669{
2670 double r;
2671 int odd_y;
Christian Heimesa342c012008-04-20 21:01:16 +00002672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 /* deal directly with IEEE specials, to cope with problems on various
2674 platforms whose semantics don't exactly match C99 */
2675 r = 0.; /* silence compiler warning */
2676 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
2677 errno = 0;
2678 if (Py_IS_NAN(x))
2679 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
2680 else if (Py_IS_NAN(y))
2681 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
2682 else if (Py_IS_INFINITY(x)) {
2683 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
2684 if (y > 0.)
2685 r = odd_y ? x : fabs(x);
2686 else if (y == 0.)
2687 r = 1.;
2688 else /* y < 0. */
2689 r = odd_y ? copysign(0., x) : 0.;
2690 }
2691 else if (Py_IS_INFINITY(y)) {
2692 if (fabs(x) == 1.0)
2693 r = 1.;
2694 else if (y > 0. && fabs(x) > 1.0)
2695 r = y;
2696 else if (y < 0. && fabs(x) < 1.0) {
2697 r = -y; /* result is +inf */
2698 if (x == 0.) /* 0**-inf: divide-by-zero */
2699 errno = EDOM;
2700 }
2701 else
2702 r = 0.;
2703 }
2704 }
2705 else {
2706 /* let libm handle finite**finite */
2707 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002708 r = pow(x, y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002709 /* a NaN result should arise only from (-ve)**(finite
2710 non-integer); in this case we want to raise ValueError. */
2711 if (!Py_IS_FINITE(r)) {
2712 if (Py_IS_NAN(r)) {
2713 errno = EDOM;
2714 }
2715 /*
2716 an infinite result here arises either from:
2717 (A) (+/-0.)**negative (-> divide-by-zero)
2718 (B) overflow of x**y with x and y finite
2719 */
2720 else if (Py_IS_INFINITY(r)) {
2721 if (x == 0.)
2722 errno = EDOM;
2723 else
2724 errno = ERANGE;
2725 }
2726 }
2727 }
Christian Heimes53876d92008-04-19 00:31:39 +00002728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 if (errno && is_error(r))
2730 return NULL;
2731 else
2732 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00002733}
2734
Christian Heimes53876d92008-04-19 00:31:39 +00002735
Christian Heimes072c0f12008-01-03 23:01:04 +00002736static const double degToRad = Py_MATH_PI / 180.0;
2737static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002738
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002739/*[clinic input]
2740math.degrees
2741
2742 x: double
2743 /
2744
2745Convert angle x from radians to degrees.
2746[clinic start generated code]*/
2747
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002748static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002749math_degrees_impl(PyObject *module, double x)
2750/*[clinic end generated code: output=7fea78b294acd12f input=81e016555d6e3660]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002751{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002752 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002753}
2754
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002755
2756/*[clinic input]
2757math.radians
2758
2759 x: double
2760 /
2761
2762Convert angle x from degrees to radians.
2763[clinic start generated code]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002764
2765static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002766math_radians_impl(PyObject *module, double x)
2767/*[clinic end generated code: output=34daa47caf9b1590 input=91626fc489fe3d63]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002768{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 return PyFloat_FromDouble(x * degToRad);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002770}
2771
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002772
2773/*[clinic input]
2774math.isfinite
2775
2776 x: double
2777 /
2778
2779Return True if x is neither an infinity nor a NaN, and False otherwise.
2780[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002781
Christian Heimes072c0f12008-01-03 23:01:04 +00002782static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002783math_isfinite_impl(PyObject *module, double x)
2784/*[clinic end generated code: output=8ba1f396440c9901 input=46967d254812e54a]*/
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002785{
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002786 return PyBool_FromLong((long)Py_IS_FINITE(x));
2787}
2788
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002789
2790/*[clinic input]
2791math.isnan
2792
2793 x: double
2794 /
2795
2796Return True if x is a NaN (not a number), and False otherwise.
2797[clinic start generated code]*/
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002798
2799static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002800math_isnan_impl(PyObject *module, double x)
2801/*[clinic end generated code: output=f537b4d6df878c3e input=935891e66083f46a]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002803 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00002804}
2805
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002806
2807/*[clinic input]
2808math.isinf
2809
2810 x: double
2811 /
2812
2813Return True if x is a positive or negative infinity, and False otherwise.
2814[clinic start generated code]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002815
2816static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002817math_isinf_impl(PyObject *module, double x)
2818/*[clinic end generated code: output=9f00cbec4de7b06b input=32630e4212cf961f]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002820 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00002821}
2822
Christian Heimes072c0f12008-01-03 23:01:04 +00002823
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002824/*[clinic input]
2825math.isclose -> bool
2826
2827 a: double
2828 b: double
2829 *
2830 rel_tol: double = 1e-09
2831 maximum difference for being considered "close", relative to the
2832 magnitude of the input values
2833 abs_tol: double = 0.0
2834 maximum difference for being considered "close", regardless of the
2835 magnitude of the input values
2836
2837Determine whether two floating point numbers are close in value.
2838
2839Return True if a is close in value to b, and False otherwise.
2840
2841For the values to be considered close, the difference between them
2842must be smaller than at least one of the tolerances.
2843
2844-inf, inf and NaN behave similarly to the IEEE 754 Standard. That
2845is, NaN is not close to anything, even itself. inf and -inf are
2846only close to themselves.
2847[clinic start generated code]*/
2848
2849static int
2850math_isclose_impl(PyObject *module, double a, double b, double rel_tol,
2851 double abs_tol)
2852/*[clinic end generated code: output=b73070207511952d input=f28671871ea5bfba]*/
Tal Einatd5519ed2015-05-31 22:05:00 +03002853{
Tal Einatd5519ed2015-05-31 22:05:00 +03002854 double diff = 0.0;
Tal Einatd5519ed2015-05-31 22:05:00 +03002855
2856 /* sanity check on the inputs */
2857 if (rel_tol < 0.0 || abs_tol < 0.0 ) {
2858 PyErr_SetString(PyExc_ValueError,
2859 "tolerances must be non-negative");
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002860 return -1;
Tal Einatd5519ed2015-05-31 22:05:00 +03002861 }
2862
2863 if ( a == b ) {
2864 /* short circuit exact equality -- needed to catch two infinities of
2865 the same sign. And perhaps speeds things up a bit sometimes.
2866 */
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002867 return 1;
Tal Einatd5519ed2015-05-31 22:05:00 +03002868 }
2869
2870 /* This catches the case of two infinities of opposite sign, or
2871 one infinity and one finite number. Two infinities of opposite
2872 sign would otherwise have an infinite relative tolerance.
2873 Two infinities of the same sign are caught by the equality check
2874 above.
2875 */
2876
2877 if (Py_IS_INFINITY(a) || Py_IS_INFINITY(b)) {
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002878 return 0;
Tal Einatd5519ed2015-05-31 22:05:00 +03002879 }
2880
2881 /* now do the regular computation
2882 this is essentially the "weak" test from the Boost library
2883 */
2884
2885 diff = fabs(b - a);
2886
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002887 return (((diff <= fabs(rel_tol * b)) ||
2888 (diff <= fabs(rel_tol * a))) ||
2889 (diff <= abs_tol));
Tal Einatd5519ed2015-05-31 22:05:00 +03002890}
2891
Pablo Galindo04114112019-03-09 19:18:08 +00002892static inline int
2893_check_long_mult_overflow(long a, long b) {
2894
2895 /* From Python2's int_mul code:
2896
2897 Integer overflow checking for * is painful: Python tried a couple ways, but
2898 they didn't work on all platforms, or failed in endcases (a product of
2899 -sys.maxint-1 has been a particular pain).
2900
2901 Here's another way:
2902
2903 The native long product x*y is either exactly right or *way* off, being
2904 just the last n bits of the true product, where n is the number of bits
2905 in a long (the delivered product is the true product plus i*2**n for
2906 some integer i).
2907
2908 The native double product (double)x * (double)y is subject to three
2909 rounding errors: on a sizeof(long)==8 box, each cast to double can lose
2910 info, and even on a sizeof(long)==4 box, the multiplication can lose info.
2911 But, unlike the native long product, it's not in *range* trouble: even
2912 if sizeof(long)==32 (256-bit longs), the product easily fits in the
2913 dynamic range of a double. So the leading 50 (or so) bits of the double
2914 product are correct.
2915
2916 We check these two ways against each other, and declare victory if they're
2917 approximately the same. Else, because the native long product is the only
2918 one that can lose catastrophic amounts of information, it's the native long
2919 product that must have overflowed.
2920
2921 */
2922
2923 long longprod = (long)((unsigned long)a * b);
2924 double doubleprod = (double)a * (double)b;
2925 double doubled_longprod = (double)longprod;
2926
2927 if (doubled_longprod == doubleprod) {
2928 return 0;
2929 }
2930
2931 const double diff = doubled_longprod - doubleprod;
2932 const double absdiff = diff >= 0.0 ? diff : -diff;
2933 const double absprod = doubleprod >= 0.0 ? doubleprod : -doubleprod;
2934
2935 if (32.0 * absdiff <= absprod) {
2936 return 0;
2937 }
2938
2939 return 1;
2940}
Tal Einatd5519ed2015-05-31 22:05:00 +03002941
Pablo Galindobc098512019-02-07 07:04:02 +00002942/*[clinic input]
2943math.prod
2944
2945 iterable: object
2946 /
2947 *
2948 start: object(c_default="NULL") = 1
2949
2950Calculate the product of all the elements in the input iterable.
2951
2952The default start value for the product is 1.
2953
2954When the iterable is empty, return the start value. This function is
2955intended specifically for use with numeric values and may reject
2956non-numeric types.
2957[clinic start generated code]*/
2958
2959static PyObject *
2960math_prod_impl(PyObject *module, PyObject *iterable, PyObject *start)
2961/*[clinic end generated code: output=36153bedac74a198 input=4c5ab0682782ed54]*/
2962{
2963 PyObject *result = start;
2964 PyObject *temp, *item, *iter;
2965
2966 iter = PyObject_GetIter(iterable);
2967 if (iter == NULL) {
2968 return NULL;
2969 }
2970
2971 if (result == NULL) {
2972 result = PyLong_FromLong(1);
2973 if (result == NULL) {
2974 Py_DECREF(iter);
2975 return NULL;
2976 }
2977 } else {
2978 Py_INCREF(result);
2979 }
2980#ifndef SLOW_PROD
2981 /* Fast paths for integers keeping temporary products in C.
2982 * Assumes all inputs are the same type.
2983 * If the assumption fails, default to use PyObjects instead.
2984 */
2985 if (PyLong_CheckExact(result)) {
2986 int overflow;
2987 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2988 /* If this already overflowed, don't even enter the loop. */
2989 if (overflow == 0) {
2990 Py_DECREF(result);
2991 result = NULL;
2992 }
2993 /* Loop over all the items in the iterable until we finish, we overflow
2994 * or we found a non integer element */
2995 while(result == NULL) {
2996 item = PyIter_Next(iter);
2997 if (item == NULL) {
2998 Py_DECREF(iter);
2999 if (PyErr_Occurred()) {
3000 return NULL;
3001 }
3002 return PyLong_FromLong(i_result);
3003 }
3004 if (PyLong_CheckExact(item)) {
3005 long b = PyLong_AsLongAndOverflow(item, &overflow);
Pablo Galindo04114112019-03-09 19:18:08 +00003006 if (overflow == 0 && !_check_long_mult_overflow(i_result, b)) {
3007 long x = i_result * b;
Pablo Galindobc098512019-02-07 07:04:02 +00003008 i_result = x;
3009 Py_DECREF(item);
3010 continue;
3011 }
3012 }
3013 /* Either overflowed or is not an int.
3014 * Restore real objects and process normally */
3015 result = PyLong_FromLong(i_result);
3016 if (result == NULL) {
3017 Py_DECREF(item);
3018 Py_DECREF(iter);
3019 return NULL;
3020 }
3021 temp = PyNumber_Multiply(result, item);
3022 Py_DECREF(result);
3023 Py_DECREF(item);
3024 result = temp;
3025 if (result == NULL) {
3026 Py_DECREF(iter);
3027 return NULL;
3028 }
3029 }
3030 }
3031
3032 /* Fast paths for floats keeping temporary products in C.
3033 * Assumes all inputs are the same type.
3034 * If the assumption fails, default to use PyObjects instead.
3035 */
3036 if (PyFloat_CheckExact(result)) {
3037 double f_result = PyFloat_AS_DOUBLE(result);
3038 Py_DECREF(result);
3039 result = NULL;
3040 while(result == NULL) {
3041 item = PyIter_Next(iter);
3042 if (item == NULL) {
3043 Py_DECREF(iter);
3044 if (PyErr_Occurred()) {
3045 return NULL;
3046 }
3047 return PyFloat_FromDouble(f_result);
3048 }
3049 if (PyFloat_CheckExact(item)) {
3050 f_result *= PyFloat_AS_DOUBLE(item);
3051 Py_DECREF(item);
3052 continue;
3053 }
3054 if (PyLong_CheckExact(item)) {
3055 long value;
3056 int overflow;
3057 value = PyLong_AsLongAndOverflow(item, &overflow);
3058 if (!overflow) {
3059 f_result *= (double)value;
3060 Py_DECREF(item);
3061 continue;
3062 }
3063 }
3064 result = PyFloat_FromDouble(f_result);
3065 if (result == NULL) {
3066 Py_DECREF(item);
3067 Py_DECREF(iter);
3068 return NULL;
3069 }
3070 temp = PyNumber_Multiply(result, item);
3071 Py_DECREF(result);
3072 Py_DECREF(item);
3073 result = temp;
3074 if (result == NULL) {
3075 Py_DECREF(iter);
3076 return NULL;
3077 }
3078 }
3079 }
3080#endif
3081 /* Consume rest of the iterable (if any) that could not be handled
3082 * by specialized functions above.*/
3083 for(;;) {
3084 item = PyIter_Next(iter);
3085 if (item == NULL) {
3086 /* error, or end-of-sequence */
3087 if (PyErr_Occurred()) {
3088 Py_DECREF(result);
3089 result = NULL;
3090 }
3091 break;
3092 }
3093 temp = PyNumber_Multiply(result, item);
3094 Py_DECREF(result);
3095 Py_DECREF(item);
3096 result = temp;
3097 if (result == NULL)
3098 break;
3099 }
3100 Py_DECREF(iter);
3101 return result;
3102}
3103
3104
Yash Aggarwal4a686502019-06-01 12:51:27 +05303105/*[clinic input]
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003106math.perm
3107
3108 n: object
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003109 k: object = None
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003110 /
3111
3112Number of ways to choose k items from n items without repetition and with order.
3113
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003114Evaluates to n! / (n - k)! when k <= n and evaluates
3115to zero when k > n.
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003116
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003117If k is not specified or is None, then k defaults to n
3118and the function returns n!.
3119
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003120Raises TypeError if either of the arguments are not integers.
3121Raises ValueError if either of the arguments are negative.
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003122[clinic start generated code]*/
3123
3124static PyObject *
3125math_perm_impl(PyObject *module, PyObject *n, PyObject *k)
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003126/*[clinic end generated code: output=e021a25469653e23 input=5311c5a00f359b53]*/
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003127{
3128 PyObject *result = NULL, *factor = NULL;
3129 int overflow, cmp;
3130 long long i, factors;
3131
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003132 if (k == Py_None) {
3133 return math_factorial(module, n);
3134 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003135 n = PyNumber_Index(n);
3136 if (n == NULL) {
3137 return NULL;
3138 }
3139 if (!PyLong_CheckExact(n)) {
3140 Py_SETREF(n, _PyLong_Copy((PyLongObject *)n));
3141 if (n == NULL) {
3142 return NULL;
3143 }
3144 }
3145 k = PyNumber_Index(k);
3146 if (k == NULL) {
3147 Py_DECREF(n);
3148 return NULL;
3149 }
3150 if (!PyLong_CheckExact(k)) {
3151 Py_SETREF(k, _PyLong_Copy((PyLongObject *)k));
3152 if (k == NULL) {
3153 Py_DECREF(n);
3154 return NULL;
3155 }
3156 }
3157
3158 if (Py_SIZE(n) < 0) {
3159 PyErr_SetString(PyExc_ValueError,
3160 "n must be a non-negative integer");
3161 goto error;
3162 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003163 if (Py_SIZE(k) < 0) {
3164 PyErr_SetString(PyExc_ValueError,
3165 "k must be a non-negative integer");
3166 goto error;
3167 }
3168
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003169 cmp = PyObject_RichCompareBool(n, k, Py_LT);
3170 if (cmp != 0) {
3171 if (cmp > 0) {
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003172 result = PyLong_FromLong(0);
3173 goto done;
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003174 }
3175 goto error;
3176 }
3177
3178 factors = PyLong_AsLongLongAndOverflow(k, &overflow);
3179 if (overflow > 0) {
3180 PyErr_Format(PyExc_OverflowError,
3181 "k must not exceed %lld",
3182 LLONG_MAX);
3183 goto error;
3184 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003185 else if (factors == -1) {
3186 /* k is nonnegative, so a return value of -1 can only indicate error */
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003187 goto error;
3188 }
3189
3190 if (factors == 0) {
3191 result = PyLong_FromLong(1);
3192 goto done;
3193 }
3194
3195 result = n;
3196 Py_INCREF(result);
3197 if (factors == 1) {
3198 goto done;
3199 }
3200
3201 factor = n;
3202 Py_INCREF(factor);
3203 for (i = 1; i < factors; ++i) {
3204 Py_SETREF(factor, PyNumber_Subtract(factor, _PyLong_One));
3205 if (factor == NULL) {
3206 goto error;
3207 }
3208 Py_SETREF(result, PyNumber_Multiply(result, factor));
3209 if (result == NULL) {
3210 goto error;
3211 }
3212 }
3213 Py_DECREF(factor);
3214
3215done:
3216 Py_DECREF(n);
3217 Py_DECREF(k);
3218 return result;
3219
3220error:
3221 Py_XDECREF(factor);
3222 Py_XDECREF(result);
3223 Py_DECREF(n);
3224 Py_DECREF(k);
3225 return NULL;
3226}
3227
3228
3229/*[clinic input]
Yash Aggarwal4a686502019-06-01 12:51:27 +05303230math.comb
3231
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003232 n: object
3233 k: object
3234 /
Yash Aggarwal4a686502019-06-01 12:51:27 +05303235
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003236Number of ways to choose k items from n items without repetition and without order.
Yash Aggarwal4a686502019-06-01 12:51:27 +05303237
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003238Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates
3239to zero when k > n.
Yash Aggarwal4a686502019-06-01 12:51:27 +05303240
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003241Also called the binomial coefficient because it is equivalent
3242to the coefficient of k-th term in polynomial expansion of the
3243expression (1 + x)**n.
3244
3245Raises TypeError if either of the arguments are not integers.
3246Raises ValueError if either of the arguments are negative.
Yash Aggarwal4a686502019-06-01 12:51:27 +05303247
3248[clinic start generated code]*/
3249
3250static PyObject *
3251math_comb_impl(PyObject *module, PyObject *n, PyObject *k)
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003252/*[clinic end generated code: output=bd2cec8d854f3493 input=9a05315af2518709]*/
Yash Aggarwal4a686502019-06-01 12:51:27 +05303253{
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003254 PyObject *result = NULL, *factor = NULL, *temp;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303255 int overflow, cmp;
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003256 long long i, factors;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303257
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003258 n = PyNumber_Index(n);
3259 if (n == NULL) {
3260 return NULL;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303261 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003262 if (!PyLong_CheckExact(n)) {
3263 Py_SETREF(n, _PyLong_Copy((PyLongObject *)n));
3264 if (n == NULL) {
3265 return NULL;
3266 }
3267 }
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003268 k = PyNumber_Index(k);
3269 if (k == NULL) {
3270 Py_DECREF(n);
3271 return NULL;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303272 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003273 if (!PyLong_CheckExact(k)) {
3274 Py_SETREF(k, _PyLong_Copy((PyLongObject *)k));
3275 if (k == NULL) {
3276 Py_DECREF(n);
3277 return NULL;
3278 }
3279 }
Yash Aggarwal4a686502019-06-01 12:51:27 +05303280
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003281 if (Py_SIZE(n) < 0) {
3282 PyErr_SetString(PyExc_ValueError,
3283 "n must be a non-negative integer");
3284 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303285 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003286 if (Py_SIZE(k) < 0) {
3287 PyErr_SetString(PyExc_ValueError,
3288 "k must be a non-negative integer");
3289 goto error;
3290 }
3291
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003292 /* k = min(k, n - k) */
3293 temp = PyNumber_Subtract(n, k);
3294 if (temp == NULL) {
3295 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303296 }
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003297 if (Py_SIZE(temp) < 0) {
3298 Py_DECREF(temp);
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003299 result = PyLong_FromLong(0);
3300 goto done;
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003301 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003302 cmp = PyObject_RichCompareBool(temp, k, Py_LT);
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003303 if (cmp > 0) {
3304 Py_SETREF(k, temp);
Yash Aggarwal4a686502019-06-01 12:51:27 +05303305 }
3306 else {
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003307 Py_DECREF(temp);
3308 if (cmp < 0) {
3309 goto error;
3310 }
Yash Aggarwal4a686502019-06-01 12:51:27 +05303311 }
3312
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003313 factors = PyLong_AsLongLongAndOverflow(k, &overflow);
3314 if (overflow > 0) {
Yash Aggarwal4a686502019-06-01 12:51:27 +05303315 PyErr_Format(PyExc_OverflowError,
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003316 "min(n - k, k) must not exceed %lld",
Yash Aggarwal4a686502019-06-01 12:51:27 +05303317 LLONG_MAX);
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003318 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303319 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003320 if (factors == -1) {
3321 /* k is nonnegative, so a return value of -1 can only indicate error */
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003322 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303323 }
3324
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003325 if (factors == 0) {
3326 result = PyLong_FromLong(1);
3327 goto done;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303328 }
3329
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003330 result = n;
3331 Py_INCREF(result);
3332 if (factors == 1) {
3333 goto done;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303334 }
3335
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003336 factor = n;
3337 Py_INCREF(factor);
3338 for (i = 1; i < factors; ++i) {
3339 Py_SETREF(factor, PyNumber_Subtract(factor, _PyLong_One));
3340 if (factor == NULL) {
3341 goto error;
3342 }
3343 Py_SETREF(result, PyNumber_Multiply(result, factor));
3344 if (result == NULL) {
3345 goto error;
3346 }
Yash Aggarwal4a686502019-06-01 12:51:27 +05303347
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003348 temp = PyLong_FromUnsignedLongLong((unsigned long long)i + 1);
3349 if (temp == NULL) {
3350 goto error;
3351 }
3352 Py_SETREF(result, PyNumber_FloorDivide(result, temp));
3353 Py_DECREF(temp);
3354 if (result == NULL) {
3355 goto error;
3356 }
3357 }
3358 Py_DECREF(factor);
Yash Aggarwal4a686502019-06-01 12:51:27 +05303359
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003360done:
3361 Py_DECREF(n);
3362 Py_DECREF(k);
3363 return result;
3364
3365error:
3366 Py_XDECREF(factor);
3367 Py_XDECREF(result);
3368 Py_DECREF(n);
3369 Py_DECREF(k);
Yash Aggarwal4a686502019-06-01 12:51:27 +05303370 return NULL;
3371}
3372
3373
Victor Stinner100fafc2020-01-12 02:15:42 +01003374/*[clinic input]
3375math.nextafter
3376
3377 x: double
3378 y: double
3379 /
3380
3381Return the next floating-point value after x towards y.
3382[clinic start generated code]*/
3383
3384static PyObject *
3385math_nextafter_impl(PyObject *module, double x, double y)
3386/*[clinic end generated code: output=750c8266c1c540ce input=02b2d50cd1d9f9b6]*/
3387{
Victor Stinner85ead4f2020-01-21 11:14:10 +01003388#if defined(_AIX)
3389 if (x == y) {
3390 /* On AIX 7.1, libm nextafter(-0.0, +0.0) returns -0.0.
3391 Bug fixed in bos.adt.libm 7.2.2.0 by APAR IV95512. */
3392 return PyFloat_FromDouble(y);
3393 }
3394#endif
3395 return PyFloat_FromDouble(nextafter(x, y));
Victor Stinner100fafc2020-01-12 02:15:42 +01003396}
3397
3398
Victor Stinner0b2ab212020-01-13 12:44:35 +01003399/*[clinic input]
3400math.ulp -> double
3401
3402 x: double
3403 /
3404
3405Return the value of the least significant bit of the float x.
3406[clinic start generated code]*/
3407
3408static double
3409math_ulp_impl(PyObject *module, double x)
3410/*[clinic end generated code: output=f5207867a9384dd4 input=31f9bfbbe373fcaa]*/
3411{
3412 if (Py_IS_NAN(x)) {
3413 return x;
3414 }
3415 x = fabs(x);
3416 if (Py_IS_INFINITY(x)) {
3417 return x;
3418 }
3419 double inf = m_inf();
3420 double x2 = nextafter(x, inf);
3421 if (Py_IS_INFINITY(x2)) {
3422 /* special case: x is the largest positive representable float */
3423 x2 = nextafter(x, -inf);
3424 return x - x2;
3425 }
3426 return x2 - x;
3427}
3428
Dong-hee Na5be82412020-03-31 23:33:22 +09003429static int
3430math_exec(PyObject *module)
3431{
3432 if (PyModule_AddObject(module, "pi", PyFloat_FromDouble(Py_MATH_PI)) < 0) {
3433 return -1;
3434 }
3435 if (PyModule_AddObject(module, "e", PyFloat_FromDouble(Py_MATH_E)) < 0) {
3436 return -1;
3437 }
3438 // 2pi
3439 if (PyModule_AddObject(module, "tau", PyFloat_FromDouble(Py_MATH_TAU)) < 0) {
3440 return -1;
3441 }
3442 if (PyModule_AddObject(module, "inf", PyFloat_FromDouble(m_inf())) < 0) {
3443 return -1;
3444 }
3445#if !defined(PY_NO_SHORT_FLOAT_REPR) || defined(Py_NAN)
3446 if (PyModule_AddObject(module, "nan", PyFloat_FromDouble(m_nan())) < 0) {
3447 return -1;
3448 }
3449#endif
3450 return 0;
3451}
Victor Stinner0b2ab212020-01-13 12:44:35 +01003452
Barry Warsaw8b43b191996-12-09 22:32:36 +00003453static PyMethodDef math_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003454 {"acos", math_acos, METH_O, math_acos_doc},
3455 {"acosh", math_acosh, METH_O, math_acosh_doc},
3456 {"asin", math_asin, METH_O, math_asin_doc},
3457 {"asinh", math_asinh, METH_O, math_asinh_doc},
3458 {"atan", math_atan, METH_O, math_atan_doc},
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003459 {"atan2", (PyCFunction)(void(*)(void))math_atan2, METH_FASTCALL, math_atan2_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003460 {"atanh", math_atanh, METH_O, math_atanh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003461 MATH_CEIL_METHODDEF
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003462 {"copysign", (PyCFunction)(void(*)(void))math_copysign, METH_FASTCALL, math_copysign_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003463 {"cos", math_cos, METH_O, math_cos_doc},
3464 {"cosh", math_cosh, METH_O, math_cosh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003465 MATH_DEGREES_METHODDEF
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07003466 MATH_DIST_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003467 {"erf", math_erf, METH_O, math_erf_doc},
3468 {"erfc", math_erfc, METH_O, math_erfc_doc},
3469 {"exp", math_exp, METH_O, math_exp_doc},
3470 {"expm1", math_expm1, METH_O, math_expm1_doc},
3471 {"fabs", math_fabs, METH_O, math_fabs_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003472 MATH_FACTORIAL_METHODDEF
3473 MATH_FLOOR_METHODDEF
3474 MATH_FMOD_METHODDEF
3475 MATH_FREXP_METHODDEF
3476 MATH_FSUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003477 {"gamma", math_gamma, METH_O, math_gamma_doc},
Serhiy Storchaka559e7f12020-02-23 13:21:29 +02003478 {"gcd", (PyCFunction)(void(*)(void))math_gcd, METH_FASTCALL, math_gcd_doc},
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003479 {"hypot", (PyCFunction)(void(*)(void))math_hypot, METH_FASTCALL, math_hypot_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003480 MATH_ISCLOSE_METHODDEF
3481 MATH_ISFINITE_METHODDEF
3482 MATH_ISINF_METHODDEF
3483 MATH_ISNAN_METHODDEF
Mark Dickinson73934b92019-05-18 12:29:50 +01003484 MATH_ISQRT_METHODDEF
Serhiy Storchaka559e7f12020-02-23 13:21:29 +02003485 {"lcm", (PyCFunction)(void(*)(void))math_lcm, METH_FASTCALL, math_lcm_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003486 MATH_LDEXP_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003487 {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003488 MATH_LOG_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003489 {"log1p", math_log1p, METH_O, math_log1p_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003490 MATH_LOG10_METHODDEF
3491 MATH_LOG2_METHODDEF
3492 MATH_MODF_METHODDEF
3493 MATH_POW_METHODDEF
3494 MATH_RADIANS_METHODDEF
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003495 {"remainder", (PyCFunction)(void(*)(void))math_remainder, METH_FASTCALL, math_remainder_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003496 {"sin", math_sin, METH_O, math_sin_doc},
3497 {"sinh", math_sinh, METH_O, math_sinh_doc},
3498 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
3499 {"tan", math_tan, METH_O, math_tan_doc},
3500 {"tanh", math_tanh, METH_O, math_tanh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003501 MATH_TRUNC_METHODDEF
Pablo Galindobc098512019-02-07 07:04:02 +00003502 MATH_PROD_METHODDEF
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003503 MATH_PERM_METHODDEF
Yash Aggarwal4a686502019-06-01 12:51:27 +05303504 MATH_COMB_METHODDEF
Victor Stinner100fafc2020-01-12 02:15:42 +01003505 MATH_NEXTAFTER_METHODDEF
Victor Stinner0b2ab212020-01-13 12:44:35 +01003506 MATH_ULP_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003507 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003508};
3509
Dong-hee Na5be82412020-03-31 23:33:22 +09003510static PyModuleDef_Slot math_slots[] = {
3511 {Py_mod_exec, math_exec},
3512 {0, NULL}
3513};
Guido van Rossumc6e22901998-12-04 19:26:43 +00003514
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003515PyDoc_STRVAR(module_doc,
Ned Batchelder6faad352019-05-17 05:59:14 -04003516"This module provides access to the mathematical functions\n"
3517"defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00003518
Martin v. Löwis1a214512008-06-11 05:26:20 +00003519static struct PyModuleDef mathmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003520 PyModuleDef_HEAD_INIT,
Dong-hee Na5be82412020-03-31 23:33:22 +09003521 .m_name = "math",
3522 .m_doc = module_doc,
3523 .m_size = 0,
3524 .m_methods = math_methods,
3525 .m_slots = math_slots,
Martin v. Löwis1a214512008-06-11 05:26:20 +00003526};
3527
Mark Hammondfe51c6d2002-08-02 02:27:13 +00003528PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003529PyInit_math(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003530{
Dong-hee Na5be82412020-03-31 23:33:22 +09003531 return PyModuleDef_Init(&mathmodule);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003532}