blob: 5b96631d633c15bf46f6db1c476808d3ba7d1206 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Math module -- standard C math library functions, pi and e */
2
Christian Heimes53876d92008-04-19 00:31:39 +00003/* Here are some comments from Tim Peters, extracted from the
4 discussion attached to http://bugs.python.org/issue1640. They
5 describe the general aims of the math module with respect to
6 special values, IEEE-754 floating-point exceptions, and Python
7 exceptions.
8
9These are the "spirit of 754" rules:
10
111. If the mathematical result is a real number, but of magnitude too
12large to approximate by a machine float, overflow is signaled and the
13result is an infinity (with the appropriate sign).
14
152. If the mathematical result is a real number, but of magnitude too
16small to approximate by a machine float, underflow is signaled and the
17result is a zero (with the appropriate sign).
18
193. At a singularity (a value x such that the limit of f(y) as y
20approaches x exists and is an infinity), "divide by zero" is signaled
21and the result is an infinity (with the appropriate sign). This is
22complicated a little by that the left-side and right-side limits may
23not be the same; e.g., 1/x approaches +inf or -inf as x approaches 0
24from the positive or negative directions. In that specific case, the
25sign of the zero determines the result of 1/0.
26
274. At a point where a function has no defined result in the extended
28reals (i.e., the reals plus an infinity or two), invalid operation is
29signaled and a NaN is returned.
30
31And these are what Python has historically /tried/ to do (but not
32always successfully, as platform libm behavior varies a lot):
33
34For #1, raise OverflowError.
35
36For #2, return a zero (with the appropriate sign if that happens by
37accident ;-)).
38
39For #3 and #4, raise ValueError. It may have made sense to raise
40Python's ZeroDivisionError in #3, but historically that's only been
41raised for division by zero and mod by zero.
42
43*/
44
45/*
46 In general, on an IEEE-754 platform the aim is to follow the C99
47 standard, including Annex 'F', whenever possible. Where the
48 standard recommends raising the 'divide-by-zero' or 'invalid'
49 floating-point exceptions, Python should raise a ValueError. Where
50 the standard recommends raising 'overflow', Python should raise an
51 OverflowError. In all other circumstances a value should be
52 returned.
53 */
54
Barry Warsaw8b43b191996-12-09 22:32:36 +000055#include "Python.h"
Victor Stinnere9e7d282020-02-12 22:54:42 +010056#include "pycore_dtoa.h"
Mark Dickinson664b5112009-12-16 20:23:42 +000057#include "_math.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000058
Serhiy Storchakac9ea9332017-01-19 18:13:09 +020059#include "clinic/mathmodule.c.h"
60
61/*[clinic input]
62module math
63[clinic start generated code]*/
64/*[clinic end generated code: output=da39a3ee5e6b4b0d input=76bc7002685dd942]*/
65
66
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000067/*
68 sin(pi*x), giving accurate results for all finite x (especially x
69 integral or close to an integer). This is here for use in the
70 reflection formula for the gamma function. It conforms to IEEE
71 754-2008 for finite arguments, but not for infinities or nans.
72*/
Tim Petersa40c7932001-09-05 22:36:56 +000073
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000074static const double pi = 3.141592653589793238462643383279502884197;
Mark Dickinson9c91eb82010-07-07 16:17:31 +000075static const double logpi = 1.144729885849400174143427351353058711647;
Louie Lu7a264642017-03-31 01:05:10 +080076#if !defined(HAVE_ERF) || !defined(HAVE_ERFC)
77static const double sqrtpi = 1.772453850905516027298167483341145182798;
78#endif /* !defined(HAVE_ERF) || !defined(HAVE_ERFC) */
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000079
Raymond Hettingercfd735e2019-01-29 20:39:53 -080080
81/* Version of PyFloat_AsDouble() with in-line fast paths
82 for exact floats and integers. Gives a substantial
83 speed improvement for extracting float arguments.
84*/
85
86#define ASSIGN_DOUBLE(target_var, obj, error_label) \
87 if (PyFloat_CheckExact(obj)) { \
88 target_var = PyFloat_AS_DOUBLE(obj); \
89 } \
90 else if (PyLong_CheckExact(obj)) { \
91 target_var = PyLong_AsDouble(obj); \
92 if (target_var == -1.0 && PyErr_Occurred()) { \
93 goto error_label; \
94 } \
95 } \
96 else { \
97 target_var = PyFloat_AsDouble(obj); \
98 if (target_var == -1.0 && PyErr_Occurred()) { \
99 goto error_label; \
100 } \
101 }
102
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000103static double
Dima Pasechnikf57cd822019-02-26 06:36:11 +0000104m_sinpi(double x)
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000105{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 double y, r;
107 int n;
108 /* this function should only ever be called for finite arguments */
109 assert(Py_IS_FINITE(x));
110 y = fmod(fabs(x), 2.0);
111 n = (int)round(2.0*y);
112 assert(0 <= n && n <= 4);
113 switch (n) {
114 case 0:
115 r = sin(pi*y);
116 break;
117 case 1:
118 r = cos(pi*(y-0.5));
119 break;
120 case 2:
121 /* N.B. -sin(pi*(y-1.0)) is *not* equivalent: it would give
122 -0.0 instead of 0.0 when y == 1.0. */
123 r = sin(pi*(1.0-y));
124 break;
125 case 3:
126 r = -cos(pi*(y-1.5));
127 break;
128 case 4:
129 r = sin(pi*(y-2.0));
130 break;
131 default:
Barry Warsawb2e57942017-09-14 18:13:16 -0700132 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 }
134 return copysign(1.0, x)*r;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000135}
136
137/* Implementation of the real gamma function. In extensive but non-exhaustive
138 random tests, this function proved accurate to within <= 10 ulps across the
139 entire float domain. Note that accuracy may depend on the quality of the
140 system math functions, the pow function in particular. Special cases
141 follow C99 annex F. The parameters and method are tailored to platforms
142 whose double format is the IEEE 754 binary64 format.
143
144 Method: for x > 0.0 we use the Lanczos approximation with parameters N=13
145 and g=6.024680040776729583740234375; these parameters are amongst those
146 used by the Boost library. Following Boost (again), we re-express the
147 Lanczos sum as a rational function, and compute it that way. The
148 coefficients below were computed independently using MPFR, and have been
149 double-checked against the coefficients in the Boost source code.
150
151 For x < 0.0 we use the reflection formula.
152
153 There's one minor tweak that deserves explanation: Lanczos' formula for
154 Gamma(x) involves computing pow(x+g-0.5, x-0.5) / exp(x+g-0.5). For many x
155 values, x+g-0.5 can be represented exactly. However, in cases where it
156 can't be represented exactly the small error in x+g-0.5 can be magnified
157 significantly by the pow and exp calls, especially for large x. A cheap
158 correction is to multiply by (1 + e*g/(x+g-0.5)), where e is the error
159 involved in the computation of x+g-0.5 (that is, e = computed value of
160 x+g-0.5 - exact value of x+g-0.5). Here's the proof:
161
162 Correction factor
163 -----------------
164 Write x+g-0.5 = y-e, where y is exactly representable as an IEEE 754
165 double, and e is tiny. Then:
166
167 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) = pow(y-e, x-0.5)/exp(y-e)
168 = pow(y, x-0.5)/exp(y) * C,
169
170 where the correction_factor C is given by
171
172 C = pow(1-e/y, x-0.5) * exp(e)
173
174 Since e is tiny, pow(1-e/y, x-0.5) ~ 1-(x-0.5)*e/y, and exp(x) ~ 1+e, so:
175
176 C ~ (1-(x-0.5)*e/y) * (1+e) ~ 1 + e*(y-(x-0.5))/y
177
178 But y-(x-0.5) = g+e, and g+e ~ g. So we get C ~ 1 + e*g/y, and
179
180 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) ~ pow(y, x-0.5)/exp(y) * (1 + e*g/y),
181
182 Note that for accuracy, when computing r*C it's better to do
183
184 r + e*g/y*r;
185
186 than
187
188 r * (1 + e*g/y);
189
190 since the addition in the latter throws away most of the bits of
191 information in e*g/y.
192*/
193
194#define LANCZOS_N 13
195static const double lanczos_g = 6.024680040776729583740234375;
196static const double lanczos_g_minus_half = 5.524680040776729583740234375;
197static const double lanczos_num_coeffs[LANCZOS_N] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 23531376880.410759688572007674451636754734846804940,
199 42919803642.649098768957899047001988850926355848959,
200 35711959237.355668049440185451547166705960488635843,
201 17921034426.037209699919755754458931112671403265390,
202 6039542586.3520280050642916443072979210699388420708,
203 1439720407.3117216736632230727949123939715485786772,
204 248874557.86205415651146038641322942321632125127801,
205 31426415.585400194380614231628318205362874684987640,
206 2876370.6289353724412254090516208496135991145378768,
207 186056.26539522349504029498971604569928220784236328,
208 8071.6720023658162106380029022722506138218516325024,
209 210.82427775157934587250973392071336271166969580291,
210 2.5066282746310002701649081771338373386264310793408
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000211};
212
213/* denominator is x*(x+1)*...*(x+LANCZOS_N-2) */
214static const double lanczos_den_coeffs[LANCZOS_N] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000215 0.0, 39916800.0, 120543840.0, 150917976.0, 105258076.0, 45995730.0,
216 13339535.0, 2637558.0, 357423.0, 32670.0, 1925.0, 66.0, 1.0};
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000217
218/* gamma values for small positive integers, 1 though NGAMMA_INTEGRAL */
219#define NGAMMA_INTEGRAL 23
220static const double gamma_integral[NGAMMA_INTEGRAL] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0,
222 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0,
223 1307674368000.0, 20922789888000.0, 355687428096000.0,
224 6402373705728000.0, 121645100408832000.0, 2432902008176640000.0,
225 51090942171709440000.0, 1124000727777607680000.0,
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000226};
227
228/* Lanczos' sum L_g(x), for positive x */
229
230static double
231lanczos_sum(double x)
232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 double num = 0.0, den = 0.0;
234 int i;
235 assert(x > 0.0);
236 /* evaluate the rational function lanczos_sum(x). For large
237 x, the obvious algorithm risks overflow, so we instead
238 rescale the denominator and numerator of the rational
239 function by x**(1-LANCZOS_N) and treat this as a
240 rational function in 1/x. This also reduces the error for
241 larger x values. The choice of cutoff point (5.0 below) is
242 somewhat arbitrary; in tests, smaller cutoff values than
243 this resulted in lower accuracy. */
244 if (x < 5.0) {
245 for (i = LANCZOS_N; --i >= 0; ) {
246 num = num * x + lanczos_num_coeffs[i];
247 den = den * x + lanczos_den_coeffs[i];
248 }
249 }
250 else {
251 for (i = 0; i < LANCZOS_N; i++) {
252 num = num / x + lanczos_num_coeffs[i];
253 den = den / x + lanczos_den_coeffs[i];
254 }
255 }
256 return num/den;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000257}
258
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +0000259/* Constant for +infinity, generated in the same way as float('inf'). */
260
261static double
262m_inf(void)
263{
264#ifndef PY_NO_SHORT_FLOAT_REPR
265 return _Py_dg_infinity(0);
266#else
267 return Py_HUGE_VAL;
268#endif
269}
270
271/* Constant nan value, generated in the same way as float('nan'). */
272/* We don't currently assume that Py_NAN is defined everywhere. */
273
274#if !defined(PY_NO_SHORT_FLOAT_REPR) || defined(Py_NAN)
275
276static double
277m_nan(void)
278{
279#ifndef PY_NO_SHORT_FLOAT_REPR
280 return _Py_dg_stdnan(0);
281#else
282 return Py_NAN;
283#endif
284}
285
286#endif
287
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000288static double
289m_tgamma(double x)
290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 double absx, r, y, z, sqrtpow;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 /* special cases */
294 if (!Py_IS_FINITE(x)) {
295 if (Py_IS_NAN(x) || x > 0.0)
296 return x; /* tgamma(nan) = nan, tgamma(inf) = inf */
297 else {
298 errno = EDOM;
299 return Py_NAN; /* tgamma(-inf) = nan, invalid */
300 }
301 }
302 if (x == 0.0) {
303 errno = EDOM;
Mark Dickinson50203a62011-09-25 15:26:43 +0100304 /* tgamma(+-0.0) = +-inf, divide-by-zero */
305 return copysign(Py_HUGE_VAL, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 /* integer arguments */
309 if (x == floor(x)) {
310 if (x < 0.0) {
311 errno = EDOM; /* tgamma(n) = nan, invalid for */
312 return Py_NAN; /* negative integers n */
313 }
314 if (x <= NGAMMA_INTEGRAL)
315 return gamma_integral[(int)x - 1];
316 }
317 absx = fabs(x);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 /* tiny arguments: tgamma(x) ~ 1/x for x near 0 */
320 if (absx < 1e-20) {
321 r = 1.0/x;
322 if (Py_IS_INFINITY(r))
323 errno = ERANGE;
324 return r;
325 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 /* large arguments: assuming IEEE 754 doubles, tgamma(x) overflows for
328 x > 200, and underflows to +-0.0 for x < -200, not a negative
329 integer. */
330 if (absx > 200.0) {
331 if (x < 0.0) {
Dima Pasechnikf57cd822019-02-26 06:36:11 +0000332 return 0.0/m_sinpi(x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 }
334 else {
335 errno = ERANGE;
336 return Py_HUGE_VAL;
337 }
338 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 y = absx + lanczos_g_minus_half;
341 /* compute error in sum */
342 if (absx > lanczos_g_minus_half) {
343 /* note: the correction can be foiled by an optimizing
344 compiler that (incorrectly) thinks that an expression like
345 a + b - a - b can be optimized to 0.0. This shouldn't
346 happen in a standards-conforming compiler. */
347 double q = y - absx;
348 z = q - lanczos_g_minus_half;
349 }
350 else {
351 double q = y - lanczos_g_minus_half;
352 z = q - absx;
353 }
354 z = z * lanczos_g / y;
355 if (x < 0.0) {
Dima Pasechnikf57cd822019-02-26 06:36:11 +0000356 r = -pi / m_sinpi(absx) / absx * exp(y) / lanczos_sum(absx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 r -= z * r;
358 if (absx < 140.0) {
359 r /= pow(y, absx - 0.5);
360 }
361 else {
362 sqrtpow = pow(y, absx / 2.0 - 0.25);
363 r /= sqrtpow;
364 r /= sqrtpow;
365 }
366 }
367 else {
368 r = lanczos_sum(absx) / exp(y);
369 r += z * r;
370 if (absx < 140.0) {
371 r *= pow(y, absx - 0.5);
372 }
373 else {
374 sqrtpow = pow(y, absx / 2.0 - 0.25);
375 r *= sqrtpow;
376 r *= sqrtpow;
377 }
378 }
379 if (Py_IS_INFINITY(r))
380 errno = ERANGE;
381 return r;
Guido van Rossum8832b621991-12-16 15:44:24 +0000382}
383
Christian Heimes53876d92008-04-19 00:31:39 +0000384/*
Mark Dickinson05d2e082009-12-11 20:17:17 +0000385 lgamma: natural log of the absolute value of the Gamma function.
386 For large arguments, Lanczos' formula works extremely well here.
387*/
388
389static double
390m_lgamma(double x)
391{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200392 double r;
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200393 double absx;
Mark Dickinson05d2e082009-12-11 20:17:17 +0000394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 /* special cases */
396 if (!Py_IS_FINITE(x)) {
397 if (Py_IS_NAN(x))
398 return x; /* lgamma(nan) = nan */
399 else
400 return Py_HUGE_VAL; /* lgamma(+-inf) = +inf */
401 }
Mark Dickinson05d2e082009-12-11 20:17:17 +0000402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 /* integer arguments */
404 if (x == floor(x) && x <= 2.0) {
405 if (x <= 0.0) {
406 errno = EDOM; /* lgamma(n) = inf, divide-by-zero for */
407 return Py_HUGE_VAL; /* integers n <= 0 */
408 }
409 else {
410 return 0.0; /* lgamma(1) = lgamma(2) = 0.0 */
411 }
412 }
Mark Dickinson05d2e082009-12-11 20:17:17 +0000413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 absx = fabs(x);
415 /* tiny arguments: lgamma(x) ~ -log(fabs(x)) for small x */
416 if (absx < 1e-20)
417 return -log(absx);
Mark Dickinson05d2e082009-12-11 20:17:17 +0000418
Mark Dickinson9c91eb82010-07-07 16:17:31 +0000419 /* Lanczos' formula. We could save a fraction of a ulp in accuracy by
420 having a second set of numerator coefficients for lanczos_sum that
421 absorbed the exp(-lanczos_g) term, and throwing out the lanczos_g
422 subtraction below; it's probably not worth it. */
423 r = log(lanczos_sum(absx)) - lanczos_g;
424 r += (absx - 0.5) * (log(absx + lanczos_g - 0.5) - 1);
425 if (x < 0.0)
426 /* Use reflection formula to get value for negative x. */
Dima Pasechnikf57cd822019-02-26 06:36:11 +0000427 r = logpi - log(fabs(m_sinpi(absx))) - log(absx) - r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 if (Py_IS_INFINITY(r))
429 errno = ERANGE;
430 return r;
Mark Dickinson05d2e082009-12-11 20:17:17 +0000431}
432
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200433#if !defined(HAVE_ERF) || !defined(HAVE_ERFC)
434
Mark Dickinson45f992a2009-12-19 11:20:49 +0000435/*
436 Implementations of the error function erf(x) and the complementary error
437 function erfc(x).
438
Brett Cannon45adb312016-01-15 09:38:24 -0800439 Method: we use a series approximation for erf for small x, and a continued
440 fraction approximation for erfc(x) for larger x;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000441 combined with the relations erf(-x) = -erf(x) and erfc(x) = 1.0 - erf(x),
442 this gives us erf(x) and erfc(x) for all x.
443
444 The series expansion used is:
445
446 erf(x) = x*exp(-x*x)/sqrt(pi) * [
447 2/1 + 4/3 x**2 + 8/15 x**4 + 16/105 x**6 + ...]
448
449 The coefficient of x**(2k-2) here is 4**k*factorial(k)/factorial(2*k).
450 This series converges well for smallish x, but slowly for larger x.
451
452 The continued fraction expansion used is:
453
454 erfc(x) = x*exp(-x*x)/sqrt(pi) * [1/(0.5 + x**2 -) 0.5/(2.5 + x**2 - )
455 3.0/(4.5 + x**2 - ) 7.5/(6.5 + x**2 - ) ...]
456
457 after the first term, the general term has the form:
458
459 k*(k-0.5)/(2*k+0.5 + x**2 - ...).
460
461 This expansion converges fast for larger x, but convergence becomes
462 infinitely slow as x approaches 0.0. The (somewhat naive) continued
463 fraction evaluation algorithm used below also risks overflow for large x;
464 but for large x, erfc(x) == 0.0 to within machine precision. (For
465 example, erfc(30.0) is approximately 2.56e-393).
466
467 Parameters: use series expansion for abs(x) < ERF_SERIES_CUTOFF and
468 continued fraction expansion for ERF_SERIES_CUTOFF <= abs(x) <
469 ERFC_CONTFRAC_CUTOFF. ERFC_SERIES_TERMS and ERFC_CONTFRAC_TERMS are the
470 numbers of terms to use for the relevant expansions. */
471
472#define ERF_SERIES_CUTOFF 1.5
473#define ERF_SERIES_TERMS 25
474#define ERFC_CONTFRAC_CUTOFF 30.0
475#define ERFC_CONTFRAC_TERMS 50
476
477/*
478 Error function, via power series.
479
480 Given a finite float x, return an approximation to erf(x).
481 Converges reasonably fast for small x.
482*/
483
484static double
485m_erf_series(double x)
486{
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000487 double x2, acc, fk, result;
488 int i, saved_errno;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 x2 = x * x;
491 acc = 0.0;
492 fk = (double)ERF_SERIES_TERMS + 0.5;
493 for (i = 0; i < ERF_SERIES_TERMS; i++) {
494 acc = 2.0 + x2 * acc / fk;
495 fk -= 1.0;
496 }
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000497 /* Make sure the exp call doesn't affect errno;
498 see m_erfc_contfrac for more. */
499 saved_errno = errno;
500 result = acc * x * exp(-x2) / sqrtpi;
501 errno = saved_errno;
502 return result;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000503}
504
505/*
506 Complementary error function, via continued fraction expansion.
507
508 Given a positive float x, return an approximation to erfc(x). Converges
509 reasonably fast for x large (say, x > 2.0), and should be safe from
510 overflow if x and nterms are not too large. On an IEEE 754 machine, with x
511 <= 30.0, we're safe up to nterms = 100. For x >= 30.0, erfc(x) is smaller
512 than the smallest representable nonzero float. */
513
514static double
515m_erfc_contfrac(double x)
516{
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000517 double x2, a, da, p, p_last, q, q_last, b, result;
518 int i, saved_errno;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 if (x >= ERFC_CONTFRAC_CUTOFF)
521 return 0.0;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 x2 = x*x;
524 a = 0.0;
525 da = 0.5;
526 p = 1.0; p_last = 0.0;
527 q = da + x2; q_last = 1.0;
528 for (i = 0; i < ERFC_CONTFRAC_TERMS; i++) {
529 double temp;
530 a += da;
531 da += 2.0;
532 b = da + x2;
533 temp = p; p = b*p - a*p_last; p_last = temp;
534 temp = q; q = b*q - a*q_last; q_last = temp;
535 }
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000536 /* Issue #8986: On some platforms, exp sets errno on underflow to zero;
537 save the current errno value so that we can restore it later. */
538 saved_errno = errno;
539 result = p / q * x * exp(-x2) / sqrtpi;
540 errno = saved_errno;
541 return result;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000542}
543
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200544#endif /* !defined(HAVE_ERF) || !defined(HAVE_ERFC) */
545
Mark Dickinson45f992a2009-12-19 11:20:49 +0000546/* Error function erf(x), for general x */
547
548static double
549m_erf(double x)
550{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200551#ifdef HAVE_ERF
552 return erf(x);
553#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 double absx, cf;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 if (Py_IS_NAN(x))
557 return x;
558 absx = fabs(x);
559 if (absx < ERF_SERIES_CUTOFF)
560 return m_erf_series(x);
561 else {
562 cf = m_erfc_contfrac(absx);
563 return x > 0.0 ? 1.0 - cf : cf - 1.0;
564 }
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200565#endif
Mark Dickinson45f992a2009-12-19 11:20:49 +0000566}
567
568/* Complementary error function erfc(x), for general x. */
569
570static double
571m_erfc(double x)
572{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200573#ifdef HAVE_ERFC
574 return erfc(x);
575#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 double absx, cf;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 if (Py_IS_NAN(x))
579 return x;
580 absx = fabs(x);
581 if (absx < ERF_SERIES_CUTOFF)
582 return 1.0 - m_erf_series(x);
583 else {
584 cf = m_erfc_contfrac(absx);
585 return x > 0.0 ? cf : 2.0 - cf;
586 }
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200587#endif
Mark Dickinson45f992a2009-12-19 11:20:49 +0000588}
Mark Dickinson05d2e082009-12-11 20:17:17 +0000589
590/*
Christian Heimese57950f2008-04-21 13:08:03 +0000591 wrapper for atan2 that deals directly with special cases before
592 delegating to the platform libm for the remaining cases. This
593 is necessary to get consistent behaviour across platforms.
594 Windows, FreeBSD and alpha Tru64 are amongst platforms that don't
595 always follow C99.
596*/
597
598static double
599m_atan2(double y, double x)
600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 if (Py_IS_NAN(x) || Py_IS_NAN(y))
602 return Py_NAN;
603 if (Py_IS_INFINITY(y)) {
604 if (Py_IS_INFINITY(x)) {
605 if (copysign(1., x) == 1.)
606 /* atan2(+-inf, +inf) == +-pi/4 */
607 return copysign(0.25*Py_MATH_PI, y);
608 else
609 /* atan2(+-inf, -inf) == +-pi*3/4 */
610 return copysign(0.75*Py_MATH_PI, y);
611 }
612 /* atan2(+-inf, x) == +-pi/2 for finite x */
613 return copysign(0.5*Py_MATH_PI, y);
614 }
615 if (Py_IS_INFINITY(x) || y == 0.) {
616 if (copysign(1., x) == 1.)
617 /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */
618 return copysign(0., y);
619 else
620 /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */
621 return copysign(Py_MATH_PI, y);
622 }
623 return atan2(y, x);
Christian Heimese57950f2008-04-21 13:08:03 +0000624}
625
Mark Dickinsona0ce3752017-04-05 18:34:27 +0100626
627/* IEEE 754-style remainder operation: x - n*y where n*y is the nearest
628 multiple of y to x, taking n even in the case of a tie. Assuming an IEEE 754
629 binary floating-point format, the result is always exact. */
630
631static double
632m_remainder(double x, double y)
633{
634 /* Deal with most common case first. */
635 if (Py_IS_FINITE(x) && Py_IS_FINITE(y)) {
636 double absx, absy, c, m, r;
637
638 if (y == 0.0) {
639 return Py_NAN;
640 }
641
642 absx = fabs(x);
643 absy = fabs(y);
644 m = fmod(absx, absy);
645
646 /*
647 Warning: some subtlety here. What we *want* to know at this point is
648 whether the remainder m is less than, equal to, or greater than half
649 of absy. However, we can't do that comparison directly because we
Mark Dickinson01484702019-07-13 16:50:03 +0100650 can't be sure that 0.5*absy is representable (the multiplication
Mark Dickinsona0ce3752017-04-05 18:34:27 +0100651 might incur precision loss due to underflow). So instead we compare
652 m with the complement c = absy - m: m < 0.5*absy if and only if m <
653 c, and so on. The catch is that absy - m might also not be
654 representable, but it turns out that it doesn't matter:
655
656 - if m > 0.5*absy then absy - m is exactly representable, by
657 Sterbenz's lemma, so m > c
658 - if m == 0.5*absy then again absy - m is exactly representable
659 and m == c
660 - if m < 0.5*absy then either (i) 0.5*absy is exactly representable,
661 in which case 0.5*absy < absy - m, so 0.5*absy <= c and hence m <
662 c, or (ii) absy is tiny, either subnormal or in the lowest normal
663 binade. Then absy - m is exactly representable and again m < c.
664 */
665
666 c = absy - m;
667 if (m < c) {
668 r = m;
669 }
670 else if (m > c) {
671 r = -c;
672 }
673 else {
674 /*
675 Here absx is exactly halfway between two multiples of absy,
676 and we need to choose the even multiple. x now has the form
677
678 absx = n * absy + m
679
680 for some integer n (recalling that m = 0.5*absy at this point).
681 If n is even we want to return m; if n is odd, we need to
682 return -m.
683
684 So
685
686 0.5 * (absx - m) = (n/2) * absy
687
688 and now reducing modulo absy gives us:
689
690 | m, if n is odd
691 fmod(0.5 * (absx - m), absy) = |
692 | 0, if n is even
693
694 Now m - 2.0 * fmod(...) gives the desired result: m
695 if n is even, -m if m is odd.
696
697 Note that all steps in fmod(0.5 * (absx - m), absy)
698 will be computed exactly, with no rounding error
699 introduced.
700 */
701 assert(m == c);
702 r = m - 2.0 * fmod(0.5 * (absx - m), absy);
703 }
704 return copysign(1.0, x) * r;
705 }
706
707 /* Special values. */
708 if (Py_IS_NAN(x)) {
709 return x;
710 }
711 if (Py_IS_NAN(y)) {
712 return y;
713 }
714 if (Py_IS_INFINITY(x)) {
715 return Py_NAN;
716 }
717 assert(Py_IS_INFINITY(y));
718 return x;
719}
720
721
Christian Heimese57950f2008-04-21 13:08:03 +0000722/*
Mark Dickinsone675f082008-12-11 21:56:00 +0000723 Various platforms (Solaris, OpenBSD) do nonstandard things for log(0),
724 log(-ve), log(NaN). Here are wrappers for log and log10 that deal with
725 special values directly, passing positive non-special values through to
726 the system log/log10.
727 */
728
729static double
730m_log(double x)
731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 if (Py_IS_FINITE(x)) {
733 if (x > 0.0)
734 return log(x);
735 errno = EDOM;
736 if (x == 0.0)
737 return -Py_HUGE_VAL; /* log(0) = -inf */
738 else
739 return Py_NAN; /* log(-ve) = nan */
740 }
741 else if (Py_IS_NAN(x))
742 return x; /* log(nan) = nan */
743 else if (x > 0.0)
744 return x; /* log(inf) = inf */
745 else {
746 errno = EDOM;
747 return Py_NAN; /* log(-inf) = nan */
748 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000749}
750
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200751/*
752 log2: log to base 2.
753
754 Uses an algorithm that should:
Mark Dickinson83b8c0b2011-05-09 08:40:20 +0100755
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200756 (a) produce exact results for powers of 2, and
Mark Dickinson83b8c0b2011-05-09 08:40:20 +0100757 (b) give a monotonic log2 (for positive finite floats),
758 assuming that the system log is monotonic.
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200759*/
760
761static double
762m_log2(double x)
763{
764 if (!Py_IS_FINITE(x)) {
765 if (Py_IS_NAN(x))
766 return x; /* log2(nan) = nan */
767 else if (x > 0.0)
768 return x; /* log2(+inf) = +inf */
769 else {
770 errno = EDOM;
771 return Py_NAN; /* log2(-inf) = nan, invalid-operation */
772 }
773 }
774
775 if (x > 0.0) {
Victor Stinner8f9f8d62011-05-09 12:45:41 +0200776#ifdef HAVE_LOG2
777 return log2(x);
778#else
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200779 double m;
780 int e;
781 m = frexp(x, &e);
782 /* We want log2(m * 2**e) == log(m) / log(2) + e. Care is needed when
783 * x is just greater than 1.0: in that case e is 1, log(m) is negative,
784 * and we get significant cancellation error from the addition of
785 * log(m) / log(2) to e. The slight rewrite of the expression below
786 * avoids this problem.
787 */
788 if (x >= 1.0) {
789 return log(2.0 * m) / log(2.0) + (e - 1);
790 }
791 else {
792 return log(m) / log(2.0) + e;
793 }
Victor Stinner8f9f8d62011-05-09 12:45:41 +0200794#endif
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200795 }
796 else if (x == 0.0) {
797 errno = EDOM;
798 return -Py_HUGE_VAL; /* log2(0) = -inf, divide-by-zero */
799 }
800 else {
801 errno = EDOM;
Mark Dickinson23442582011-05-09 08:05:00 +0100802 return Py_NAN; /* log2(-inf) = nan, invalid-operation */
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200803 }
804}
805
Mark Dickinsone675f082008-12-11 21:56:00 +0000806static double
807m_log10(double x)
808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 if (Py_IS_FINITE(x)) {
810 if (x > 0.0)
811 return log10(x);
812 errno = EDOM;
813 if (x == 0.0)
814 return -Py_HUGE_VAL; /* log10(0) = -inf */
815 else
816 return Py_NAN; /* log10(-ve) = nan */
817 }
818 else if (Py_IS_NAN(x))
819 return x; /* log10(nan) = nan */
820 else if (x > 0.0)
821 return x; /* log10(inf) = inf */
822 else {
823 errno = EDOM;
824 return Py_NAN; /* log10(-inf) = nan */
825 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000826}
827
828
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200829static PyObject *
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200830math_gcd(PyObject *module, PyObject * const *args, Py_ssize_t nargs)
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200831{
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200832 PyObject *res, *x;
833 Py_ssize_t i;
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300834
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200835 if (nargs == 0) {
836 return PyLong_FromLong(0);
837 }
838 res = PyNumber_Index(args[0]);
839 if (res == NULL) {
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300840 return NULL;
841 }
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200842 if (nargs == 1) {
843 Py_SETREF(res, PyNumber_Absolute(res));
844 return res;
845 }
846 for (i = 1; i < nargs; i++) {
847 x = PyNumber_Index(args[i]);
848 if (x == NULL) {
849 Py_DECREF(res);
850 return NULL;
851 }
852 if (res == _PyLong_One) {
853 /* Fast path: just check arguments.
854 It is okay to use identity comparison here. */
855 Py_DECREF(x);
856 continue;
857 }
858 Py_SETREF(res, _PyLong_GCD(res, x));
859 Py_DECREF(x);
860 if (res == NULL) {
861 return NULL;
862 }
863 }
864 return res;
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300865}
866
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200867PyDoc_STRVAR(math_gcd_doc,
868"gcd($module, *integers)\n"
869"--\n"
870"\n"
871"Greatest Common Divisor.");
872
873
874static PyObject *
875long_lcm(PyObject *a, PyObject *b)
876{
877 PyObject *g, *m, *f, *ab;
878
879 if (Py_SIZE(a) == 0 || Py_SIZE(b) == 0) {
880 return PyLong_FromLong(0);
881 }
882 g = _PyLong_GCD(a, b);
883 if (g == NULL) {
884 return NULL;
885 }
886 f = PyNumber_FloorDivide(a, g);
887 Py_DECREF(g);
888 if (f == NULL) {
889 return NULL;
890 }
891 m = PyNumber_Multiply(f, b);
892 Py_DECREF(f);
893 if (m == NULL) {
894 return NULL;
895 }
896 ab = PyNumber_Absolute(m);
897 Py_DECREF(m);
898 return ab;
899}
900
901
902static PyObject *
903math_lcm(PyObject *module, PyObject * const *args, Py_ssize_t nargs)
904{
905 PyObject *res, *x;
906 Py_ssize_t i;
907
908 if (nargs == 0) {
909 return PyLong_FromLong(1);
910 }
911 res = PyNumber_Index(args[0]);
912 if (res == NULL) {
913 return NULL;
914 }
915 if (nargs == 1) {
916 Py_SETREF(res, PyNumber_Absolute(res));
917 return res;
918 }
919 for (i = 1; i < nargs; i++) {
920 x = PyNumber_Index(args[i]);
921 if (x == NULL) {
922 Py_DECREF(res);
923 return NULL;
924 }
925 if (res == _PyLong_Zero) {
926 /* Fast path: just check arguments.
927 It is okay to use identity comparison here. */
928 Py_DECREF(x);
929 continue;
930 }
931 Py_SETREF(res, long_lcm(res, x));
932 Py_DECREF(x);
933 if (res == NULL) {
934 return NULL;
935 }
936 }
937 return res;
938}
939
940
941PyDoc_STRVAR(math_lcm_doc,
942"lcm($module, *integers)\n"
943"--\n"
944"\n"
945"Least Common Multiple.");
946
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300947
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000948/* Call is_error when errno != 0, and where x is the result libm
949 * returned. is_error will usually set up an exception and return
950 * true (1), but may return false (0) without setting up an exception.
951 */
952static int
953is_error(double x)
954{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 int result = 1; /* presumption of guilt */
956 assert(errno); /* non-zero errno is a precondition for calling */
957 if (errno == EDOM)
958 PyErr_SetString(PyExc_ValueError, "math domain error");
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 else if (errno == ERANGE) {
961 /* ANSI C generally requires libm functions to set ERANGE
962 * on overflow, but also generally *allows* them to set
963 * ERANGE on underflow too. There's no consistency about
964 * the latter across platforms.
965 * Alas, C99 never requires that errno be set.
966 * Here we suppress the underflow errors (libm functions
967 * should return a zero on underflow, and +- HUGE_VAL on
968 * overflow, so testing the result for zero suffices to
969 * distinguish the cases).
970 *
971 * On some platforms (Ubuntu/ia64) it seems that errno can be
972 * set to ERANGE for subnormal results that do *not* underflow
973 * to zero. So to be safe, we'll ignore ERANGE whenever the
974 * function result is less than one in absolute value.
975 */
976 if (fabs(x) < 1.0)
977 result = 0;
978 else
979 PyErr_SetString(PyExc_OverflowError,
980 "math range error");
981 }
982 else
983 /* Unexpected math error */
984 PyErr_SetFromErrno(PyExc_ValueError);
985 return result;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000986}
987
Mark Dickinsone675f082008-12-11 21:56:00 +0000988/*
Christian Heimes53876d92008-04-19 00:31:39 +0000989 math_1 is used to wrap a libm function f that takes a double
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200990 argument and returns a double.
Christian Heimes53876d92008-04-19 00:31:39 +0000991
992 The error reporting follows these rules, which are designed to do
993 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
994 platforms.
995
996 - a NaN result from non-NaN inputs causes ValueError to be raised
997 - an infinite result from finite inputs causes OverflowError to be
998 raised if can_overflow is 1, or raises ValueError if can_overflow
999 is 0.
1000 - if the result is finite and errno == EDOM then ValueError is
1001 raised
1002 - if the result is finite and nonzero and errno == ERANGE then
1003 OverflowError is raised
1004
1005 The last rule is used to catch overflow on platforms which follow
1006 C89 but for which HUGE_VAL is not an infinity.
1007
1008 For the majority of one-argument functions these rules are enough
1009 to ensure that Python's functions behave as specified in 'Annex F'
1010 of the C99 standard, with the 'invalid' and 'divide-by-zero'
1011 floating-point exceptions mapping to Python's ValueError and the
1012 'overflow' floating-point exception mapping to OverflowError.
1013 math_1 only works for functions that don't have singularities *and*
1014 the possibility of overflow; fortunately, that covers everything we
1015 care about right now.
1016*/
1017
Barry Warsaw8b43b191996-12-09 22:32:36 +00001018static PyObject *
Jeffrey Yasskinc2155832008-01-05 20:03:11 +00001019math_1_to_whatever(PyObject *arg, double (*func) (double),
Christian Heimes53876d92008-04-19 00:31:39 +00001020 PyObject *(*from_double_func) (double),
1021 int can_overflow)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001022{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 double x, r;
1024 x = PyFloat_AsDouble(arg);
1025 if (x == -1.0 && PyErr_Occurred())
1026 return NULL;
1027 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 r = (*func)(x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 if (Py_IS_NAN(r) && !Py_IS_NAN(x)) {
1030 PyErr_SetString(PyExc_ValueError,
1031 "math domain error"); /* invalid arg */
1032 return NULL;
1033 }
1034 if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) {
Benjamin Peterson2354a752012-03-13 16:13:09 -05001035 if (can_overflow)
1036 PyErr_SetString(PyExc_OverflowError,
1037 "math range error"); /* overflow */
1038 else
1039 PyErr_SetString(PyExc_ValueError,
1040 "math domain error"); /* singularity */
1041 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 }
1043 if (Py_IS_FINITE(r) && errno && is_error(r))
1044 /* this branch unnecessary on most platforms */
1045 return NULL;
Mark Dickinsonde429622008-05-01 00:19:23 +00001046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 return (*from_double_func)(r);
Christian Heimes53876d92008-04-19 00:31:39 +00001048}
1049
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001050/* variant of math_1, to be used when the function being wrapped is known to
1051 set errno properly (that is, errno = EDOM for invalid or divide-by-zero,
1052 errno = ERANGE for overflow). */
1053
1054static PyObject *
1055math_1a(PyObject *arg, double (*func) (double))
1056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 double x, r;
1058 x = PyFloat_AsDouble(arg);
1059 if (x == -1.0 && PyErr_Occurred())
1060 return NULL;
1061 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 r = (*func)(x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 if (errno && is_error(r))
1064 return NULL;
1065 return PyFloat_FromDouble(r);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001066}
1067
Christian Heimes53876d92008-04-19 00:31:39 +00001068/*
1069 math_2 is used to wrap a libm function f that takes two double
1070 arguments and returns a double.
1071
1072 The error reporting follows these rules, which are designed to do
1073 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
1074 platforms.
1075
1076 - a NaN result from non-NaN inputs causes ValueError to be raised
1077 - an infinite result from finite inputs causes OverflowError to be
1078 raised.
1079 - if the result is finite and errno == EDOM then ValueError is
1080 raised
1081 - if the result is finite and nonzero and errno == ERANGE then
1082 OverflowError is raised
1083
1084 The last rule is used to catch overflow on platforms which follow
1085 C89 but for which HUGE_VAL is not an infinity.
1086
1087 For most two-argument functions (copysign, fmod, hypot, atan2)
1088 these rules are enough to ensure that Python's functions behave as
1089 specified in 'Annex F' of the C99 standard, with the 'invalid' and
1090 'divide-by-zero' floating-point exceptions mapping to Python's
1091 ValueError and the 'overflow' floating-point exception mapping to
1092 OverflowError.
1093*/
1094
1095static PyObject *
1096math_1(PyObject *arg, double (*func) (double), int can_overflow)
1097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow);
Jeffrey Yasskinc2155832008-01-05 20:03:11 +00001099}
1100
1101static PyObject *
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02001102math_2(PyObject *const *args, Py_ssize_t nargs,
1103 double (*func) (double, double), const char *funcname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001104{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 double x, y, r;
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02001106 if (!_PyArg_CheckPositional(funcname, nargs, 2, 2))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 return NULL;
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02001108 x = PyFloat_AsDouble(args[0]);
Zackery Spytz5208b4b2020-03-14 04:45:32 -06001109 if (x == -1.0 && PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 return NULL;
Zackery Spytz5208b4b2020-03-14 04:45:32 -06001111 }
1112 y = PyFloat_AsDouble(args[1]);
1113 if (y == -1.0 && PyErr_Occurred()) {
1114 return NULL;
1115 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 r = (*func)(x, y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 if (Py_IS_NAN(r)) {
1119 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1120 errno = EDOM;
1121 else
1122 errno = 0;
1123 }
1124 else if (Py_IS_INFINITY(r)) {
1125 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
1126 errno = ERANGE;
1127 else
1128 errno = 0;
1129 }
1130 if (errno && is_error(r))
1131 return NULL;
1132 else
1133 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001134}
1135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136#define FUNC1(funcname, func, can_overflow, docstring) \
1137 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
1138 return math_1(args, func, can_overflow); \
1139 }\
1140 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142#define FUNC1A(funcname, func, docstring) \
1143 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
1144 return math_1a(args, func); \
1145 }\
1146 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001147
Fred Drake40c48682000-07-03 18:11:56 +00001148#define FUNC2(funcname, func, docstring) \
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02001149 static PyObject * math_##funcname(PyObject *self, PyObject *const *args, Py_ssize_t nargs) { \
1150 return math_2(args, nargs, func, #funcname); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 }\
1152 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001153
Christian Heimes53876d92008-04-19 00:31:39 +00001154FUNC1(acos, acos, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001155 "acos($module, x, /)\n--\n\n"
Giovanni Cappellottodc3f99f2019-07-13 09:59:55 -04001156 "Return the arc cosine (measured in radians) of x.\n\n"
1157 "The result is between 0 and pi.")
Mark Dickinsonf3718592009-12-21 15:27:41 +00001158FUNC1(acosh, m_acosh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001159 "acosh($module, x, /)\n--\n\n"
1160 "Return the inverse hyperbolic cosine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001161FUNC1(asin, asin, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001162 "asin($module, x, /)\n--\n\n"
Giovanni Cappellottodc3f99f2019-07-13 09:59:55 -04001163 "Return the arc sine (measured in radians) of x.\n\n"
1164 "The result is between -pi/2 and pi/2.")
Mark Dickinsonf3718592009-12-21 15:27:41 +00001165FUNC1(asinh, m_asinh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001166 "asinh($module, x, /)\n--\n\n"
1167 "Return the inverse hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001168FUNC1(atan, atan, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001169 "atan($module, x, /)\n--\n\n"
Giovanni Cappellottodc3f99f2019-07-13 09:59:55 -04001170 "Return the arc tangent (measured in radians) of x.\n\n"
1171 "The result is between -pi/2 and pi/2.")
Christian Heimese57950f2008-04-21 13:08:03 +00001172FUNC2(atan2, m_atan2,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001173 "atan2($module, y, x, /)\n--\n\n"
1174 "Return the arc tangent (measured in radians) of y/x.\n\n"
Tim Petersfe71f812001-08-07 22:10:00 +00001175 "Unlike atan(y/x), the signs of both x and y are considered.")
Mark Dickinsonf3718592009-12-21 15:27:41 +00001176FUNC1(atanh, m_atanh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001177 "atanh($module, x, /)\n--\n\n"
1178 "Return the inverse hyperbolic tangent of x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +00001179
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001180/*[clinic input]
1181math.ceil
1182
1183 x as number: object
1184 /
1185
1186Return the ceiling of x as an Integral.
1187
1188This is the smallest integer >= x.
1189[clinic start generated code]*/
1190
1191static PyObject *
1192math_ceil(PyObject *module, PyObject *number)
1193/*[clinic end generated code: output=6c3b8a78bc201c67 input=2725352806399cab]*/
1194{
Benjamin Petersonce798522012-01-22 11:24:29 -05001195 _Py_IDENTIFIER(__ceil__);
Guido van Rossum13e05de2007-08-23 22:56:55 +00001196
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001197 if (!PyFloat_CheckExact(number)) {
1198 PyObject *method = _PyObject_LookupSpecial(number, &PyId___ceil__);
1199 if (method != NULL) {
1200 PyObject *result = _PyObject_CallNoArg(method);
1201 Py_DECREF(method);
1202 return result;
1203 }
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001204 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 return NULL;
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001206 }
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001207 double x = PyFloat_AsDouble(number);
1208 if (x == -1.0 && PyErr_Occurred())
1209 return NULL;
1210
1211 return PyLong_FromDouble(ceil(x));
Guido van Rossum13e05de2007-08-23 22:56:55 +00001212}
1213
Christian Heimes072c0f12008-01-03 23:01:04 +00001214FUNC2(copysign, copysign,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001215 "copysign($module, x, y, /)\n--\n\n"
1216 "Return a float with the magnitude (absolute value) of x but the sign of y.\n\n"
1217 "On platforms that support signed zeros, copysign(1.0, -0.0)\n"
1218 "returns -1.0.\n")
Christian Heimes53876d92008-04-19 00:31:39 +00001219FUNC1(cos, cos, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001220 "cos($module, x, /)\n--\n\n"
1221 "Return the cosine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001222FUNC1(cosh, cosh, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001223 "cosh($module, x, /)\n--\n\n"
1224 "Return the hyperbolic cosine of x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +00001225FUNC1A(erf, m_erf,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001226 "erf($module, x, /)\n--\n\n"
1227 "Error function at x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +00001228FUNC1A(erfc, m_erfc,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001229 "erfc($module, x, /)\n--\n\n"
1230 "Complementary error function at x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001231FUNC1(exp, exp, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001232 "exp($module, x, /)\n--\n\n"
1233 "Return e raised to the power of x.")
Mark Dickinson664b5112009-12-16 20:23:42 +00001234FUNC1(expm1, m_expm1, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001235 "expm1($module, x, /)\n--\n\n"
1236 "Return exp(x)-1.\n\n"
Mark Dickinson664b5112009-12-16 20:23:42 +00001237 "This function avoids the loss of precision involved in the direct "
1238 "evaluation of exp(x)-1 for small x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001239FUNC1(fabs, fabs, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001240 "fabs($module, x, /)\n--\n\n"
1241 "Return the absolute value of the float x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +00001242
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001243/*[clinic input]
1244math.floor
1245
1246 x as number: object
1247 /
1248
1249Return the floor of x as an Integral.
1250
1251This is the largest integer <= x.
1252[clinic start generated code]*/
1253
1254static PyObject *
1255math_floor(PyObject *module, PyObject *number)
1256/*[clinic end generated code: output=c6a65c4884884b8a input=63af6b5d7ebcc3d6]*/
1257{
Benjamin Petersonce798522012-01-22 11:24:29 -05001258 _Py_IDENTIFIER(__floor__);
Guido van Rossum13e05de2007-08-23 22:56:55 +00001259
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001260 if (!PyFloat_CheckExact(number)) {
1261 PyObject *method = _PyObject_LookupSpecial(number, &PyId___floor__);
1262 if (method != NULL) {
1263 PyObject *result = _PyObject_CallNoArg(method);
1264 Py_DECREF(method);
1265 return result;
1266 }
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001267 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 return NULL;
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001269 }
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001270 double x = PyFloat_AsDouble(number);
1271 if (x == -1.0 && PyErr_Occurred())
1272 return NULL;
1273
1274 return PyLong_FromDouble(floor(x));
Guido van Rossum13e05de2007-08-23 22:56:55 +00001275}
1276
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001277FUNC1A(gamma, m_tgamma,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001278 "gamma($module, x, /)\n--\n\n"
1279 "Gamma function at x.")
Mark Dickinson05d2e082009-12-11 20:17:17 +00001280FUNC1A(lgamma, m_lgamma,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001281 "lgamma($module, x, /)\n--\n\n"
1282 "Natural logarithm of absolute value of Gamma function at x.")
Mark Dickinsonbe64d952010-07-07 16:21:29 +00001283FUNC1(log1p, m_log1p, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001284 "log1p($module, x, /)\n--\n\n"
1285 "Return the natural logarithm of 1+x (base e).\n\n"
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001286 "The result is computed in a way which is accurate for x near zero.")
Mark Dickinsona0ce3752017-04-05 18:34:27 +01001287FUNC2(remainder, m_remainder,
1288 "remainder($module, x, y, /)\n--\n\n"
1289 "Difference between x and the closest integer multiple of y.\n\n"
1290 "Return x - n*y where n*y is the closest integer multiple of y.\n"
1291 "In the case where x is exactly halfway between two multiples of\n"
1292 "y, the nearest even value of n is used. The result is always exact.")
Christian Heimes53876d92008-04-19 00:31:39 +00001293FUNC1(sin, sin, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001294 "sin($module, x, /)\n--\n\n"
1295 "Return the sine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001296FUNC1(sinh, sinh, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001297 "sinh($module, x, /)\n--\n\n"
1298 "Return the hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001299FUNC1(sqrt, sqrt, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001300 "sqrt($module, x, /)\n--\n\n"
1301 "Return the square root of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001302FUNC1(tan, tan, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001303 "tan($module, x, /)\n--\n\n"
1304 "Return the tangent of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001305FUNC1(tanh, tanh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001306 "tanh($module, x, /)\n--\n\n"
1307 "Return the hyperbolic tangent of x.")
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001308
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001309/* Precision summation function as msum() by Raymond Hettinger in
1310 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
1311 enhanced with the exact partials sum and roundoff from Mark
1312 Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
1313 See those links for more details, proofs and other references.
1314
1315 Note 1: IEEE 754R floating point semantics are assumed,
1316 but the current implementation does not re-establish special
1317 value semantics across iterations (i.e. handling -Inf + Inf).
1318
1319 Note 2: No provision is made for intermediate overflow handling;
Georg Brandlf78e02b2008-06-10 17:40:04 +00001320 therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001321 sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
1322 overflow of the first partial sum.
1323
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001324 Note 3: The intermediate values lo, yr, and hi are declared volatile so
1325 aggressive compilers won't algebraically reduce lo to always be exactly 0.0.
Georg Brandlf78e02b2008-06-10 17:40:04 +00001326 Also, the volatile declaration forces the values to be stored in memory as
1327 regular doubles instead of extended long precision (80-bit) values. This
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001328 prevents double rounding because any addition or subtraction of two doubles
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 can be resolved exactly into double-sized hi and lo values. As long as the
Georg Brandlf78e02b2008-06-10 17:40:04 +00001330 hi value gets forced into a double before yr and lo are computed, the extra
1331 bits in downstream extended precision operations (x87 for example) will be
1332 exactly zero and therefore can be losslessly stored back into a double,
1333 thereby preventing double rounding.
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001334
1335 Note 4: A similar implementation is in Modules/cmathmodule.c.
1336 Be sure to update both when making changes.
1337
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001338 Note 5: The signature of math.fsum() differs from builtins.sum()
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001339 because the start argument doesn't make sense in the context of
1340 accurate summation. Since the partials table is collapsed before
1341 returning a result, sum(seq2, start=sum(seq1)) may not equal the
1342 accurate result returned by sum(itertools.chain(seq1, seq2)).
1343*/
1344
1345#define NUM_PARTIALS 32 /* initial partials array size, on stack */
1346
1347/* Extend the partials array p[] by doubling its size. */
1348static int /* non-zero on error */
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001349_fsum_realloc(double **p_ptr, Py_ssize_t n,
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001350 double *ps, Py_ssize_t *m_ptr)
1351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 void *v = NULL;
1353 Py_ssize_t m = *m_ptr;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 m += m; /* double */
Victor Stinner049e5092014-08-17 22:20:00 +02001356 if (n < m && (size_t)m < ((size_t)PY_SSIZE_T_MAX / sizeof(double))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 double *p = *p_ptr;
1358 if (p == ps) {
1359 v = PyMem_Malloc(sizeof(double) * m);
1360 if (v != NULL)
1361 memcpy(v, ps, sizeof(double) * n);
1362 }
1363 else
1364 v = PyMem_Realloc(p, sizeof(double) * m);
1365 }
1366 if (v == NULL) { /* size overflow or no memory */
1367 PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
1368 return 1;
1369 }
1370 *p_ptr = (double*) v;
1371 *m_ptr = m;
1372 return 0;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001373}
1374
1375/* Full precision summation of a sequence of floats.
1376
1377 def msum(iterable):
1378 partials = [] # sorted, non-overlapping partial sums
1379 for x in iterable:
Mark Dickinsonfdb0acc2010-06-25 20:22:24 +00001380 i = 0
1381 for y in partials:
1382 if abs(x) < abs(y):
1383 x, y = y, x
1384 hi = x + y
1385 lo = y - (hi - x)
1386 if lo:
1387 partials[i] = lo
1388 i += 1
1389 x = hi
1390 partials[i:] = [x]
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001391 return sum_exact(partials)
1392
1393 Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
1394 are exactly equal to x+y. The inner loop applies hi/lo summation to each
1395 partial so that the list of partial sums remains exact.
1396
1397 Sum_exact() adds the partial sums exactly and correctly rounds the final
1398 result (using the round-half-to-even rule). The items in partials remain
1399 non-zero, non-special, non-overlapping and strictly increasing in
1400 magnitude, but possibly not all having the same sign.
1401
1402 Depends on IEEE 754 arithmetic guarantees and half-even rounding.
1403*/
1404
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001405/*[clinic input]
1406math.fsum
1407
1408 seq: object
1409 /
1410
1411Return an accurate floating point sum of values in the iterable seq.
1412
1413Assumes IEEE-754 floating point arithmetic.
1414[clinic start generated code]*/
1415
1416static PyObject *
1417math_fsum(PyObject *module, PyObject *seq)
1418/*[clinic end generated code: output=ba5c672b87fe34fc input=c51b7d8caf6f6e82]*/
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 PyObject *item, *iter, *sum = NULL;
1421 Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
1422 double x, y, t, ps[NUM_PARTIALS], *p = ps;
1423 double xsave, special_sum = 0.0, inf_sum = 0.0;
1424 volatile double hi, yr, lo;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 iter = PyObject_GetIter(seq);
1427 if (iter == NULL)
1428 return NULL;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 for(;;) { /* for x in iterable */
1431 assert(0 <= n && n <= m);
1432 assert((m == NUM_PARTIALS && p == ps) ||
1433 (m > NUM_PARTIALS && p != NULL));
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 item = PyIter_Next(iter);
1436 if (item == NULL) {
1437 if (PyErr_Occurred())
1438 goto _fsum_error;
1439 break;
1440 }
Raymond Hettingercfd735e2019-01-29 20:39:53 -08001441 ASSIGN_DOUBLE(x, item, error_with_item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 Py_DECREF(item);
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 xsave = x;
1445 for (i = j = 0; j < n; j++) { /* for y in partials */
1446 y = p[j];
1447 if (fabs(x) < fabs(y)) {
1448 t = x; x = y; y = t;
1449 }
1450 hi = x + y;
1451 yr = hi - x;
1452 lo = y - yr;
1453 if (lo != 0.0)
1454 p[i++] = lo;
1455 x = hi;
1456 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 n = i; /* ps[i:] = [x] */
1459 if (x != 0.0) {
1460 if (! Py_IS_FINITE(x)) {
1461 /* a nonfinite x could arise either as
1462 a result of intermediate overflow, or
1463 as a result of a nan or inf in the
1464 summands */
1465 if (Py_IS_FINITE(xsave)) {
1466 PyErr_SetString(PyExc_OverflowError,
1467 "intermediate overflow in fsum");
1468 goto _fsum_error;
1469 }
1470 if (Py_IS_INFINITY(xsave))
1471 inf_sum += xsave;
1472 special_sum += xsave;
1473 /* reset partials */
1474 n = 0;
1475 }
1476 else if (n >= m && _fsum_realloc(&p, n, ps, &m))
1477 goto _fsum_error;
1478 else
1479 p[n++] = x;
1480 }
1481 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 if (special_sum != 0.0) {
1484 if (Py_IS_NAN(inf_sum))
1485 PyErr_SetString(PyExc_ValueError,
1486 "-inf + inf in fsum");
1487 else
1488 sum = PyFloat_FromDouble(special_sum);
1489 goto _fsum_error;
1490 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 hi = 0.0;
1493 if (n > 0) {
1494 hi = p[--n];
1495 /* sum_exact(ps, hi) from the top, stop when the sum becomes
1496 inexact. */
1497 while (n > 0) {
1498 x = hi;
1499 y = p[--n];
1500 assert(fabs(y) < fabs(x));
1501 hi = x + y;
1502 yr = hi - x;
1503 lo = y - yr;
1504 if (lo != 0.0)
1505 break;
1506 }
1507 /* Make half-even rounding work across multiple partials.
1508 Needed so that sum([1e-16, 1, 1e16]) will round-up the last
1509 digit to two instead of down to zero (the 1e-16 makes the 1
1510 slightly closer to two). With a potential 1 ULP rounding
1511 error fixed-up, math.fsum() can guarantee commutativity. */
1512 if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
1513 (lo > 0.0 && p[n-1] > 0.0))) {
1514 y = lo * 2.0;
1515 x = hi + y;
1516 yr = x - hi;
1517 if (y == yr)
1518 hi = x;
1519 }
1520 }
1521 sum = PyFloat_FromDouble(hi);
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001522
Raymond Hettingercfd735e2019-01-29 20:39:53 -08001523 _fsum_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 Py_DECREF(iter);
1525 if (p != ps)
1526 PyMem_Free(p);
1527 return sum;
Raymond Hettingercfd735e2019-01-29 20:39:53 -08001528
1529 error_with_item:
1530 Py_DECREF(item);
1531 goto _fsum_error;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001532}
1533
1534#undef NUM_PARTIALS
1535
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001536
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001537static unsigned long
1538count_set_bits(unsigned long n)
1539{
1540 unsigned long count = 0;
1541 while (n != 0) {
1542 ++count;
1543 n &= n - 1; /* clear least significant bit */
1544 }
1545 return count;
1546}
1547
Mark Dickinson73934b92019-05-18 12:29:50 +01001548/* Integer square root
1549
1550Given a nonnegative integer `n`, we want to compute the largest integer
1551`a` for which `a * a <= n`, or equivalently the integer part of the exact
1552square root of `n`.
1553
1554We use an adaptive-precision pure-integer version of Newton's iteration. Given
1555a positive integer `n`, the algorithm produces at each iteration an integer
1556approximation `a` to the square root of `n >> s` for some even integer `s`,
1557with `s` decreasing as the iterations progress. On the final iteration, `s` is
1558zero and we have an approximation to the square root of `n` itself.
1559
1560At every step, the approximation `a` is strictly within 1.0 of the true square
1561root, so we have
1562
1563 (a - 1)**2 < (n >> s) < (a + 1)**2
1564
1565After the final iteration, a check-and-correct step is needed to determine
1566whether `a` or `a - 1` gives the desired integer square root of `n`.
1567
1568The algorithm is remarkable in its simplicity. There's no need for a
1569per-iteration check-and-correct step, and termination is straightforward: the
1570number of iterations is known in advance (it's exactly `floor(log2(log2(n)))`
1571for `n > 1`). The only tricky part of the correctness proof is in establishing
1572that the bound `(a - 1)**2 < (n >> s) < (a + 1)**2` is maintained from one
1573iteration to the next. A sketch of the proof of this is given below.
1574
1575In addition to the proof sketch, a formal, computer-verified proof
1576of correctness (using Lean) of an equivalent recursive algorithm can be found
1577here:
1578
1579 https://github.com/mdickinson/snippets/blob/master/proofs/isqrt/src/isqrt.lean
1580
1581
1582Here's Python code equivalent to the C implementation below:
1583
1584 def isqrt(n):
1585 """
1586 Return the integer part of the square root of the input.
1587 """
1588 n = operator.index(n)
1589
1590 if n < 0:
1591 raise ValueError("isqrt() argument must be nonnegative")
1592 if n == 0:
1593 return 0
1594
1595 c = (n.bit_length() - 1) // 2
1596 a = 1
1597 d = 0
1598 for s in reversed(range(c.bit_length())):
Mark Dickinson2dfeaa92019-06-16 17:53:21 +01001599 # Loop invariant: (a-1)**2 < (n >> 2*(c - d)) < (a+1)**2
Mark Dickinson73934b92019-05-18 12:29:50 +01001600 e = d
1601 d = c >> s
1602 a = (a << d - e - 1) + (n >> 2*c - e - d + 1) // a
Mark Dickinson73934b92019-05-18 12:29:50 +01001603
1604 return a - (a*a > n)
1605
1606
1607Sketch of proof of correctness
1608------------------------------
1609
1610The delicate part of the correctness proof is showing that the loop invariant
1611is preserved from one iteration to the next. That is, just before the line
1612
1613 a = (a << d - e - 1) + (n >> 2*c - e - d + 1) // a
1614
1615is executed in the above code, we know that
1616
1617 (1) (a - 1)**2 < (n >> 2*(c - e)) < (a + 1)**2.
1618
1619(since `e` is always the value of `d` from the previous iteration). We must
1620prove that after that line is executed, we have
1621
1622 (a - 1)**2 < (n >> 2*(c - d)) < (a + 1)**2
1623
Min ho Kimf7d72e42019-07-06 07:39:32 +10001624To facilitate the proof, we make some changes of notation. Write `m` for
Mark Dickinson73934b92019-05-18 12:29:50 +01001625`n >> 2*(c-d)`, and write `b` for the new value of `a`, so
1626
1627 b = (a << d - e - 1) + (n >> 2*c - e - d + 1) // a
1628
1629or equivalently:
1630
1631 (2) b = (a << d - e - 1) + (m >> d - e + 1) // a
1632
1633Then we can rewrite (1) as:
1634
1635 (3) (a - 1)**2 < (m >> 2*(d - e)) < (a + 1)**2
1636
1637and we must show that (b - 1)**2 < m < (b + 1)**2.
1638
1639From this point on, we switch to mathematical notation, so `/` means exact
1640division rather than integer division and `^` is used for exponentiation. We
1641use the `√` symbol for the exact square root. In (3), we can remove the
1642implicit floor operation to give:
1643
1644 (4) (a - 1)^2 < m / 4^(d - e) < (a + 1)^2
1645
1646Taking square roots throughout (4), scaling by `2^(d-e)`, and rearranging gives
1647
1648 (5) 0 <= | 2^(d-e)a - √m | < 2^(d-e)
1649
1650Squaring and dividing through by `2^(d-e+1) a` gives
1651
1652 (6) 0 <= 2^(d-e-1) a + m / (2^(d-e+1) a) - √m < 2^(d-e-1) / a
1653
1654We'll show below that `2^(d-e-1) <= a`. Given that, we can replace the
1655right-hand side of (6) with `1`, and now replacing the central
1656term `m / (2^(d-e+1) a)` with its floor in (6) gives
1657
1658 (7) -1 < 2^(d-e-1) a + m // 2^(d-e+1) a - √m < 1
1659
1660Or equivalently, from (2):
1661
1662 (7) -1 < b - √m < 1
1663
1664and rearranging gives that `(b-1)^2 < m < (b+1)^2`, which is what we needed
1665to prove.
1666
1667We're not quite done: we still have to prove the inequality `2^(d - e - 1) <=
1668a` that was used to get line (7) above. From the definition of `c`, we have
1669`4^c <= n`, which implies
1670
1671 (8) 4^d <= m
1672
1673also, since `e == d >> 1`, `d` is at most `2e + 1`, from which it follows
1674that `2d - 2e - 1 <= d` and hence that
1675
1676 (9) 4^(2d - 2e - 1) <= m
1677
1678Dividing both sides by `4^(d - e)` gives
1679
1680 (10) 4^(d - e - 1) <= m / 4^(d - e)
1681
1682But we know from (4) that `m / 4^(d-e) < (a + 1)^2`, hence
1683
1684 (11) 4^(d - e - 1) < (a + 1)^2
1685
1686Now taking square roots of both sides and observing that both `2^(d-e-1)` and
1687`a` are integers gives `2^(d - e - 1) <= a`, which is what we needed. This
1688completes the proof sketch.
1689
1690*/
1691
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001692
1693/* Approximate square root of a large 64-bit integer.
1694
1695 Given `n` satisfying `2**62 <= n < 2**64`, return `a`
1696 satisfying `(a - 1)**2 < n < (a + 1)**2`. */
1697
1698static uint64_t
1699_approximate_isqrt(uint64_t n)
1700{
1701 uint32_t u = 1U + (n >> 62);
1702 u = (u << 1) + (n >> 59) / u;
1703 u = (u << 3) + (n >> 53) / u;
1704 u = (u << 7) + (n >> 41) / u;
1705 return (u << 15) + (n >> 17) / u;
1706}
1707
Mark Dickinson73934b92019-05-18 12:29:50 +01001708/*[clinic input]
1709math.isqrt
1710
1711 n: object
1712 /
1713
1714Return the integer part of the square root of the input.
1715[clinic start generated code]*/
1716
1717static PyObject *
1718math_isqrt(PyObject *module, PyObject *n)
1719/*[clinic end generated code: output=35a6f7f980beab26 input=5b6e7ae4fa6c43d6]*/
1720{
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001721 int a_too_large, c_bit_length;
Mark Dickinson73934b92019-05-18 12:29:50 +01001722 size_t c, d;
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001723 uint64_t m, u;
Mark Dickinson73934b92019-05-18 12:29:50 +01001724 PyObject *a = NULL, *b;
1725
1726 n = PyNumber_Index(n);
1727 if (n == NULL) {
1728 return NULL;
1729 }
1730
1731 if (_PyLong_Sign(n) < 0) {
1732 PyErr_SetString(
1733 PyExc_ValueError,
1734 "isqrt() argument must be nonnegative");
1735 goto error;
1736 }
1737 if (_PyLong_Sign(n) == 0) {
1738 Py_DECREF(n);
1739 return PyLong_FromLong(0);
1740 }
1741
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001742 /* c = (n.bit_length() - 1) // 2 */
Mark Dickinson73934b92019-05-18 12:29:50 +01001743 c = _PyLong_NumBits(n);
1744 if (c == (size_t)(-1)) {
1745 goto error;
1746 }
1747 c = (c - 1U) / 2U;
1748
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001749 /* Fast path: if c <= 31 then n < 2**64 and we can compute directly with a
1750 fast, almost branch-free algorithm. In the final correction, we use `u*u
1751 - 1 >= m` instead of the simpler `u*u > m` in order to get the correct
1752 result in the corner case where `u=2**32`. */
1753 if (c <= 31U) {
1754 m = (uint64_t)PyLong_AsUnsignedLongLong(n);
1755 Py_DECREF(n);
1756 if (m == (uint64_t)(-1) && PyErr_Occurred()) {
1757 return NULL;
1758 }
1759 u = _approximate_isqrt(m << (62U - 2U*c)) >> (31U - c);
1760 u -= u * u - 1U >= m;
1761 return PyLong_FromUnsignedLongLong((unsigned long long)u);
Mark Dickinson73934b92019-05-18 12:29:50 +01001762 }
1763
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001764 /* Slow path: n >= 2**64. We perform the first five iterations in C integer
1765 arithmetic, then switch to using Python long integers. */
1766
1767 /* From n >= 2**64 it follows that c.bit_length() >= 6. */
1768 c_bit_length = 6;
1769 while ((c >> c_bit_length) > 0U) {
1770 ++c_bit_length;
1771 }
1772
1773 /* Initialise d and a. */
1774 d = c >> (c_bit_length - 5);
1775 b = _PyLong_Rshift(n, 2U*c - 62U);
1776 if (b == NULL) {
1777 goto error;
1778 }
1779 m = (uint64_t)PyLong_AsUnsignedLongLong(b);
1780 Py_DECREF(b);
1781 if (m == (uint64_t)(-1) && PyErr_Occurred()) {
1782 goto error;
1783 }
1784 u = _approximate_isqrt(m) >> (31U - d);
1785 a = PyLong_FromUnsignedLongLong((unsigned long long)u);
Mark Dickinson73934b92019-05-18 12:29:50 +01001786 if (a == NULL) {
1787 goto error;
1788 }
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001789
1790 for (int s = c_bit_length - 6; s >= 0; --s) {
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03001791 PyObject *q;
Mark Dickinson73934b92019-05-18 12:29:50 +01001792 size_t e = d;
1793
1794 d = c >> s;
1795
1796 /* q = (n >> 2*c - e - d + 1) // a */
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03001797 q = _PyLong_Rshift(n, 2U*c - d - e + 1U);
Mark Dickinson73934b92019-05-18 12:29:50 +01001798 if (q == NULL) {
1799 goto error;
1800 }
1801 Py_SETREF(q, PyNumber_FloorDivide(q, a));
1802 if (q == NULL) {
1803 goto error;
1804 }
1805
1806 /* a = (a << d - 1 - e) + q */
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03001807 Py_SETREF(a, _PyLong_Lshift(a, d - 1U - e));
Mark Dickinson73934b92019-05-18 12:29:50 +01001808 if (a == NULL) {
1809 Py_DECREF(q);
1810 goto error;
1811 }
1812 Py_SETREF(a, PyNumber_Add(a, q));
1813 Py_DECREF(q);
1814 if (a == NULL) {
1815 goto error;
1816 }
1817 }
1818
1819 /* The correct result is either a or a - 1. Figure out which, and
1820 decrement a if necessary. */
1821
1822 /* a_too_large = n < a * a */
1823 b = PyNumber_Multiply(a, a);
1824 if (b == NULL) {
1825 goto error;
1826 }
1827 a_too_large = PyObject_RichCompareBool(n, b, Py_LT);
1828 Py_DECREF(b);
1829 if (a_too_large == -1) {
1830 goto error;
1831 }
1832
1833 if (a_too_large) {
1834 Py_SETREF(a, PyNumber_Subtract(a, _PyLong_One));
1835 }
1836 Py_DECREF(n);
1837 return a;
1838
1839 error:
1840 Py_XDECREF(a);
1841 Py_DECREF(n);
1842 return NULL;
1843}
1844
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001845/* Divide-and-conquer factorial algorithm
1846 *
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07001847 * Based on the formula and pseudo-code provided at:
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001848 * http://www.luschny.de/math/factorial/binarysplitfact.html
1849 *
1850 * Faster algorithms exist, but they're more complicated and depend on
Ezio Melotti9527afd2010-07-08 15:03:02 +00001851 * a fast prime factorization algorithm.
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001852 *
1853 * Notes on the algorithm
1854 * ----------------------
1855 *
1856 * factorial(n) is written in the form 2**k * m, with m odd. k and m are
1857 * computed separately, and then combined using a left shift.
1858 *
1859 * The function factorial_odd_part computes the odd part m (i.e., the greatest
1860 * odd divisor) of factorial(n), using the formula:
1861 *
1862 * factorial_odd_part(n) =
1863 *
1864 * product_{i >= 0} product_{0 < j <= n / 2**i, j odd} j
1865 *
1866 * Example: factorial_odd_part(20) =
1867 *
1868 * (1) *
1869 * (1) *
1870 * (1 * 3 * 5) *
1871 * (1 * 3 * 5 * 7 * 9)
1872 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1873 *
1874 * Here i goes from large to small: the first term corresponds to i=4 (any
1875 * larger i gives an empty product), and the last term corresponds to i=0.
1876 * Each term can be computed from the last by multiplying by the extra odd
1877 * numbers required: e.g., to get from the penultimate term to the last one,
1878 * we multiply by (11 * 13 * 15 * 17 * 19).
1879 *
1880 * To see a hint of why this formula works, here are the same numbers as above
1881 * but with the even parts (i.e., the appropriate powers of 2) included. For
1882 * each subterm in the product for i, we multiply that subterm by 2**i:
1883 *
1884 * factorial(20) =
1885 *
1886 * (16) *
1887 * (8) *
1888 * (4 * 12 * 20) *
1889 * (2 * 6 * 10 * 14 * 18) *
1890 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1891 *
1892 * The factorial_partial_product function computes the product of all odd j in
1893 * range(start, stop) for given start and stop. It's used to compute the
1894 * partial products like (11 * 13 * 15 * 17 * 19) in the example above. It
1895 * operates recursively, repeatedly splitting the range into two roughly equal
1896 * pieces until the subranges are small enough to be computed using only C
1897 * integer arithmetic.
1898 *
1899 * The two-valuation k (i.e., the exponent of the largest power of 2 dividing
1900 * the factorial) is computed independently in the main math_factorial
1901 * function. By standard results, its value is:
1902 *
1903 * two_valuation = n//2 + n//4 + n//8 + ....
1904 *
1905 * It can be shown (e.g., by complete induction on n) that two_valuation is
1906 * equal to n - count_set_bits(n), where count_set_bits(n) gives the number of
1907 * '1'-bits in the binary expansion of n.
1908 */
1909
1910/* factorial_partial_product: Compute product(range(start, stop, 2)) using
1911 * divide and conquer. Assumes start and stop are odd and stop > start.
1912 * max_bits must be >= bit_length(stop - 2). */
1913
1914static PyObject *
1915factorial_partial_product(unsigned long start, unsigned long stop,
1916 unsigned long max_bits)
1917{
1918 unsigned long midpoint, num_operands;
1919 PyObject *left = NULL, *right = NULL, *result = NULL;
1920
1921 /* If the return value will fit an unsigned long, then we can
1922 * multiply in a tight, fast loop where each multiply is O(1).
1923 * Compute an upper bound on the number of bits required to store
1924 * the answer.
1925 *
1926 * Storing some integer z requires floor(lg(z))+1 bits, which is
1927 * conveniently the value returned by bit_length(z). The
1928 * product x*y will require at most
1929 * bit_length(x) + bit_length(y) bits to store, based
1930 * on the idea that lg product = lg x + lg y.
1931 *
1932 * We know that stop - 2 is the largest number to be multiplied. From
1933 * there, we have: bit_length(answer) <= num_operands *
1934 * bit_length(stop - 2)
1935 */
1936
1937 num_operands = (stop - start) / 2;
1938 /* The "num_operands <= 8 * SIZEOF_LONG" check guards against the
1939 * unlikely case of an overflow in num_operands * max_bits. */
1940 if (num_operands <= 8 * SIZEOF_LONG &&
1941 num_operands * max_bits <= 8 * SIZEOF_LONG) {
1942 unsigned long j, total;
1943 for (total = start, j = start + 2; j < stop; j += 2)
1944 total *= j;
1945 return PyLong_FromUnsignedLong(total);
1946 }
1947
1948 /* find midpoint of range(start, stop), rounded up to next odd number. */
1949 midpoint = (start + num_operands) | 1;
1950 left = factorial_partial_product(start, midpoint,
Niklas Fiekasc5b79002020-01-16 15:09:19 +01001951 _Py_bit_length(midpoint - 2));
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001952 if (left == NULL)
1953 goto error;
1954 right = factorial_partial_product(midpoint, stop, max_bits);
1955 if (right == NULL)
1956 goto error;
1957 result = PyNumber_Multiply(left, right);
1958
1959 error:
1960 Py_XDECREF(left);
1961 Py_XDECREF(right);
1962 return result;
1963}
1964
1965/* factorial_odd_part: compute the odd part of factorial(n). */
1966
1967static PyObject *
1968factorial_odd_part(unsigned long n)
1969{
1970 long i;
1971 unsigned long v, lower, upper;
1972 PyObject *partial, *tmp, *inner, *outer;
1973
1974 inner = PyLong_FromLong(1);
1975 if (inner == NULL)
1976 return NULL;
1977 outer = inner;
1978 Py_INCREF(outer);
1979
1980 upper = 3;
Niklas Fiekasc5b79002020-01-16 15:09:19 +01001981 for (i = _Py_bit_length(n) - 2; i >= 0; i--) {
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001982 v = n >> i;
1983 if (v <= 2)
1984 continue;
1985 lower = upper;
1986 /* (v + 1) | 1 = least odd integer strictly larger than n / 2**i */
1987 upper = (v + 1) | 1;
1988 /* Here inner is the product of all odd integers j in the range (0,
1989 n/2**(i+1)]. The factorial_partial_product call below gives the
1990 product of all odd integers j in the range (n/2**(i+1), n/2**i]. */
Niklas Fiekasc5b79002020-01-16 15:09:19 +01001991 partial = factorial_partial_product(lower, upper, _Py_bit_length(upper-2));
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001992 /* inner *= partial */
1993 if (partial == NULL)
1994 goto error;
1995 tmp = PyNumber_Multiply(inner, partial);
1996 Py_DECREF(partial);
1997 if (tmp == NULL)
1998 goto error;
1999 Py_DECREF(inner);
2000 inner = tmp;
2001 /* Now inner is the product of all odd integers j in the range (0,
2002 n/2**i], giving the inner product in the formula above. */
2003
2004 /* outer *= inner; */
2005 tmp = PyNumber_Multiply(outer, inner);
2006 if (tmp == NULL)
2007 goto error;
2008 Py_DECREF(outer);
2009 outer = tmp;
2010 }
Mark Dickinson76464492012-10-25 10:46:28 +01002011 Py_DECREF(inner);
2012 return outer;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002013
2014 error:
2015 Py_DECREF(outer);
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002016 Py_DECREF(inner);
Mark Dickinson76464492012-10-25 10:46:28 +01002017 return NULL;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002018}
2019
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002020
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002021/* Lookup table for small factorial values */
2022
2023static const unsigned long SmallFactorials[] = {
2024 1, 1, 2, 6, 24, 120, 720, 5040, 40320,
2025 362880, 3628800, 39916800, 479001600,
2026#if SIZEOF_LONG >= 8
2027 6227020800, 87178291200, 1307674368000,
2028 20922789888000, 355687428096000, 6402373705728000,
2029 121645100408832000, 2432902008176640000
2030#endif
2031};
2032
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002033/*[clinic input]
2034math.factorial
2035
2036 x as arg: object
2037 /
2038
2039Find x!.
2040
2041Raise a ValueError if x is negative or non-integral.
2042[clinic start generated code]*/
2043
Barry Warsaw8b43b191996-12-09 22:32:36 +00002044static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002045math_factorial(PyObject *module, PyObject *arg)
2046/*[clinic end generated code: output=6686f26fae00e9ca input=6d1c8105c0d91fb4]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002047{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03002048 long x, two_valuation;
Mark Dickinson5990d282014-04-10 09:29:39 -04002049 int overflow;
Serhiy Storchaka578c3952020-05-26 18:43:38 +03002050 PyObject *result, *odd_part;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002051
Serhiy Storchaka578c3952020-05-26 18:43:38 +03002052 x = PyLong_AsLongAndOverflow(arg, &overflow);
Mark Dickinson5990d282014-04-10 09:29:39 -04002053 if (x == -1 && PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 return NULL;
Mark Dickinson5990d282014-04-10 09:29:39 -04002055 }
2056 else if (overflow == 1) {
2057 PyErr_Format(PyExc_OverflowError,
2058 "factorial() argument should not exceed %ld",
2059 LONG_MAX);
2060 return NULL;
2061 }
2062 else if (overflow == -1 || x < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002064 "factorial() not defined for negative values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 return NULL;
2066 }
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002067
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002068 /* use lookup table if x is small */
Victor Stinner63941882011-09-29 00:42:28 +02002069 if (x < (long)Py_ARRAY_LENGTH(SmallFactorials))
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002070 return PyLong_FromUnsignedLong(SmallFactorials[x]);
2071
2072 /* else express in the form odd_part * 2**two_valuation, and compute as
2073 odd_part << two_valuation. */
2074 odd_part = factorial_odd_part(x);
2075 if (odd_part == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03002077 two_valuation = x - count_set_bits(x);
2078 result = _PyLong_Lshift(odd_part, two_valuation);
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002079 Py_DECREF(odd_part);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 return result;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002081}
2082
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002083
2084/*[clinic input]
2085math.trunc
2086
2087 x: object
2088 /
2089
2090Truncates the Real x to the nearest Integral toward 0.
2091
2092Uses the __trunc__ magic method.
2093[clinic start generated code]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002094
2095static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002096math_trunc(PyObject *module, PyObject *x)
2097/*[clinic end generated code: output=34b9697b707e1031 input=2168b34e0a09134d]*/
Christian Heimes400adb02008-02-01 08:12:03 +00002098{
Benjamin Petersonce798522012-01-22 11:24:29 -05002099 _Py_IDENTIFIER(__trunc__);
Benjamin Petersonb0125892010-07-02 13:35:17 +00002100 PyObject *trunc, *result;
Christian Heimes400adb02008-02-01 08:12:03 +00002101
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02002102 if (PyFloat_CheckExact(x)) {
2103 return PyFloat_Type.tp_as_number->nb_int(x);
2104 }
2105
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002106 if (Py_TYPE(x)->tp_dict == NULL) {
2107 if (PyType_Ready(Py_TYPE(x)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 return NULL;
2109 }
Christian Heimes400adb02008-02-01 08:12:03 +00002110
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002111 trunc = _PyObject_LookupSpecial(x, &PyId___trunc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 if (trunc == NULL) {
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00002113 if (!PyErr_Occurred())
2114 PyErr_Format(PyExc_TypeError,
2115 "type %.100s doesn't define __trunc__ method",
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002116 Py_TYPE(x)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 return NULL;
2118 }
Victor Stinnerf17c3de2016-12-06 18:46:19 +01002119 result = _PyObject_CallNoArg(trunc);
Benjamin Petersonb0125892010-07-02 13:35:17 +00002120 Py_DECREF(trunc);
2121 return result;
Christian Heimes400adb02008-02-01 08:12:03 +00002122}
2123
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002124
2125/*[clinic input]
2126math.frexp
2127
2128 x: double
2129 /
2130
2131Return the mantissa and exponent of x, as pair (m, e).
2132
2133m is a float and e is an int, such that x = m * 2.**e.
2134If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.
2135[clinic start generated code]*/
Christian Heimes400adb02008-02-01 08:12:03 +00002136
2137static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002138math_frexp_impl(PyObject *module, double x)
2139/*[clinic end generated code: output=03e30d252a15ad4a input=96251c9e208bc6e9]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00002140{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 /* deal with special cases directly, to sidestep platform
2143 differences */
2144 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
2145 i = 0;
2146 }
2147 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 x = frexp(x, &i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 }
2150 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +00002151}
2152
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002153
2154/*[clinic input]
2155math.ldexp
2156
2157 x: double
2158 i: object
2159 /
2160
2161Return x * (2**i).
2162
2163This is essentially the inverse of frexp().
2164[clinic start generated code]*/
Guido van Rossumc6e22901998-12-04 19:26:43 +00002165
Barry Warsaw8b43b191996-12-09 22:32:36 +00002166static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002167math_ldexp_impl(PyObject *module, double x, PyObject *i)
2168/*[clinic end generated code: output=b6892f3c2df9cc6a input=17d5970c1a40a8c1]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00002169{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002170 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 long exp;
2172 int overflow;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00002173
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002174 if (PyLong_Check(i)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 /* on overflow, replace exponent with either LONG_MAX
2176 or LONG_MIN, depending on the sign. */
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002177 exp = PyLong_AsLongAndOverflow(i, &overflow);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 if (exp == -1 && PyErr_Occurred())
2179 return NULL;
2180 if (overflow)
2181 exp = overflow < 0 ? LONG_MIN : LONG_MAX;
2182 }
2183 else {
2184 PyErr_SetString(PyExc_TypeError,
Serhiy Storchaka95949422013-08-27 19:40:23 +03002185 "Expected an int as second argument to ldexp.");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 return NULL;
2187 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00002188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 if (x == 0. || !Py_IS_FINITE(x)) {
2190 /* NaNs, zeros and infinities are returned unchanged */
2191 r = x;
2192 errno = 0;
2193 } else if (exp > INT_MAX) {
2194 /* overflow */
2195 r = copysign(Py_HUGE_VAL, x);
2196 errno = ERANGE;
2197 } else if (exp < INT_MIN) {
2198 /* underflow to +-0 */
2199 r = copysign(0., x);
2200 errno = 0;
2201 } else {
2202 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 r = ldexp(x, (int)exp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 if (Py_IS_INFINITY(r))
2205 errno = ERANGE;
2206 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00002207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002208 if (errno && is_error(r))
2209 return NULL;
2210 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +00002211}
2212
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002213
2214/*[clinic input]
2215math.modf
2216
2217 x: double
2218 /
2219
2220Return the fractional and integer parts of x.
2221
2222Both results carry the sign of x and are floats.
2223[clinic start generated code]*/
Guido van Rossumc6e22901998-12-04 19:26:43 +00002224
Barry Warsaw8b43b191996-12-09 22:32:36 +00002225static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002226math_modf_impl(PyObject *module, double x)
2227/*[clinic end generated code: output=90cee0260014c3c0 input=b4cfb6786afd9035]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00002228{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002229 double y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 /* some platforms don't do the right thing for NaNs and
2231 infinities, so we take care of special cases directly. */
2232 if (!Py_IS_FINITE(x)) {
2233 if (Py_IS_INFINITY(x))
2234 return Py_BuildValue("(dd)", copysign(0., x), x);
2235 else if (Py_IS_NAN(x))
2236 return Py_BuildValue("(dd)", x, x);
2237 }
Christian Heimesa342c012008-04-20 21:01:16 +00002238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 x = modf(x, &y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +00002242}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002243
Guido van Rossumc6e22901998-12-04 19:26:43 +00002244
Serhiy Storchaka95949422013-08-27 19:40:23 +03002245/* A decent logarithm is easy to compute even for huge ints, but libm can't
Tim Peters78526162001-09-05 00:53:45 +00002246 do that by itself -- loghelper can. func is log or log10, and name is
Serhiy Storchaka95949422013-08-27 19:40:23 +03002247 "log" or "log10". Note that overflow of the result isn't possible: an int
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002248 can contain no more than INT_MAX * SHIFT bits, so has value certainly less
2249 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 +00002250 small enough to fit in an IEEE single. log and log10 are even smaller.
Serhiy Storchaka95949422013-08-27 19:40:23 +03002251 However, intermediate overflow is possible for an int if the number of bits
2252 in that int is larger than PY_SSIZE_T_MAX. */
Tim Peters78526162001-09-05 00:53:45 +00002253
2254static PyObject*
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002255loghelper(PyObject* arg, double (*func)(double), const char *funcname)
Tim Peters78526162001-09-05 00:53:45 +00002256{
Serhiy Storchaka95949422013-08-27 19:40:23 +03002257 /* If it is int, do it ourselves. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 if (PyLong_Check(arg)) {
Mark Dickinsonc6037172010-09-29 19:06:36 +00002259 double x, result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 Py_ssize_t e;
Mark Dickinsonc6037172010-09-29 19:06:36 +00002261
2262 /* Negative or zero inputs give a ValueError. */
2263 if (Py_SIZE(arg) <= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 PyErr_SetString(PyExc_ValueError,
2265 "math domain error");
2266 return NULL;
2267 }
Mark Dickinsonfa41e602010-09-28 07:22:27 +00002268
Mark Dickinsonc6037172010-09-29 19:06:36 +00002269 x = PyLong_AsDouble(arg);
2270 if (x == -1.0 && PyErr_Occurred()) {
2271 if (!PyErr_ExceptionMatches(PyExc_OverflowError))
2272 return NULL;
2273 /* Here the conversion to double overflowed, but it's possible
2274 to compute the log anyway. Clear the exception and continue. */
2275 PyErr_Clear();
2276 x = _PyLong_Frexp((PyLongObject *)arg, &e);
2277 if (x == -1.0 && PyErr_Occurred())
2278 return NULL;
2279 /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */
2280 result = func(x) + func(2.0) * e;
2281 }
2282 else
2283 /* Successfully converted x to a double. */
2284 result = func(x);
2285 return PyFloat_FromDouble(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 }
Tim Peters78526162001-09-05 00:53:45 +00002287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 /* Else let libm handle it by itself. */
2289 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +00002290}
2291
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002292
2293/*[clinic input]
2294math.log
2295
2296 x: object
2297 [
2298 base: object(c_default="NULL") = math.e
2299 ]
2300 /
2301
2302Return the logarithm of x to the given base.
2303
2304If the base not specified, returns the natural logarithm (base e) of x.
2305[clinic start generated code]*/
2306
Tim Peters78526162001-09-05 00:53:45 +00002307static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002308math_log_impl(PyObject *module, PyObject *x, int group_right_1,
2309 PyObject *base)
2310/*[clinic end generated code: output=7b5a39e526b73fc9 input=0f62d5726cbfebbd]*/
Tim Peters78526162001-09-05 00:53:45 +00002311{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 PyObject *num, *den;
2313 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +00002314
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002315 num = loghelper(x, m_log, "log");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 if (num == NULL || base == NULL)
2317 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +00002318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 den = loghelper(base, m_log, "log");
2320 if (den == NULL) {
2321 Py_DECREF(num);
2322 return NULL;
2323 }
Raymond Hettinger866964c2002-12-14 19:51:34 +00002324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 ans = PyNumber_TrueDivide(num, den);
2326 Py_DECREF(num);
2327 Py_DECREF(den);
2328 return ans;
Tim Peters78526162001-09-05 00:53:45 +00002329}
2330
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002331
2332/*[clinic input]
2333math.log2
2334
2335 x: object
2336 /
2337
2338Return the base 2 logarithm of x.
2339[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002340
2341static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002342math_log2(PyObject *module, PyObject *x)
2343/*[clinic end generated code: output=5425899a4d5d6acb input=08321262bae4f39b]*/
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02002344{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002345 return loghelper(x, m_log2, "log2");
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02002346}
2347
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002348
2349/*[clinic input]
2350math.log10
2351
2352 x: object
2353 /
2354
2355Return the base 10 logarithm of x.
2356[clinic start generated code]*/
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02002357
2358static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002359math_log10(PyObject *module, PyObject *x)
2360/*[clinic end generated code: output=be72a64617df9c6f input=b2469d02c6469e53]*/
Tim Peters78526162001-09-05 00:53:45 +00002361{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002362 return loghelper(x, m_log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +00002363}
2364
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002365
2366/*[clinic input]
2367math.fmod
2368
2369 x: double
2370 y: double
2371 /
2372
2373Return fmod(x, y), according to platform C.
2374
2375x % y may differ.
2376[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002377
Christian Heimes53876d92008-04-19 00:31:39 +00002378static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002379math_fmod_impl(PyObject *module, double x, double y)
2380/*[clinic end generated code: output=7559d794343a27b5 input=4f84caa8cfc26a03]*/
Christian Heimes53876d92008-04-19 00:31:39 +00002381{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002382 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 /* fmod(x, +/-Inf) returns x for finite x. */
2384 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
2385 return PyFloat_FromDouble(x);
2386 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 r = fmod(x, y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 if (Py_IS_NAN(r)) {
2389 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
2390 errno = EDOM;
2391 else
2392 errno = 0;
2393 }
2394 if (errno && is_error(r))
2395 return NULL;
2396 else
2397 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00002398}
2399
Raymond Hettinger13990742018-08-11 11:26:36 -07002400/*
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002401Given an *n* length *vec* of values and a value *max*, compute:
Raymond Hettinger13990742018-08-11 11:26:36 -07002402
Raymond Hettingerc630e102018-08-11 18:39:05 -07002403 max * sqrt(sum((x / max) ** 2 for x in vec))
Raymond Hettinger13990742018-08-11 11:26:36 -07002404
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002405The value of the *max* variable must be non-negative and
Raymond Hettinger216aaaa2018-11-09 01:06:02 -08002406equal to the absolute value of the largest magnitude
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002407entry in the vector. If n==0, then *max* should be 0.0.
2408If an infinity is present in the vec, *max* should be INF.
Raymond Hettingerc630e102018-08-11 18:39:05 -07002409
2410The *found_nan* variable indicates whether some member of
2411the *vec* is a NaN.
Raymond Hettinger21786f52018-08-28 22:47:24 -07002412
2413To improve accuracy and to increase the number of cases where
2414vector_norm() is commutative, we use a variant of Neumaier
2415summation specialized to exploit that we always know that
2416|csum| >= |x|.
2417
2418The *csum* variable tracks the cumulative sum and *frac* tracks
2419the cumulative fractional errors at each step. Since this
2420variant assumes that |csum| >= |x| at each step, we establish
2421the precondition by starting the accumulation from 1.0 which
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002422represents the largest possible value of (x/max)**2.
2423
2424After the loop is finished, the initial 1.0 is subtracted out
2425for a net zero effect on the final sum. Since *csum* will be
2426greater than 1.0, the subtraction of 1.0 will not cause
2427fractional digits to be dropped from *csum*.
Raymond Hettinger21786f52018-08-28 22:47:24 -07002428
Raymond Hettinger13990742018-08-11 11:26:36 -07002429*/
2430
2431static inline double
Raymond Hettingerc630e102018-08-11 18:39:05 -07002432vector_norm(Py_ssize_t n, double *vec, double max, int found_nan)
Raymond Hettinger13990742018-08-11 11:26:36 -07002433{
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002434 double x, csum = 1.0, oldcsum, frac = 0.0;
Raymond Hettinger13990742018-08-11 11:26:36 -07002435 Py_ssize_t i;
2436
Raymond Hettingerc630e102018-08-11 18:39:05 -07002437 if (Py_IS_INFINITY(max)) {
2438 return max;
2439 }
2440 if (found_nan) {
2441 return Py_NAN;
2442 }
Raymond Hettingerf3267142018-09-02 13:34:21 -07002443 if (max == 0.0 || n <= 1) {
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002444 return max;
Raymond Hettinger13990742018-08-11 11:26:36 -07002445 }
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002446 for (i=0 ; i < n ; i++) {
Raymond Hettinger13990742018-08-11 11:26:36 -07002447 x = vec[i];
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002448 assert(Py_IS_FINITE(x) && fabs(x) <= max);
Raymond Hettinger13990742018-08-11 11:26:36 -07002449 x /= max;
Raymond Hettinger21786f52018-08-28 22:47:24 -07002450 x = x*x;
Raymond Hettinger13990742018-08-11 11:26:36 -07002451 oldcsum = csum;
2452 csum += x;
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002453 assert(csum >= x);
Raymond Hettinger21786f52018-08-28 22:47:24 -07002454 frac += (oldcsum - csum) + x;
Raymond Hettinger13990742018-08-11 11:26:36 -07002455 }
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002456 return max * sqrt(csum - 1.0 + frac);
Raymond Hettinger13990742018-08-11 11:26:36 -07002457}
2458
Raymond Hettingerc630e102018-08-11 18:39:05 -07002459#define NUM_STACK_ELEMS 16
2460
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002461/*[clinic input]
2462math.dist
2463
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002464 p: object
2465 q: object
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002466 /
2467
2468Return the Euclidean distance between two points p and q.
2469
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002470The points should be specified as sequences (or iterables) of
2471coordinates. Both inputs must have the same dimension.
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002472
2473Roughly equivalent to:
2474 sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
2475[clinic start generated code]*/
2476
2477static PyObject *
2478math_dist_impl(PyObject *module, PyObject *p, PyObject *q)
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002479/*[clinic end generated code: output=56bd9538d06bbcfe input=74e85e1b6092e68e]*/
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002480{
2481 PyObject *item;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002482 double max = 0.0;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002483 double x, px, qx, result;
2484 Py_ssize_t i, m, n;
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002485 int found_nan = 0, p_allocated = 0, q_allocated = 0;
Raymond Hettingerc630e102018-08-11 18:39:05 -07002486 double diffs_on_stack[NUM_STACK_ELEMS];
2487 double *diffs = diffs_on_stack;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002488
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002489 if (!PyTuple_Check(p)) {
2490 p = PySequence_Tuple(p);
2491 if (p == NULL) {
2492 return NULL;
2493 }
2494 p_allocated = 1;
2495 }
2496 if (!PyTuple_Check(q)) {
2497 q = PySequence_Tuple(q);
2498 if (q == NULL) {
2499 if (p_allocated) {
2500 Py_DECREF(p);
2501 }
2502 return NULL;
2503 }
2504 q_allocated = 1;
2505 }
2506
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002507 m = PyTuple_GET_SIZE(p);
2508 n = PyTuple_GET_SIZE(q);
2509 if (m != n) {
2510 PyErr_SetString(PyExc_ValueError,
2511 "both points must have the same number of dimensions");
2512 return NULL;
2513
2514 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002515 if (n > NUM_STACK_ELEMS) {
2516 diffs = (double *) PyObject_Malloc(n * sizeof(double));
2517 if (diffs == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07002518 return PyErr_NoMemory();
Raymond Hettingerc630e102018-08-11 18:39:05 -07002519 }
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002520 }
2521 for (i=0 ; i<n ; i++) {
2522 item = PyTuple_GET_ITEM(p, i);
Raymond Hettingercfd735e2019-01-29 20:39:53 -08002523 ASSIGN_DOUBLE(px, item, error_exit);
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002524 item = PyTuple_GET_ITEM(q, i);
Raymond Hettingercfd735e2019-01-29 20:39:53 -08002525 ASSIGN_DOUBLE(qx, item, error_exit);
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002526 x = fabs(px - qx);
2527 diffs[i] = x;
2528 found_nan |= Py_IS_NAN(x);
2529 if (x > max) {
2530 max = x;
2531 }
2532 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002533 result = vector_norm(n, diffs, max, found_nan);
2534 if (diffs != diffs_on_stack) {
2535 PyObject_Free(diffs);
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002536 }
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002537 if (p_allocated) {
2538 Py_DECREF(p);
2539 }
2540 if (q_allocated) {
2541 Py_DECREF(q);
2542 }
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002543 return PyFloat_FromDouble(result);
Raymond Hettingerc630e102018-08-11 18:39:05 -07002544
2545 error_exit:
2546 if (diffs != diffs_on_stack) {
2547 PyObject_Free(diffs);
2548 }
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002549 if (p_allocated) {
2550 Py_DECREF(p);
2551 }
2552 if (q_allocated) {
2553 Py_DECREF(q);
2554 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002555 return NULL;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002556}
2557
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002558/* AC: cannot convert yet, waiting for *args support */
Christian Heimes53876d92008-04-19 00:31:39 +00002559static PyObject *
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002560math_hypot(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Christian Heimes53876d92008-04-19 00:31:39 +00002561{
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002562 Py_ssize_t i;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002563 PyObject *item;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002564 double max = 0.0;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002565 double x, result;
2566 int found_nan = 0;
Raymond Hettingerc630e102018-08-11 18:39:05 -07002567 double coord_on_stack[NUM_STACK_ELEMS];
2568 double *coordinates = coord_on_stack;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002569
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002570 if (nargs > NUM_STACK_ELEMS) {
2571 coordinates = (double *) PyObject_Malloc(nargs * sizeof(double));
Zackery Spytz4c49da02018-12-07 03:11:30 -07002572 if (coordinates == NULL) {
2573 return PyErr_NoMemory();
2574 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002575 }
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002576 for (i = 0; i < nargs; i++) {
2577 item = args[i];
Raymond Hettingercfd735e2019-01-29 20:39:53 -08002578 ASSIGN_DOUBLE(x, item, error_exit);
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002579 x = fabs(x);
2580 coordinates[i] = x;
2581 found_nan |= Py_IS_NAN(x);
2582 if (x > max) {
2583 max = x;
2584 }
2585 }
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002586 result = vector_norm(nargs, coordinates, max, found_nan);
Raymond Hettingerc630e102018-08-11 18:39:05 -07002587 if (coordinates != coord_on_stack) {
2588 PyObject_Free(coordinates);
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002589 }
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002590 return PyFloat_FromDouble(result);
Raymond Hettingerc630e102018-08-11 18:39:05 -07002591
2592 error_exit:
2593 if (coordinates != coord_on_stack) {
2594 PyObject_Free(coordinates);
2595 }
2596 return NULL;
Christian Heimes53876d92008-04-19 00:31:39 +00002597}
2598
Raymond Hettingerc630e102018-08-11 18:39:05 -07002599#undef NUM_STACK_ELEMS
2600
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002601PyDoc_STRVAR(math_hypot_doc,
2602 "hypot(*coordinates) -> value\n\n\
2603Multidimensional Euclidean distance from the origin to a point.\n\
2604\n\
2605Roughly equivalent to:\n\
2606 sqrt(sum(x**2 for x in coordinates))\n\
2607\n\
2608For a two dimensional point (x, y), gives the hypotenuse\n\
2609using the Pythagorean theorem: sqrt(x*x + y*y).\n\
2610\n\
2611For example, the hypotenuse of a 3/4/5 right triangle is:\n\
2612\n\
2613 >>> hypot(3.0, 4.0)\n\
2614 5.0\n\
2615");
Christian Heimes53876d92008-04-19 00:31:39 +00002616
2617/* pow can't use math_2, but needs its own wrapper: the problem is
2618 that an infinite result can arise either as a result of overflow
2619 (in which case OverflowError should be raised) or as a result of
2620 e.g. 0.**-5. (for which ValueError needs to be raised.)
2621*/
2622
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002623/*[clinic input]
2624math.pow
Christian Heimes53876d92008-04-19 00:31:39 +00002625
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002626 x: double
2627 y: double
2628 /
2629
2630Return x**y (x to the power of y).
2631[clinic start generated code]*/
2632
2633static PyObject *
2634math_pow_impl(PyObject *module, double x, double y)
2635/*[clinic end generated code: output=fff93e65abccd6b0 input=c26f1f6075088bfd]*/
2636{
2637 double r;
2638 int odd_y;
Christian Heimesa342c012008-04-20 21:01:16 +00002639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 /* deal directly with IEEE specials, to cope with problems on various
2641 platforms whose semantics don't exactly match C99 */
2642 r = 0.; /* silence compiler warning */
2643 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
2644 errno = 0;
2645 if (Py_IS_NAN(x))
2646 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
2647 else if (Py_IS_NAN(y))
2648 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
2649 else if (Py_IS_INFINITY(x)) {
2650 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
2651 if (y > 0.)
2652 r = odd_y ? x : fabs(x);
2653 else if (y == 0.)
2654 r = 1.;
2655 else /* y < 0. */
2656 r = odd_y ? copysign(0., x) : 0.;
2657 }
2658 else if (Py_IS_INFINITY(y)) {
2659 if (fabs(x) == 1.0)
2660 r = 1.;
2661 else if (y > 0. && fabs(x) > 1.0)
2662 r = y;
2663 else if (y < 0. && fabs(x) < 1.0) {
2664 r = -y; /* result is +inf */
2665 if (x == 0.) /* 0**-inf: divide-by-zero */
2666 errno = EDOM;
2667 }
2668 else
2669 r = 0.;
2670 }
2671 }
2672 else {
2673 /* let libm handle finite**finite */
2674 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002675 r = pow(x, y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 /* a NaN result should arise only from (-ve)**(finite
2677 non-integer); in this case we want to raise ValueError. */
2678 if (!Py_IS_FINITE(r)) {
2679 if (Py_IS_NAN(r)) {
2680 errno = EDOM;
2681 }
2682 /*
2683 an infinite result here arises either from:
2684 (A) (+/-0.)**negative (-> divide-by-zero)
2685 (B) overflow of x**y with x and y finite
2686 */
2687 else if (Py_IS_INFINITY(r)) {
2688 if (x == 0.)
2689 errno = EDOM;
2690 else
2691 errno = ERANGE;
2692 }
2693 }
2694 }
Christian Heimes53876d92008-04-19 00:31:39 +00002695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 if (errno && is_error(r))
2697 return NULL;
2698 else
2699 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00002700}
2701
Christian Heimes53876d92008-04-19 00:31:39 +00002702
Christian Heimes072c0f12008-01-03 23:01:04 +00002703static const double degToRad = Py_MATH_PI / 180.0;
2704static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002705
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002706/*[clinic input]
2707math.degrees
2708
2709 x: double
2710 /
2711
2712Convert angle x from radians to degrees.
2713[clinic start generated code]*/
2714
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002715static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002716math_degrees_impl(PyObject *module, double x)
2717/*[clinic end generated code: output=7fea78b294acd12f input=81e016555d6e3660]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002720}
2721
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002722
2723/*[clinic input]
2724math.radians
2725
2726 x: double
2727 /
2728
2729Convert angle x from degrees to radians.
2730[clinic start generated code]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002731
2732static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002733math_radians_impl(PyObject *module, double x)
2734/*[clinic end generated code: output=34daa47caf9b1590 input=91626fc489fe3d63]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 return PyFloat_FromDouble(x * degToRad);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002737}
2738
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002739
2740/*[clinic input]
2741math.isfinite
2742
2743 x: double
2744 /
2745
2746Return True if x is neither an infinity nor a NaN, and False otherwise.
2747[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002748
Christian Heimes072c0f12008-01-03 23:01:04 +00002749static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002750math_isfinite_impl(PyObject *module, double x)
2751/*[clinic end generated code: output=8ba1f396440c9901 input=46967d254812e54a]*/
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002752{
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002753 return PyBool_FromLong((long)Py_IS_FINITE(x));
2754}
2755
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002756
2757/*[clinic input]
2758math.isnan
2759
2760 x: double
2761 /
2762
2763Return True if x is a NaN (not a number), and False otherwise.
2764[clinic start generated code]*/
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002765
2766static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002767math_isnan_impl(PyObject *module, double x)
2768/*[clinic end generated code: output=f537b4d6df878c3e input=935891e66083f46a]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002770 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00002771}
2772
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002773
2774/*[clinic input]
2775math.isinf
2776
2777 x: double
2778 /
2779
2780Return True if x is a positive or negative infinity, and False otherwise.
2781[clinic start generated code]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002782
2783static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002784math_isinf_impl(PyObject *module, double x)
2785/*[clinic end generated code: output=9f00cbec4de7b06b input=32630e4212cf961f]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00002788}
2789
Christian Heimes072c0f12008-01-03 23:01:04 +00002790
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002791/*[clinic input]
2792math.isclose -> bool
2793
2794 a: double
2795 b: double
2796 *
2797 rel_tol: double = 1e-09
2798 maximum difference for being considered "close", relative to the
2799 magnitude of the input values
2800 abs_tol: double = 0.0
2801 maximum difference for being considered "close", regardless of the
2802 magnitude of the input values
2803
2804Determine whether two floating point numbers are close in value.
2805
2806Return True if a is close in value to b, and False otherwise.
2807
2808For the values to be considered close, the difference between them
2809must be smaller than at least one of the tolerances.
2810
2811-inf, inf and NaN behave similarly to the IEEE 754 Standard. That
2812is, NaN is not close to anything, even itself. inf and -inf are
2813only close to themselves.
2814[clinic start generated code]*/
2815
2816static int
2817math_isclose_impl(PyObject *module, double a, double b, double rel_tol,
2818 double abs_tol)
2819/*[clinic end generated code: output=b73070207511952d input=f28671871ea5bfba]*/
Tal Einatd5519ed2015-05-31 22:05:00 +03002820{
Tal Einatd5519ed2015-05-31 22:05:00 +03002821 double diff = 0.0;
Tal Einatd5519ed2015-05-31 22:05:00 +03002822
2823 /* sanity check on the inputs */
2824 if (rel_tol < 0.0 || abs_tol < 0.0 ) {
2825 PyErr_SetString(PyExc_ValueError,
2826 "tolerances must be non-negative");
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002827 return -1;
Tal Einatd5519ed2015-05-31 22:05:00 +03002828 }
2829
2830 if ( a == b ) {
2831 /* short circuit exact equality -- needed to catch two infinities of
2832 the same sign. And perhaps speeds things up a bit sometimes.
2833 */
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002834 return 1;
Tal Einatd5519ed2015-05-31 22:05:00 +03002835 }
2836
2837 /* This catches the case of two infinities of opposite sign, or
2838 one infinity and one finite number. Two infinities of opposite
2839 sign would otherwise have an infinite relative tolerance.
2840 Two infinities of the same sign are caught by the equality check
2841 above.
2842 */
2843
2844 if (Py_IS_INFINITY(a) || Py_IS_INFINITY(b)) {
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002845 return 0;
Tal Einatd5519ed2015-05-31 22:05:00 +03002846 }
2847
2848 /* now do the regular computation
2849 this is essentially the "weak" test from the Boost library
2850 */
2851
2852 diff = fabs(b - a);
2853
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002854 return (((diff <= fabs(rel_tol * b)) ||
2855 (diff <= fabs(rel_tol * a))) ||
2856 (diff <= abs_tol));
Tal Einatd5519ed2015-05-31 22:05:00 +03002857}
2858
Pablo Galindo04114112019-03-09 19:18:08 +00002859static inline int
2860_check_long_mult_overflow(long a, long b) {
2861
2862 /* From Python2's int_mul code:
2863
2864 Integer overflow checking for * is painful: Python tried a couple ways, but
2865 they didn't work on all platforms, or failed in endcases (a product of
2866 -sys.maxint-1 has been a particular pain).
2867
2868 Here's another way:
2869
2870 The native long product x*y is either exactly right or *way* off, being
2871 just the last n bits of the true product, where n is the number of bits
2872 in a long (the delivered product is the true product plus i*2**n for
2873 some integer i).
2874
2875 The native double product (double)x * (double)y is subject to three
2876 rounding errors: on a sizeof(long)==8 box, each cast to double can lose
2877 info, and even on a sizeof(long)==4 box, the multiplication can lose info.
2878 But, unlike the native long product, it's not in *range* trouble: even
2879 if sizeof(long)==32 (256-bit longs), the product easily fits in the
2880 dynamic range of a double. So the leading 50 (or so) bits of the double
2881 product are correct.
2882
2883 We check these two ways against each other, and declare victory if they're
2884 approximately the same. Else, because the native long product is the only
2885 one that can lose catastrophic amounts of information, it's the native long
2886 product that must have overflowed.
2887
2888 */
2889
2890 long longprod = (long)((unsigned long)a * b);
2891 double doubleprod = (double)a * (double)b;
2892 double doubled_longprod = (double)longprod;
2893
2894 if (doubled_longprod == doubleprod) {
2895 return 0;
2896 }
2897
2898 const double diff = doubled_longprod - doubleprod;
2899 const double absdiff = diff >= 0.0 ? diff : -diff;
2900 const double absprod = doubleprod >= 0.0 ? doubleprod : -doubleprod;
2901
2902 if (32.0 * absdiff <= absprod) {
2903 return 0;
2904 }
2905
2906 return 1;
2907}
Tal Einatd5519ed2015-05-31 22:05:00 +03002908
Pablo Galindobc098512019-02-07 07:04:02 +00002909/*[clinic input]
2910math.prod
2911
2912 iterable: object
2913 /
2914 *
2915 start: object(c_default="NULL") = 1
2916
2917Calculate the product of all the elements in the input iterable.
2918
2919The default start value for the product is 1.
2920
2921When the iterable is empty, return the start value. This function is
2922intended specifically for use with numeric values and may reject
2923non-numeric types.
2924[clinic start generated code]*/
2925
2926static PyObject *
2927math_prod_impl(PyObject *module, PyObject *iterable, PyObject *start)
2928/*[clinic end generated code: output=36153bedac74a198 input=4c5ab0682782ed54]*/
2929{
2930 PyObject *result = start;
2931 PyObject *temp, *item, *iter;
2932
2933 iter = PyObject_GetIter(iterable);
2934 if (iter == NULL) {
2935 return NULL;
2936 }
2937
2938 if (result == NULL) {
2939 result = PyLong_FromLong(1);
2940 if (result == NULL) {
2941 Py_DECREF(iter);
2942 return NULL;
2943 }
2944 } else {
2945 Py_INCREF(result);
2946 }
2947#ifndef SLOW_PROD
2948 /* Fast paths for integers keeping temporary products in C.
2949 * Assumes all inputs are the same type.
2950 * If the assumption fails, default to use PyObjects instead.
2951 */
2952 if (PyLong_CheckExact(result)) {
2953 int overflow;
2954 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2955 /* If this already overflowed, don't even enter the loop. */
2956 if (overflow == 0) {
2957 Py_DECREF(result);
2958 result = NULL;
2959 }
2960 /* Loop over all the items in the iterable until we finish, we overflow
2961 * or we found a non integer element */
2962 while(result == NULL) {
2963 item = PyIter_Next(iter);
2964 if (item == NULL) {
2965 Py_DECREF(iter);
2966 if (PyErr_Occurred()) {
2967 return NULL;
2968 }
2969 return PyLong_FromLong(i_result);
2970 }
2971 if (PyLong_CheckExact(item)) {
2972 long b = PyLong_AsLongAndOverflow(item, &overflow);
Pablo Galindo04114112019-03-09 19:18:08 +00002973 if (overflow == 0 && !_check_long_mult_overflow(i_result, b)) {
2974 long x = i_result * b;
Pablo Galindobc098512019-02-07 07:04:02 +00002975 i_result = x;
2976 Py_DECREF(item);
2977 continue;
2978 }
2979 }
2980 /* Either overflowed or is not an int.
2981 * Restore real objects and process normally */
2982 result = PyLong_FromLong(i_result);
2983 if (result == NULL) {
2984 Py_DECREF(item);
2985 Py_DECREF(iter);
2986 return NULL;
2987 }
2988 temp = PyNumber_Multiply(result, item);
2989 Py_DECREF(result);
2990 Py_DECREF(item);
2991 result = temp;
2992 if (result == NULL) {
2993 Py_DECREF(iter);
2994 return NULL;
2995 }
2996 }
2997 }
2998
2999 /* Fast paths for floats keeping temporary products in C.
3000 * Assumes all inputs are the same type.
3001 * If the assumption fails, default to use PyObjects instead.
3002 */
3003 if (PyFloat_CheckExact(result)) {
3004 double f_result = PyFloat_AS_DOUBLE(result);
3005 Py_DECREF(result);
3006 result = NULL;
3007 while(result == NULL) {
3008 item = PyIter_Next(iter);
3009 if (item == NULL) {
3010 Py_DECREF(iter);
3011 if (PyErr_Occurred()) {
3012 return NULL;
3013 }
3014 return PyFloat_FromDouble(f_result);
3015 }
3016 if (PyFloat_CheckExact(item)) {
3017 f_result *= PyFloat_AS_DOUBLE(item);
3018 Py_DECREF(item);
3019 continue;
3020 }
3021 if (PyLong_CheckExact(item)) {
3022 long value;
3023 int overflow;
3024 value = PyLong_AsLongAndOverflow(item, &overflow);
3025 if (!overflow) {
3026 f_result *= (double)value;
3027 Py_DECREF(item);
3028 continue;
3029 }
3030 }
3031 result = PyFloat_FromDouble(f_result);
3032 if (result == NULL) {
3033 Py_DECREF(item);
3034 Py_DECREF(iter);
3035 return NULL;
3036 }
3037 temp = PyNumber_Multiply(result, item);
3038 Py_DECREF(result);
3039 Py_DECREF(item);
3040 result = temp;
3041 if (result == NULL) {
3042 Py_DECREF(iter);
3043 return NULL;
3044 }
3045 }
3046 }
3047#endif
3048 /* Consume rest of the iterable (if any) that could not be handled
3049 * by specialized functions above.*/
3050 for(;;) {
3051 item = PyIter_Next(iter);
3052 if (item == NULL) {
3053 /* error, or end-of-sequence */
3054 if (PyErr_Occurred()) {
3055 Py_DECREF(result);
3056 result = NULL;
3057 }
3058 break;
3059 }
3060 temp = PyNumber_Multiply(result, item);
3061 Py_DECREF(result);
3062 Py_DECREF(item);
3063 result = temp;
3064 if (result == NULL)
3065 break;
3066 }
3067 Py_DECREF(iter);
3068 return result;
3069}
3070
3071
Yash Aggarwal4a686502019-06-01 12:51:27 +05303072/*[clinic input]
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003073math.perm
3074
3075 n: object
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003076 k: object = None
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003077 /
3078
3079Number of ways to choose k items from n items without repetition and with order.
3080
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003081Evaluates to n! / (n - k)! when k <= n and evaluates
3082to zero when k > n.
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003083
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003084If k is not specified or is None, then k defaults to n
3085and the function returns n!.
3086
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003087Raises TypeError if either of the arguments are not integers.
3088Raises ValueError if either of the arguments are negative.
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003089[clinic start generated code]*/
3090
3091static PyObject *
3092math_perm_impl(PyObject *module, PyObject *n, PyObject *k)
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003093/*[clinic end generated code: output=e021a25469653e23 input=5311c5a00f359b53]*/
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003094{
3095 PyObject *result = NULL, *factor = NULL;
3096 int overflow, cmp;
3097 long long i, factors;
3098
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003099 if (k == Py_None) {
3100 return math_factorial(module, n);
3101 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003102 n = PyNumber_Index(n);
3103 if (n == NULL) {
3104 return NULL;
3105 }
3106 if (!PyLong_CheckExact(n)) {
3107 Py_SETREF(n, _PyLong_Copy((PyLongObject *)n));
3108 if (n == NULL) {
3109 return NULL;
3110 }
3111 }
3112 k = PyNumber_Index(k);
3113 if (k == NULL) {
3114 Py_DECREF(n);
3115 return NULL;
3116 }
3117 if (!PyLong_CheckExact(k)) {
3118 Py_SETREF(k, _PyLong_Copy((PyLongObject *)k));
3119 if (k == NULL) {
3120 Py_DECREF(n);
3121 return NULL;
3122 }
3123 }
3124
3125 if (Py_SIZE(n) < 0) {
3126 PyErr_SetString(PyExc_ValueError,
3127 "n must be a non-negative integer");
3128 goto error;
3129 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003130 if (Py_SIZE(k) < 0) {
3131 PyErr_SetString(PyExc_ValueError,
3132 "k must be a non-negative integer");
3133 goto error;
3134 }
3135
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003136 cmp = PyObject_RichCompareBool(n, k, Py_LT);
3137 if (cmp != 0) {
3138 if (cmp > 0) {
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003139 result = PyLong_FromLong(0);
3140 goto done;
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003141 }
3142 goto error;
3143 }
3144
3145 factors = PyLong_AsLongLongAndOverflow(k, &overflow);
3146 if (overflow > 0) {
3147 PyErr_Format(PyExc_OverflowError,
3148 "k must not exceed %lld",
3149 LLONG_MAX);
3150 goto error;
3151 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003152 else if (factors == -1) {
3153 /* k is nonnegative, so a return value of -1 can only indicate error */
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003154 goto error;
3155 }
3156
3157 if (factors == 0) {
3158 result = PyLong_FromLong(1);
3159 goto done;
3160 }
3161
3162 result = n;
3163 Py_INCREF(result);
3164 if (factors == 1) {
3165 goto done;
3166 }
3167
3168 factor = n;
3169 Py_INCREF(factor);
3170 for (i = 1; i < factors; ++i) {
3171 Py_SETREF(factor, PyNumber_Subtract(factor, _PyLong_One));
3172 if (factor == NULL) {
3173 goto error;
3174 }
3175 Py_SETREF(result, PyNumber_Multiply(result, factor));
3176 if (result == NULL) {
3177 goto error;
3178 }
3179 }
3180 Py_DECREF(factor);
3181
3182done:
3183 Py_DECREF(n);
3184 Py_DECREF(k);
3185 return result;
3186
3187error:
3188 Py_XDECREF(factor);
3189 Py_XDECREF(result);
3190 Py_DECREF(n);
3191 Py_DECREF(k);
3192 return NULL;
3193}
3194
3195
3196/*[clinic input]
Yash Aggarwal4a686502019-06-01 12:51:27 +05303197math.comb
3198
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003199 n: object
3200 k: object
3201 /
Yash Aggarwal4a686502019-06-01 12:51:27 +05303202
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003203Number of ways to choose k items from n items without repetition and without order.
Yash Aggarwal4a686502019-06-01 12:51:27 +05303204
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003205Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates
3206to zero when k > n.
Yash Aggarwal4a686502019-06-01 12:51:27 +05303207
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003208Also called the binomial coefficient because it is equivalent
3209to the coefficient of k-th term in polynomial expansion of the
3210expression (1 + x)**n.
3211
3212Raises TypeError if either of the arguments are not integers.
3213Raises ValueError if either of the arguments are negative.
Yash Aggarwal4a686502019-06-01 12:51:27 +05303214
3215[clinic start generated code]*/
3216
3217static PyObject *
3218math_comb_impl(PyObject *module, PyObject *n, PyObject *k)
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003219/*[clinic end generated code: output=bd2cec8d854f3493 input=9a05315af2518709]*/
Yash Aggarwal4a686502019-06-01 12:51:27 +05303220{
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003221 PyObject *result = NULL, *factor = NULL, *temp;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303222 int overflow, cmp;
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003223 long long i, factors;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303224
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003225 n = PyNumber_Index(n);
3226 if (n == NULL) {
3227 return NULL;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303228 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003229 if (!PyLong_CheckExact(n)) {
3230 Py_SETREF(n, _PyLong_Copy((PyLongObject *)n));
3231 if (n == NULL) {
3232 return NULL;
3233 }
3234 }
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003235 k = PyNumber_Index(k);
3236 if (k == NULL) {
3237 Py_DECREF(n);
3238 return NULL;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303239 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003240 if (!PyLong_CheckExact(k)) {
3241 Py_SETREF(k, _PyLong_Copy((PyLongObject *)k));
3242 if (k == NULL) {
3243 Py_DECREF(n);
3244 return NULL;
3245 }
3246 }
Yash Aggarwal4a686502019-06-01 12:51:27 +05303247
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003248 if (Py_SIZE(n) < 0) {
3249 PyErr_SetString(PyExc_ValueError,
3250 "n must be a non-negative integer");
3251 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303252 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003253 if (Py_SIZE(k) < 0) {
3254 PyErr_SetString(PyExc_ValueError,
3255 "k must be a non-negative integer");
3256 goto error;
3257 }
3258
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003259 /* k = min(k, n - k) */
3260 temp = PyNumber_Subtract(n, k);
3261 if (temp == NULL) {
3262 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303263 }
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003264 if (Py_SIZE(temp) < 0) {
3265 Py_DECREF(temp);
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003266 result = PyLong_FromLong(0);
3267 goto done;
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003268 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003269 cmp = PyObject_RichCompareBool(temp, k, Py_LT);
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003270 if (cmp > 0) {
3271 Py_SETREF(k, temp);
Yash Aggarwal4a686502019-06-01 12:51:27 +05303272 }
3273 else {
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003274 Py_DECREF(temp);
3275 if (cmp < 0) {
3276 goto error;
3277 }
Yash Aggarwal4a686502019-06-01 12:51:27 +05303278 }
3279
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003280 factors = PyLong_AsLongLongAndOverflow(k, &overflow);
3281 if (overflow > 0) {
Yash Aggarwal4a686502019-06-01 12:51:27 +05303282 PyErr_Format(PyExc_OverflowError,
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003283 "min(n - k, k) must not exceed %lld",
Yash Aggarwal4a686502019-06-01 12:51:27 +05303284 LLONG_MAX);
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003285 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303286 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003287 if (factors == -1) {
3288 /* k is nonnegative, so a return value of -1 can only indicate error */
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003289 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303290 }
3291
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003292 if (factors == 0) {
3293 result = PyLong_FromLong(1);
3294 goto done;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303295 }
3296
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003297 result = n;
3298 Py_INCREF(result);
3299 if (factors == 1) {
3300 goto done;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303301 }
3302
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003303 factor = n;
3304 Py_INCREF(factor);
3305 for (i = 1; i < factors; ++i) {
3306 Py_SETREF(factor, PyNumber_Subtract(factor, _PyLong_One));
3307 if (factor == NULL) {
3308 goto error;
3309 }
3310 Py_SETREF(result, PyNumber_Multiply(result, factor));
3311 if (result == NULL) {
3312 goto error;
3313 }
Yash Aggarwal4a686502019-06-01 12:51:27 +05303314
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003315 temp = PyLong_FromUnsignedLongLong((unsigned long long)i + 1);
3316 if (temp == NULL) {
3317 goto error;
3318 }
3319 Py_SETREF(result, PyNumber_FloorDivide(result, temp));
3320 Py_DECREF(temp);
3321 if (result == NULL) {
3322 goto error;
3323 }
3324 }
3325 Py_DECREF(factor);
Yash Aggarwal4a686502019-06-01 12:51:27 +05303326
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003327done:
3328 Py_DECREF(n);
3329 Py_DECREF(k);
3330 return result;
3331
3332error:
3333 Py_XDECREF(factor);
3334 Py_XDECREF(result);
3335 Py_DECREF(n);
3336 Py_DECREF(k);
Yash Aggarwal4a686502019-06-01 12:51:27 +05303337 return NULL;
3338}
3339
3340
Victor Stinner100fafc2020-01-12 02:15:42 +01003341/*[clinic input]
3342math.nextafter
3343
3344 x: double
3345 y: double
3346 /
3347
3348Return the next floating-point value after x towards y.
3349[clinic start generated code]*/
3350
3351static PyObject *
3352math_nextafter_impl(PyObject *module, double x, double y)
3353/*[clinic end generated code: output=750c8266c1c540ce input=02b2d50cd1d9f9b6]*/
3354{
Victor Stinner85ead4f2020-01-21 11:14:10 +01003355#if defined(_AIX)
3356 if (x == y) {
3357 /* On AIX 7.1, libm nextafter(-0.0, +0.0) returns -0.0.
3358 Bug fixed in bos.adt.libm 7.2.2.0 by APAR IV95512. */
3359 return PyFloat_FromDouble(y);
3360 }
3361#endif
3362 return PyFloat_FromDouble(nextafter(x, y));
Victor Stinner100fafc2020-01-12 02:15:42 +01003363}
3364
3365
Victor Stinner0b2ab212020-01-13 12:44:35 +01003366/*[clinic input]
3367math.ulp -> double
3368
3369 x: double
3370 /
3371
3372Return the value of the least significant bit of the float x.
3373[clinic start generated code]*/
3374
3375static double
3376math_ulp_impl(PyObject *module, double x)
3377/*[clinic end generated code: output=f5207867a9384dd4 input=31f9bfbbe373fcaa]*/
3378{
3379 if (Py_IS_NAN(x)) {
3380 return x;
3381 }
3382 x = fabs(x);
3383 if (Py_IS_INFINITY(x)) {
3384 return x;
3385 }
3386 double inf = m_inf();
3387 double x2 = nextafter(x, inf);
3388 if (Py_IS_INFINITY(x2)) {
3389 /* special case: x is the largest positive representable float */
3390 x2 = nextafter(x, -inf);
3391 return x - x2;
3392 }
3393 return x2 - x;
3394}
3395
Dong-hee Na5be82412020-03-31 23:33:22 +09003396static int
3397math_exec(PyObject *module)
3398{
3399 if (PyModule_AddObject(module, "pi", PyFloat_FromDouble(Py_MATH_PI)) < 0) {
3400 return -1;
3401 }
3402 if (PyModule_AddObject(module, "e", PyFloat_FromDouble(Py_MATH_E)) < 0) {
3403 return -1;
3404 }
3405 // 2pi
3406 if (PyModule_AddObject(module, "tau", PyFloat_FromDouble(Py_MATH_TAU)) < 0) {
3407 return -1;
3408 }
3409 if (PyModule_AddObject(module, "inf", PyFloat_FromDouble(m_inf())) < 0) {
3410 return -1;
3411 }
3412#if !defined(PY_NO_SHORT_FLOAT_REPR) || defined(Py_NAN)
3413 if (PyModule_AddObject(module, "nan", PyFloat_FromDouble(m_nan())) < 0) {
3414 return -1;
3415 }
3416#endif
3417 return 0;
3418}
Victor Stinner0b2ab212020-01-13 12:44:35 +01003419
Barry Warsaw8b43b191996-12-09 22:32:36 +00003420static PyMethodDef math_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003421 {"acos", math_acos, METH_O, math_acos_doc},
3422 {"acosh", math_acosh, METH_O, math_acosh_doc},
3423 {"asin", math_asin, METH_O, math_asin_doc},
3424 {"asinh", math_asinh, METH_O, math_asinh_doc},
3425 {"atan", math_atan, METH_O, math_atan_doc},
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003426 {"atan2", (PyCFunction)(void(*)(void))math_atan2, METH_FASTCALL, math_atan2_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003427 {"atanh", math_atanh, METH_O, math_atanh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003428 MATH_CEIL_METHODDEF
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003429 {"copysign", (PyCFunction)(void(*)(void))math_copysign, METH_FASTCALL, math_copysign_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003430 {"cos", math_cos, METH_O, math_cos_doc},
3431 {"cosh", math_cosh, METH_O, math_cosh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003432 MATH_DEGREES_METHODDEF
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07003433 MATH_DIST_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003434 {"erf", math_erf, METH_O, math_erf_doc},
3435 {"erfc", math_erfc, METH_O, math_erfc_doc},
3436 {"exp", math_exp, METH_O, math_exp_doc},
3437 {"expm1", math_expm1, METH_O, math_expm1_doc},
3438 {"fabs", math_fabs, METH_O, math_fabs_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003439 MATH_FACTORIAL_METHODDEF
3440 MATH_FLOOR_METHODDEF
3441 MATH_FMOD_METHODDEF
3442 MATH_FREXP_METHODDEF
3443 MATH_FSUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003444 {"gamma", math_gamma, METH_O, math_gamma_doc},
Serhiy Storchaka559e7f12020-02-23 13:21:29 +02003445 {"gcd", (PyCFunction)(void(*)(void))math_gcd, METH_FASTCALL, math_gcd_doc},
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003446 {"hypot", (PyCFunction)(void(*)(void))math_hypot, METH_FASTCALL, math_hypot_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003447 MATH_ISCLOSE_METHODDEF
3448 MATH_ISFINITE_METHODDEF
3449 MATH_ISINF_METHODDEF
3450 MATH_ISNAN_METHODDEF
Mark Dickinson73934b92019-05-18 12:29:50 +01003451 MATH_ISQRT_METHODDEF
Serhiy Storchaka559e7f12020-02-23 13:21:29 +02003452 {"lcm", (PyCFunction)(void(*)(void))math_lcm, METH_FASTCALL, math_lcm_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003453 MATH_LDEXP_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003454 {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003455 MATH_LOG_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003456 {"log1p", math_log1p, METH_O, math_log1p_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003457 MATH_LOG10_METHODDEF
3458 MATH_LOG2_METHODDEF
3459 MATH_MODF_METHODDEF
3460 MATH_POW_METHODDEF
3461 MATH_RADIANS_METHODDEF
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003462 {"remainder", (PyCFunction)(void(*)(void))math_remainder, METH_FASTCALL, math_remainder_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003463 {"sin", math_sin, METH_O, math_sin_doc},
3464 {"sinh", math_sinh, METH_O, math_sinh_doc},
3465 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
3466 {"tan", math_tan, METH_O, math_tan_doc},
3467 {"tanh", math_tanh, METH_O, math_tanh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003468 MATH_TRUNC_METHODDEF
Pablo Galindobc098512019-02-07 07:04:02 +00003469 MATH_PROD_METHODDEF
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003470 MATH_PERM_METHODDEF
Yash Aggarwal4a686502019-06-01 12:51:27 +05303471 MATH_COMB_METHODDEF
Victor Stinner100fafc2020-01-12 02:15:42 +01003472 MATH_NEXTAFTER_METHODDEF
Victor Stinner0b2ab212020-01-13 12:44:35 +01003473 MATH_ULP_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003474 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003475};
3476
Dong-hee Na5be82412020-03-31 23:33:22 +09003477static PyModuleDef_Slot math_slots[] = {
3478 {Py_mod_exec, math_exec},
3479 {0, NULL}
3480};
Guido van Rossumc6e22901998-12-04 19:26:43 +00003481
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003482PyDoc_STRVAR(module_doc,
Ned Batchelder6faad352019-05-17 05:59:14 -04003483"This module provides access to the mathematical functions\n"
3484"defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00003485
Martin v. Löwis1a214512008-06-11 05:26:20 +00003486static struct PyModuleDef mathmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003487 PyModuleDef_HEAD_INIT,
Dong-hee Na5be82412020-03-31 23:33:22 +09003488 .m_name = "math",
3489 .m_doc = module_doc,
3490 .m_size = 0,
3491 .m_methods = math_methods,
3492 .m_slots = math_slots,
Martin v. Löwis1a214512008-06-11 05:26:20 +00003493};
3494
Mark Hammondfe51c6d2002-08-02 02:27:13 +00003495PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003496PyInit_math(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003497{
Dong-hee Na5be82412020-03-31 23:33:22 +09003498 return PyModuleDef_Init(&mathmodule);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003499}