blob: 4450ce1894102056e971f35d23f7d353b3175ab2 [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"
Niklas Fiekas794e7d12020-06-15 14:33:48 +020056#include "pycore_bitutils.h" // _Py_bit_length()
Victor Stinnere9e7d282020-02-12 22:54:42 +010057#include "pycore_dtoa.h"
Mark Dickinson664b5112009-12-16 20:23:42 +000058#include "_math.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000059
Serhiy Storchakac9ea9332017-01-19 18:13:09 +020060#include "clinic/mathmodule.c.h"
61
62/*[clinic input]
63module math
64[clinic start generated code]*/
65/*[clinic end generated code: output=da39a3ee5e6b4b0d input=76bc7002685dd942]*/
66
67
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000068/*
69 sin(pi*x), giving accurate results for all finite x (especially x
70 integral or close to an integer). This is here for use in the
71 reflection formula for the gamma function. It conforms to IEEE
72 754-2008 for finite arguments, but not for infinities or nans.
73*/
Tim Petersa40c7932001-09-05 22:36:56 +000074
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000075static const double pi = 3.141592653589793238462643383279502884197;
Mark Dickinson9c91eb82010-07-07 16:17:31 +000076static const double logpi = 1.144729885849400174143427351353058711647;
Louie Lu7a264642017-03-31 01:05:10 +080077#if !defined(HAVE_ERF) || !defined(HAVE_ERFC)
78static const double sqrtpi = 1.772453850905516027298167483341145182798;
79#endif /* !defined(HAVE_ERF) || !defined(HAVE_ERFC) */
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000080
Raymond Hettingercfd735e2019-01-29 20:39:53 -080081
82/* Version of PyFloat_AsDouble() with in-line fast paths
83 for exact floats and integers. Gives a substantial
84 speed improvement for extracting float arguments.
85*/
86
87#define ASSIGN_DOUBLE(target_var, obj, error_label) \
88 if (PyFloat_CheckExact(obj)) { \
89 target_var = PyFloat_AS_DOUBLE(obj); \
90 } \
91 else if (PyLong_CheckExact(obj)) { \
92 target_var = PyLong_AsDouble(obj); \
93 if (target_var == -1.0 && PyErr_Occurred()) { \
94 goto error_label; \
95 } \
96 } \
97 else { \
98 target_var = PyFloat_AsDouble(obj); \
99 if (target_var == -1.0 && PyErr_Occurred()) { \
100 goto error_label; \
101 } \
102 }
103
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000104static double
Dima Pasechnikf57cd822019-02-26 06:36:11 +0000105m_sinpi(double x)
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000106{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107 double y, r;
108 int n;
109 /* this function should only ever be called for finite arguments */
110 assert(Py_IS_FINITE(x));
111 y = fmod(fabs(x), 2.0);
112 n = (int)round(2.0*y);
113 assert(0 <= n && n <= 4);
114 switch (n) {
115 case 0:
116 r = sin(pi*y);
117 break;
118 case 1:
119 r = cos(pi*(y-0.5));
120 break;
121 case 2:
122 /* N.B. -sin(pi*(y-1.0)) is *not* equivalent: it would give
123 -0.0 instead of 0.0 when y == 1.0. */
124 r = sin(pi*(1.0-y));
125 break;
126 case 3:
127 r = -cos(pi*(y-1.5));
128 break;
129 case 4:
130 r = sin(pi*(y-2.0));
131 break;
132 default:
Barry Warsawb2e57942017-09-14 18:13:16 -0700133 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 }
135 return copysign(1.0, x)*r;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000136}
137
138/* Implementation of the real gamma function. In extensive but non-exhaustive
139 random tests, this function proved accurate to within <= 10 ulps across the
140 entire float domain. Note that accuracy may depend on the quality of the
141 system math functions, the pow function in particular. Special cases
142 follow C99 annex F. The parameters and method are tailored to platforms
143 whose double format is the IEEE 754 binary64 format.
144
145 Method: for x > 0.0 we use the Lanczos approximation with parameters N=13
146 and g=6.024680040776729583740234375; these parameters are amongst those
147 used by the Boost library. Following Boost (again), we re-express the
148 Lanczos sum as a rational function, and compute it that way. The
149 coefficients below were computed independently using MPFR, and have been
150 double-checked against the coefficients in the Boost source code.
151
152 For x < 0.0 we use the reflection formula.
153
154 There's one minor tweak that deserves explanation: Lanczos' formula for
155 Gamma(x) involves computing pow(x+g-0.5, x-0.5) / exp(x+g-0.5). For many x
156 values, x+g-0.5 can be represented exactly. However, in cases where it
157 can't be represented exactly the small error in x+g-0.5 can be magnified
158 significantly by the pow and exp calls, especially for large x. A cheap
159 correction is to multiply by (1 + e*g/(x+g-0.5)), where e is the error
160 involved in the computation of x+g-0.5 (that is, e = computed value of
161 x+g-0.5 - exact value of x+g-0.5). Here's the proof:
162
163 Correction factor
164 -----------------
165 Write x+g-0.5 = y-e, where y is exactly representable as an IEEE 754
166 double, and e is tiny. Then:
167
168 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) = pow(y-e, x-0.5)/exp(y-e)
169 = pow(y, x-0.5)/exp(y) * C,
170
171 where the correction_factor C is given by
172
173 C = pow(1-e/y, x-0.5) * exp(e)
174
175 Since e is tiny, pow(1-e/y, x-0.5) ~ 1-(x-0.5)*e/y, and exp(x) ~ 1+e, so:
176
177 C ~ (1-(x-0.5)*e/y) * (1+e) ~ 1 + e*(y-(x-0.5))/y
178
179 But y-(x-0.5) = g+e, and g+e ~ g. So we get C ~ 1 + e*g/y, and
180
181 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) ~ pow(y, x-0.5)/exp(y) * (1 + e*g/y),
182
183 Note that for accuracy, when computing r*C it's better to do
184
185 r + e*g/y*r;
186
187 than
188
189 r * (1 + e*g/y);
190
191 since the addition in the latter throws away most of the bits of
192 information in e*g/y.
193*/
194
195#define LANCZOS_N 13
196static const double lanczos_g = 6.024680040776729583740234375;
197static const double lanczos_g_minus_half = 5.524680040776729583740234375;
198static const double lanczos_num_coeffs[LANCZOS_N] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 23531376880.410759688572007674451636754734846804940,
200 42919803642.649098768957899047001988850926355848959,
201 35711959237.355668049440185451547166705960488635843,
202 17921034426.037209699919755754458931112671403265390,
203 6039542586.3520280050642916443072979210699388420708,
204 1439720407.3117216736632230727949123939715485786772,
205 248874557.86205415651146038641322942321632125127801,
206 31426415.585400194380614231628318205362874684987640,
207 2876370.6289353724412254090516208496135991145378768,
208 186056.26539522349504029498971604569928220784236328,
209 8071.6720023658162106380029022722506138218516325024,
210 210.82427775157934587250973392071336271166969580291,
211 2.5066282746310002701649081771338373386264310793408
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000212};
213
214/* denominator is x*(x+1)*...*(x+LANCZOS_N-2) */
215static const double lanczos_den_coeffs[LANCZOS_N] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000216 0.0, 39916800.0, 120543840.0, 150917976.0, 105258076.0, 45995730.0,
217 13339535.0, 2637558.0, 357423.0, 32670.0, 1925.0, 66.0, 1.0};
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000218
219/* gamma values for small positive integers, 1 though NGAMMA_INTEGRAL */
220#define NGAMMA_INTEGRAL 23
221static const double gamma_integral[NGAMMA_INTEGRAL] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0,
223 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0,
224 1307674368000.0, 20922789888000.0, 355687428096000.0,
225 6402373705728000.0, 121645100408832000.0, 2432902008176640000.0,
226 51090942171709440000.0, 1124000727777607680000.0,
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000227};
228
229/* Lanczos' sum L_g(x), for positive x */
230
231static double
232lanczos_sum(double x)
233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 double num = 0.0, den = 0.0;
235 int i;
236 assert(x > 0.0);
237 /* evaluate the rational function lanczos_sum(x). For large
238 x, the obvious algorithm risks overflow, so we instead
239 rescale the denominator and numerator of the rational
240 function by x**(1-LANCZOS_N) and treat this as a
241 rational function in 1/x. This also reduces the error for
242 larger x values. The choice of cutoff point (5.0 below) is
243 somewhat arbitrary; in tests, smaller cutoff values than
244 this resulted in lower accuracy. */
245 if (x < 5.0) {
246 for (i = LANCZOS_N; --i >= 0; ) {
247 num = num * x + lanczos_num_coeffs[i];
248 den = den * x + lanczos_den_coeffs[i];
249 }
250 }
251 else {
252 for (i = 0; i < LANCZOS_N; i++) {
253 num = num / x + lanczos_num_coeffs[i];
254 den = den / x + lanczos_den_coeffs[i];
255 }
256 }
257 return num/den;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000258}
259
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +0000260/* Constant for +infinity, generated in the same way as float('inf'). */
261
262static double
263m_inf(void)
264{
265#ifndef PY_NO_SHORT_FLOAT_REPR
266 return _Py_dg_infinity(0);
267#else
268 return Py_HUGE_VAL;
269#endif
270}
271
272/* Constant nan value, generated in the same way as float('nan'). */
273/* We don't currently assume that Py_NAN is defined everywhere. */
274
275#if !defined(PY_NO_SHORT_FLOAT_REPR) || defined(Py_NAN)
276
277static double
278m_nan(void)
279{
280#ifndef PY_NO_SHORT_FLOAT_REPR
281 return _Py_dg_stdnan(0);
282#else
283 return Py_NAN;
284#endif
285}
286
287#endif
288
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000289static double
290m_tgamma(double x)
291{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 double absx, r, y, z, sqrtpow;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 /* special cases */
295 if (!Py_IS_FINITE(x)) {
296 if (Py_IS_NAN(x) || x > 0.0)
297 return x; /* tgamma(nan) = nan, tgamma(inf) = inf */
298 else {
299 errno = EDOM;
300 return Py_NAN; /* tgamma(-inf) = nan, invalid */
301 }
302 }
303 if (x == 0.0) {
304 errno = EDOM;
Mark Dickinson50203a62011-09-25 15:26:43 +0100305 /* tgamma(+-0.0) = +-inf, divide-by-zero */
306 return copysign(Py_HUGE_VAL, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 /* integer arguments */
310 if (x == floor(x)) {
311 if (x < 0.0) {
312 errno = EDOM; /* tgamma(n) = nan, invalid for */
313 return Py_NAN; /* negative integers n */
314 }
315 if (x <= NGAMMA_INTEGRAL)
316 return gamma_integral[(int)x - 1];
317 }
318 absx = fabs(x);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 /* tiny arguments: tgamma(x) ~ 1/x for x near 0 */
321 if (absx < 1e-20) {
322 r = 1.0/x;
323 if (Py_IS_INFINITY(r))
324 errno = ERANGE;
325 return r;
326 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 /* large arguments: assuming IEEE 754 doubles, tgamma(x) overflows for
329 x > 200, and underflows to +-0.0 for x < -200, not a negative
330 integer. */
331 if (absx > 200.0) {
332 if (x < 0.0) {
Dima Pasechnikf57cd822019-02-26 06:36:11 +0000333 return 0.0/m_sinpi(x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 }
335 else {
336 errno = ERANGE;
337 return Py_HUGE_VAL;
338 }
339 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 y = absx + lanczos_g_minus_half;
342 /* compute error in sum */
343 if (absx > lanczos_g_minus_half) {
344 /* note: the correction can be foiled by an optimizing
345 compiler that (incorrectly) thinks that an expression like
346 a + b - a - b can be optimized to 0.0. This shouldn't
347 happen in a standards-conforming compiler. */
348 double q = y - absx;
349 z = q - lanczos_g_minus_half;
350 }
351 else {
352 double q = y - lanczos_g_minus_half;
353 z = q - absx;
354 }
355 z = z * lanczos_g / y;
356 if (x < 0.0) {
Dima Pasechnikf57cd822019-02-26 06:36:11 +0000357 r = -pi / m_sinpi(absx) / absx * exp(y) / lanczos_sum(absx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 r -= z * r;
359 if (absx < 140.0) {
360 r /= pow(y, absx - 0.5);
361 }
362 else {
363 sqrtpow = pow(y, absx / 2.0 - 0.25);
364 r /= sqrtpow;
365 r /= sqrtpow;
366 }
367 }
368 else {
369 r = lanczos_sum(absx) / exp(y);
370 r += z * r;
371 if (absx < 140.0) {
372 r *= pow(y, absx - 0.5);
373 }
374 else {
375 sqrtpow = pow(y, absx / 2.0 - 0.25);
376 r *= sqrtpow;
377 r *= sqrtpow;
378 }
379 }
380 if (Py_IS_INFINITY(r))
381 errno = ERANGE;
382 return r;
Guido van Rossum8832b621991-12-16 15:44:24 +0000383}
384
Christian Heimes53876d92008-04-19 00:31:39 +0000385/*
Mark Dickinson05d2e082009-12-11 20:17:17 +0000386 lgamma: natural log of the absolute value of the Gamma function.
387 For large arguments, Lanczos' formula works extremely well here.
388*/
389
390static double
391m_lgamma(double x)
392{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200393 double r;
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200394 double absx;
Mark Dickinson05d2e082009-12-11 20:17:17 +0000395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 /* special cases */
397 if (!Py_IS_FINITE(x)) {
398 if (Py_IS_NAN(x))
399 return x; /* lgamma(nan) = nan */
400 else
401 return Py_HUGE_VAL; /* lgamma(+-inf) = +inf */
402 }
Mark Dickinson05d2e082009-12-11 20:17:17 +0000403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 /* integer arguments */
405 if (x == floor(x) && x <= 2.0) {
406 if (x <= 0.0) {
407 errno = EDOM; /* lgamma(n) = inf, divide-by-zero for */
408 return Py_HUGE_VAL; /* integers n <= 0 */
409 }
410 else {
411 return 0.0; /* lgamma(1) = lgamma(2) = 0.0 */
412 }
413 }
Mark Dickinson05d2e082009-12-11 20:17:17 +0000414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 absx = fabs(x);
416 /* tiny arguments: lgamma(x) ~ -log(fabs(x)) for small x */
417 if (absx < 1e-20)
418 return -log(absx);
Mark Dickinson05d2e082009-12-11 20:17:17 +0000419
Mark Dickinson9c91eb82010-07-07 16:17:31 +0000420 /* Lanczos' formula. We could save a fraction of a ulp in accuracy by
421 having a second set of numerator coefficients for lanczos_sum that
422 absorbed the exp(-lanczos_g) term, and throwing out the lanczos_g
423 subtraction below; it's probably not worth it. */
424 r = log(lanczos_sum(absx)) - lanczos_g;
425 r += (absx - 0.5) * (log(absx + lanczos_g - 0.5) - 1);
426 if (x < 0.0)
427 /* Use reflection formula to get value for negative x. */
Dima Pasechnikf57cd822019-02-26 06:36:11 +0000428 r = logpi - log(fabs(m_sinpi(absx))) - log(absx) - r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 if (Py_IS_INFINITY(r))
430 errno = ERANGE;
431 return r;
Mark Dickinson05d2e082009-12-11 20:17:17 +0000432}
433
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200434#if !defined(HAVE_ERF) || !defined(HAVE_ERFC)
435
Mark Dickinson45f992a2009-12-19 11:20:49 +0000436/*
437 Implementations of the error function erf(x) and the complementary error
438 function erfc(x).
439
Brett Cannon45adb312016-01-15 09:38:24 -0800440 Method: we use a series approximation for erf for small x, and a continued
441 fraction approximation for erfc(x) for larger x;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000442 combined with the relations erf(-x) = -erf(x) and erfc(x) = 1.0 - erf(x),
443 this gives us erf(x) and erfc(x) for all x.
444
445 The series expansion used is:
446
447 erf(x) = x*exp(-x*x)/sqrt(pi) * [
448 2/1 + 4/3 x**2 + 8/15 x**4 + 16/105 x**6 + ...]
449
450 The coefficient of x**(2k-2) here is 4**k*factorial(k)/factorial(2*k).
451 This series converges well for smallish x, but slowly for larger x.
452
453 The continued fraction expansion used is:
454
455 erfc(x) = x*exp(-x*x)/sqrt(pi) * [1/(0.5 + x**2 -) 0.5/(2.5 + x**2 - )
456 3.0/(4.5 + x**2 - ) 7.5/(6.5 + x**2 - ) ...]
457
458 after the first term, the general term has the form:
459
460 k*(k-0.5)/(2*k+0.5 + x**2 - ...).
461
462 This expansion converges fast for larger x, but convergence becomes
463 infinitely slow as x approaches 0.0. The (somewhat naive) continued
464 fraction evaluation algorithm used below also risks overflow for large x;
465 but for large x, erfc(x) == 0.0 to within machine precision. (For
466 example, erfc(30.0) is approximately 2.56e-393).
467
468 Parameters: use series expansion for abs(x) < ERF_SERIES_CUTOFF and
469 continued fraction expansion for ERF_SERIES_CUTOFF <= abs(x) <
470 ERFC_CONTFRAC_CUTOFF. ERFC_SERIES_TERMS and ERFC_CONTFRAC_TERMS are the
471 numbers of terms to use for the relevant expansions. */
472
473#define ERF_SERIES_CUTOFF 1.5
474#define ERF_SERIES_TERMS 25
475#define ERFC_CONTFRAC_CUTOFF 30.0
476#define ERFC_CONTFRAC_TERMS 50
477
478/*
479 Error function, via power series.
480
481 Given a finite float x, return an approximation to erf(x).
482 Converges reasonably fast for small x.
483*/
484
485static double
486m_erf_series(double x)
487{
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000488 double x2, acc, fk, result;
489 int i, saved_errno;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 x2 = x * x;
492 acc = 0.0;
493 fk = (double)ERF_SERIES_TERMS + 0.5;
494 for (i = 0; i < ERF_SERIES_TERMS; i++) {
495 acc = 2.0 + x2 * acc / fk;
496 fk -= 1.0;
497 }
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000498 /* Make sure the exp call doesn't affect errno;
499 see m_erfc_contfrac for more. */
500 saved_errno = errno;
501 result = acc * x * exp(-x2) / sqrtpi;
502 errno = saved_errno;
503 return result;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000504}
505
506/*
507 Complementary error function, via continued fraction expansion.
508
509 Given a positive float x, return an approximation to erfc(x). Converges
510 reasonably fast for x large (say, x > 2.0), and should be safe from
511 overflow if x and nterms are not too large. On an IEEE 754 machine, with x
512 <= 30.0, we're safe up to nterms = 100. For x >= 30.0, erfc(x) is smaller
513 than the smallest representable nonzero float. */
514
515static double
516m_erfc_contfrac(double x)
517{
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000518 double x2, a, da, p, p_last, q, q_last, b, result;
519 int i, saved_errno;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 if (x >= ERFC_CONTFRAC_CUTOFF)
522 return 0.0;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 x2 = x*x;
525 a = 0.0;
526 da = 0.5;
527 p = 1.0; p_last = 0.0;
528 q = da + x2; q_last = 1.0;
529 for (i = 0; i < ERFC_CONTFRAC_TERMS; i++) {
530 double temp;
531 a += da;
532 da += 2.0;
533 b = da + x2;
534 temp = p; p = b*p - a*p_last; p_last = temp;
535 temp = q; q = b*q - a*q_last; q_last = temp;
536 }
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000537 /* Issue #8986: On some platforms, exp sets errno on underflow to zero;
538 save the current errno value so that we can restore it later. */
539 saved_errno = errno;
540 result = p / q * x * exp(-x2) / sqrtpi;
541 errno = saved_errno;
542 return result;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000543}
544
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200545#endif /* !defined(HAVE_ERF) || !defined(HAVE_ERFC) */
546
Mark Dickinson45f992a2009-12-19 11:20:49 +0000547/* Error function erf(x), for general x */
548
549static double
550m_erf(double x)
551{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200552#ifdef HAVE_ERF
553 return erf(x);
554#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 double absx, cf;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 if (Py_IS_NAN(x))
558 return x;
559 absx = fabs(x);
560 if (absx < ERF_SERIES_CUTOFF)
561 return m_erf_series(x);
562 else {
563 cf = m_erfc_contfrac(absx);
564 return x > 0.0 ? 1.0 - cf : cf - 1.0;
565 }
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200566#endif
Mark Dickinson45f992a2009-12-19 11:20:49 +0000567}
568
569/* Complementary error function erfc(x), for general x. */
570
571static double
572m_erfc(double x)
573{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200574#ifdef HAVE_ERFC
575 return erfc(x);
576#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 double absx, cf;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 if (Py_IS_NAN(x))
580 return x;
581 absx = fabs(x);
582 if (absx < ERF_SERIES_CUTOFF)
583 return 1.0 - m_erf_series(x);
584 else {
585 cf = m_erfc_contfrac(absx);
586 return x > 0.0 ? cf : 2.0 - cf;
587 }
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200588#endif
Mark Dickinson45f992a2009-12-19 11:20:49 +0000589}
Mark Dickinson05d2e082009-12-11 20:17:17 +0000590
591/*
Christian Heimese57950f2008-04-21 13:08:03 +0000592 wrapper for atan2 that deals directly with special cases before
593 delegating to the platform libm for the remaining cases. This
594 is necessary to get consistent behaviour across platforms.
595 Windows, FreeBSD and alpha Tru64 are amongst platforms that don't
596 always follow C99.
597*/
598
599static double
600m_atan2(double y, double x)
601{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 if (Py_IS_NAN(x) || Py_IS_NAN(y))
603 return Py_NAN;
604 if (Py_IS_INFINITY(y)) {
605 if (Py_IS_INFINITY(x)) {
606 if (copysign(1., x) == 1.)
607 /* atan2(+-inf, +inf) == +-pi/4 */
608 return copysign(0.25*Py_MATH_PI, y);
609 else
610 /* atan2(+-inf, -inf) == +-pi*3/4 */
611 return copysign(0.75*Py_MATH_PI, y);
612 }
613 /* atan2(+-inf, x) == +-pi/2 for finite x */
614 return copysign(0.5*Py_MATH_PI, y);
615 }
616 if (Py_IS_INFINITY(x) || y == 0.) {
617 if (copysign(1., x) == 1.)
618 /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */
619 return copysign(0., y);
620 else
621 /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */
622 return copysign(Py_MATH_PI, y);
623 }
624 return atan2(y, x);
Christian Heimese57950f2008-04-21 13:08:03 +0000625}
626
Mark Dickinsona0ce3752017-04-05 18:34:27 +0100627
628/* IEEE 754-style remainder operation: x - n*y where n*y is the nearest
629 multiple of y to x, taking n even in the case of a tie. Assuming an IEEE 754
630 binary floating-point format, the result is always exact. */
631
632static double
633m_remainder(double x, double y)
634{
635 /* Deal with most common case first. */
636 if (Py_IS_FINITE(x) && Py_IS_FINITE(y)) {
637 double absx, absy, c, m, r;
638
639 if (y == 0.0) {
640 return Py_NAN;
641 }
642
643 absx = fabs(x);
644 absy = fabs(y);
645 m = fmod(absx, absy);
646
647 /*
648 Warning: some subtlety here. What we *want* to know at this point is
649 whether the remainder m is less than, equal to, or greater than half
650 of absy. However, we can't do that comparison directly because we
Mark Dickinson01484702019-07-13 16:50:03 +0100651 can't be sure that 0.5*absy is representable (the multiplication
Mark Dickinsona0ce3752017-04-05 18:34:27 +0100652 might incur precision loss due to underflow). So instead we compare
653 m with the complement c = absy - m: m < 0.5*absy if and only if m <
654 c, and so on. The catch is that absy - m might also not be
655 representable, but it turns out that it doesn't matter:
656
657 - if m > 0.5*absy then absy - m is exactly representable, by
658 Sterbenz's lemma, so m > c
659 - if m == 0.5*absy then again absy - m is exactly representable
660 and m == c
661 - if m < 0.5*absy then either (i) 0.5*absy is exactly representable,
662 in which case 0.5*absy < absy - m, so 0.5*absy <= c and hence m <
663 c, or (ii) absy is tiny, either subnormal or in the lowest normal
664 binade. Then absy - m is exactly representable and again m < c.
665 */
666
667 c = absy - m;
668 if (m < c) {
669 r = m;
670 }
671 else if (m > c) {
672 r = -c;
673 }
674 else {
675 /*
676 Here absx is exactly halfway between two multiples of absy,
677 and we need to choose the even multiple. x now has the form
678
679 absx = n * absy + m
680
681 for some integer n (recalling that m = 0.5*absy at this point).
682 If n is even we want to return m; if n is odd, we need to
683 return -m.
684
685 So
686
687 0.5 * (absx - m) = (n/2) * absy
688
689 and now reducing modulo absy gives us:
690
691 | m, if n is odd
692 fmod(0.5 * (absx - m), absy) = |
693 | 0, if n is even
694
695 Now m - 2.0 * fmod(...) gives the desired result: m
696 if n is even, -m if m is odd.
697
698 Note that all steps in fmod(0.5 * (absx - m), absy)
699 will be computed exactly, with no rounding error
700 introduced.
701 */
702 assert(m == c);
703 r = m - 2.0 * fmod(0.5 * (absx - m), absy);
704 }
705 return copysign(1.0, x) * r;
706 }
707
708 /* Special values. */
709 if (Py_IS_NAN(x)) {
710 return x;
711 }
712 if (Py_IS_NAN(y)) {
713 return y;
714 }
715 if (Py_IS_INFINITY(x)) {
716 return Py_NAN;
717 }
718 assert(Py_IS_INFINITY(y));
719 return x;
720}
721
722
Christian Heimese57950f2008-04-21 13:08:03 +0000723/*
Mark Dickinsone675f082008-12-11 21:56:00 +0000724 Various platforms (Solaris, OpenBSD) do nonstandard things for log(0),
725 log(-ve), log(NaN). Here are wrappers for log and log10 that deal with
726 special values directly, passing positive non-special values through to
727 the system log/log10.
728 */
729
730static double
731m_log(double x)
732{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 if (Py_IS_FINITE(x)) {
734 if (x > 0.0)
735 return log(x);
736 errno = EDOM;
737 if (x == 0.0)
738 return -Py_HUGE_VAL; /* log(0) = -inf */
739 else
740 return Py_NAN; /* log(-ve) = nan */
741 }
742 else if (Py_IS_NAN(x))
743 return x; /* log(nan) = nan */
744 else if (x > 0.0)
745 return x; /* log(inf) = inf */
746 else {
747 errno = EDOM;
748 return Py_NAN; /* log(-inf) = nan */
749 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000750}
751
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200752/*
753 log2: log to base 2.
754
755 Uses an algorithm that should:
Mark Dickinson83b8c0b2011-05-09 08:40:20 +0100756
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200757 (a) produce exact results for powers of 2, and
Mark Dickinson83b8c0b2011-05-09 08:40:20 +0100758 (b) give a monotonic log2 (for positive finite floats),
759 assuming that the system log is monotonic.
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200760*/
761
762static double
763m_log2(double x)
764{
765 if (!Py_IS_FINITE(x)) {
766 if (Py_IS_NAN(x))
767 return x; /* log2(nan) = nan */
768 else if (x > 0.0)
769 return x; /* log2(+inf) = +inf */
770 else {
771 errno = EDOM;
772 return Py_NAN; /* log2(-inf) = nan, invalid-operation */
773 }
774 }
775
776 if (x > 0.0) {
Victor Stinner8f9f8d62011-05-09 12:45:41 +0200777#ifdef HAVE_LOG2
778 return log2(x);
779#else
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200780 double m;
781 int e;
782 m = frexp(x, &e);
783 /* We want log2(m * 2**e) == log(m) / log(2) + e. Care is needed when
784 * x is just greater than 1.0: in that case e is 1, log(m) is negative,
785 * and we get significant cancellation error from the addition of
786 * log(m) / log(2) to e. The slight rewrite of the expression below
787 * avoids this problem.
788 */
789 if (x >= 1.0) {
790 return log(2.0 * m) / log(2.0) + (e - 1);
791 }
792 else {
793 return log(m) / log(2.0) + e;
794 }
Victor Stinner8f9f8d62011-05-09 12:45:41 +0200795#endif
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200796 }
797 else if (x == 0.0) {
798 errno = EDOM;
799 return -Py_HUGE_VAL; /* log2(0) = -inf, divide-by-zero */
800 }
801 else {
802 errno = EDOM;
Mark Dickinson23442582011-05-09 08:05:00 +0100803 return Py_NAN; /* log2(-inf) = nan, invalid-operation */
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200804 }
805}
806
Mark Dickinsone675f082008-12-11 21:56:00 +0000807static double
808m_log10(double x)
809{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 if (Py_IS_FINITE(x)) {
811 if (x > 0.0)
812 return log10(x);
813 errno = EDOM;
814 if (x == 0.0)
815 return -Py_HUGE_VAL; /* log10(0) = -inf */
816 else
817 return Py_NAN; /* log10(-ve) = nan */
818 }
819 else if (Py_IS_NAN(x))
820 return x; /* log10(nan) = nan */
821 else if (x > 0.0)
822 return x; /* log10(inf) = inf */
823 else {
824 errno = EDOM;
825 return Py_NAN; /* log10(-inf) = nan */
826 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000827}
828
829
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200830static PyObject *
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200831math_gcd(PyObject *module, PyObject * const *args, Py_ssize_t nargs)
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200832{
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200833 PyObject *res, *x;
834 Py_ssize_t i;
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300835
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200836 if (nargs == 0) {
837 return PyLong_FromLong(0);
838 }
839 res = PyNumber_Index(args[0]);
840 if (res == NULL) {
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300841 return NULL;
842 }
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200843 if (nargs == 1) {
844 Py_SETREF(res, PyNumber_Absolute(res));
845 return res;
846 }
847 for (i = 1; i < nargs; i++) {
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +0300848 x = _PyNumber_Index(args[i]);
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200849 if (x == NULL) {
850 Py_DECREF(res);
851 return NULL;
852 }
853 if (res == _PyLong_One) {
854 /* Fast path: just check arguments.
855 It is okay to use identity comparison here. */
856 Py_DECREF(x);
857 continue;
858 }
859 Py_SETREF(res, _PyLong_GCD(res, x));
860 Py_DECREF(x);
861 if (res == NULL) {
862 return NULL;
863 }
864 }
865 return res;
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300866}
867
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200868PyDoc_STRVAR(math_gcd_doc,
869"gcd($module, *integers)\n"
870"--\n"
871"\n"
872"Greatest Common Divisor.");
873
874
875static PyObject *
876long_lcm(PyObject *a, PyObject *b)
877{
878 PyObject *g, *m, *f, *ab;
879
880 if (Py_SIZE(a) == 0 || Py_SIZE(b) == 0) {
881 return PyLong_FromLong(0);
882 }
883 g = _PyLong_GCD(a, b);
884 if (g == NULL) {
885 return NULL;
886 }
887 f = PyNumber_FloorDivide(a, g);
888 Py_DECREF(g);
889 if (f == NULL) {
890 return NULL;
891 }
892 m = PyNumber_Multiply(f, b);
893 Py_DECREF(f);
894 if (m == NULL) {
895 return NULL;
896 }
897 ab = PyNumber_Absolute(m);
898 Py_DECREF(m);
899 return ab;
900}
901
902
903static PyObject *
904math_lcm(PyObject *module, PyObject * const *args, Py_ssize_t nargs)
905{
906 PyObject *res, *x;
907 Py_ssize_t i;
908
909 if (nargs == 0) {
910 return PyLong_FromLong(1);
911 }
912 res = PyNumber_Index(args[0]);
913 if (res == NULL) {
914 return NULL;
915 }
916 if (nargs == 1) {
917 Py_SETREF(res, PyNumber_Absolute(res));
918 return res;
919 }
920 for (i = 1; i < nargs; i++) {
921 x = PyNumber_Index(args[i]);
922 if (x == NULL) {
923 Py_DECREF(res);
924 return NULL;
925 }
926 if (res == _PyLong_Zero) {
927 /* Fast path: just check arguments.
928 It is okay to use identity comparison here. */
929 Py_DECREF(x);
930 continue;
931 }
932 Py_SETREF(res, long_lcm(res, x));
933 Py_DECREF(x);
934 if (res == NULL) {
935 return NULL;
936 }
937 }
938 return res;
939}
940
941
942PyDoc_STRVAR(math_lcm_doc,
943"lcm($module, *integers)\n"
944"--\n"
945"\n"
946"Least Common Multiple.");
947
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300948
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000949/* Call is_error when errno != 0, and where x is the result libm
950 * returned. is_error will usually set up an exception and return
951 * true (1), but may return false (0) without setting up an exception.
952 */
953static int
954is_error(double x)
955{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 int result = 1; /* presumption of guilt */
957 assert(errno); /* non-zero errno is a precondition for calling */
958 if (errno == EDOM)
959 PyErr_SetString(PyExc_ValueError, "math domain error");
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 else if (errno == ERANGE) {
962 /* ANSI C generally requires libm functions to set ERANGE
963 * on overflow, but also generally *allows* them to set
964 * ERANGE on underflow too. There's no consistency about
965 * the latter across platforms.
966 * Alas, C99 never requires that errno be set.
967 * Here we suppress the underflow errors (libm functions
968 * should return a zero on underflow, and +- HUGE_VAL on
969 * overflow, so testing the result for zero suffices to
970 * distinguish the cases).
971 *
972 * On some platforms (Ubuntu/ia64) it seems that errno can be
973 * set to ERANGE for subnormal results that do *not* underflow
974 * to zero. So to be safe, we'll ignore ERANGE whenever the
975 * function result is less than one in absolute value.
976 */
977 if (fabs(x) < 1.0)
978 result = 0;
979 else
980 PyErr_SetString(PyExc_OverflowError,
981 "math range error");
982 }
983 else
984 /* Unexpected math error */
985 PyErr_SetFromErrno(PyExc_ValueError);
986 return result;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000987}
988
Mark Dickinsone675f082008-12-11 21:56:00 +0000989/*
Christian Heimes53876d92008-04-19 00:31:39 +0000990 math_1 is used to wrap a libm function f that takes a double
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200991 argument and returns a double.
Christian Heimes53876d92008-04-19 00:31:39 +0000992
993 The error reporting follows these rules, which are designed to do
994 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
995 platforms.
996
997 - a NaN result from non-NaN inputs causes ValueError to be raised
998 - an infinite result from finite inputs causes OverflowError to be
999 raised if can_overflow is 1, or raises ValueError if can_overflow
1000 is 0.
1001 - if the result is finite and errno == EDOM then ValueError is
1002 raised
1003 - if the result is finite and nonzero and errno == ERANGE then
1004 OverflowError is raised
1005
1006 The last rule is used to catch overflow on platforms which follow
1007 C89 but for which HUGE_VAL is not an infinity.
1008
1009 For the majority of one-argument functions these rules are enough
1010 to ensure that Python's functions behave as specified in 'Annex F'
1011 of the C99 standard, with the 'invalid' and 'divide-by-zero'
1012 floating-point exceptions mapping to Python's ValueError and the
1013 'overflow' floating-point exception mapping to OverflowError.
1014 math_1 only works for functions that don't have singularities *and*
1015 the possibility of overflow; fortunately, that covers everything we
1016 care about right now.
1017*/
1018
Barry Warsaw8b43b191996-12-09 22:32:36 +00001019static PyObject *
Jeffrey Yasskinc2155832008-01-05 20:03:11 +00001020math_1_to_whatever(PyObject *arg, double (*func) (double),
Christian Heimes53876d92008-04-19 00:31:39 +00001021 PyObject *(*from_double_func) (double),
1022 int can_overflow)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001023{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 double x, r;
1025 x = PyFloat_AsDouble(arg);
1026 if (x == -1.0 && PyErr_Occurred())
1027 return NULL;
1028 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 r = (*func)(x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 if (Py_IS_NAN(r) && !Py_IS_NAN(x)) {
1031 PyErr_SetString(PyExc_ValueError,
1032 "math domain error"); /* invalid arg */
1033 return NULL;
1034 }
1035 if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) {
Benjamin Peterson2354a752012-03-13 16:13:09 -05001036 if (can_overflow)
1037 PyErr_SetString(PyExc_OverflowError,
1038 "math range error"); /* overflow */
1039 else
1040 PyErr_SetString(PyExc_ValueError,
1041 "math domain error"); /* singularity */
1042 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 }
1044 if (Py_IS_FINITE(r) && errno && is_error(r))
1045 /* this branch unnecessary on most platforms */
1046 return NULL;
Mark Dickinsonde429622008-05-01 00:19:23 +00001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 return (*from_double_func)(r);
Christian Heimes53876d92008-04-19 00:31:39 +00001049}
1050
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001051/* variant of math_1, to be used when the function being wrapped is known to
1052 set errno properly (that is, errno = EDOM for invalid or divide-by-zero,
1053 errno = ERANGE for overflow). */
1054
1055static PyObject *
1056math_1a(PyObject *arg, double (*func) (double))
1057{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 double x, r;
1059 x = PyFloat_AsDouble(arg);
1060 if (x == -1.0 && PyErr_Occurred())
1061 return NULL;
1062 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 r = (*func)(x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 if (errno && is_error(r))
1065 return NULL;
1066 return PyFloat_FromDouble(r);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001067}
1068
Christian Heimes53876d92008-04-19 00:31:39 +00001069/*
1070 math_2 is used to wrap a libm function f that takes two double
1071 arguments and returns a double.
1072
1073 The error reporting follows these rules, which are designed to do
1074 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
1075 platforms.
1076
1077 - a NaN result from non-NaN inputs causes ValueError to be raised
1078 - an infinite result from finite inputs causes OverflowError to be
1079 raised.
1080 - if the result is finite and errno == EDOM then ValueError is
1081 raised
1082 - if the result is finite and nonzero and errno == ERANGE then
1083 OverflowError is raised
1084
1085 The last rule is used to catch overflow on platforms which follow
1086 C89 but for which HUGE_VAL is not an infinity.
1087
1088 For most two-argument functions (copysign, fmod, hypot, atan2)
1089 these rules are enough to ensure that Python's functions behave as
1090 specified in 'Annex F' of the C99 standard, with the 'invalid' and
1091 'divide-by-zero' floating-point exceptions mapping to Python's
1092 ValueError and the 'overflow' floating-point exception mapping to
1093 OverflowError.
1094*/
1095
1096static PyObject *
1097math_1(PyObject *arg, double (*func) (double), int can_overflow)
1098{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow);
Jeffrey Yasskinc2155832008-01-05 20:03:11 +00001100}
1101
1102static PyObject *
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02001103math_2(PyObject *const *args, Py_ssize_t nargs,
1104 double (*func) (double, double), const char *funcname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001105{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 double x, y, r;
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02001107 if (!_PyArg_CheckPositional(funcname, nargs, 2, 2))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 return NULL;
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02001109 x = PyFloat_AsDouble(args[0]);
Zackery Spytz5208b4b2020-03-14 04:45:32 -06001110 if (x == -1.0 && PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 return NULL;
Zackery Spytz5208b4b2020-03-14 04:45:32 -06001112 }
1113 y = PyFloat_AsDouble(args[1]);
1114 if (y == -1.0 && PyErr_Occurred()) {
1115 return NULL;
1116 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 r = (*func)(x, y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 if (Py_IS_NAN(r)) {
1120 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1121 errno = EDOM;
1122 else
1123 errno = 0;
1124 }
1125 else if (Py_IS_INFINITY(r)) {
1126 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
1127 errno = ERANGE;
1128 else
1129 errno = 0;
1130 }
1131 if (errno && is_error(r))
1132 return NULL;
1133 else
1134 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001135}
1136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137#define FUNC1(funcname, func, can_overflow, docstring) \
1138 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
1139 return math_1(args, func, can_overflow); \
1140 }\
1141 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143#define FUNC1A(funcname, func, docstring) \
1144 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
1145 return math_1a(args, func); \
1146 }\
1147 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001148
Fred Drake40c48682000-07-03 18:11:56 +00001149#define FUNC2(funcname, func, docstring) \
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02001150 static PyObject * math_##funcname(PyObject *self, PyObject *const *args, Py_ssize_t nargs) { \
1151 return math_2(args, nargs, func, #funcname); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 }\
1153 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001154
Christian Heimes53876d92008-04-19 00:31:39 +00001155FUNC1(acos, acos, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001156 "acos($module, x, /)\n--\n\n"
Giovanni Cappellottodc3f99f2019-07-13 09:59:55 -04001157 "Return the arc cosine (measured in radians) of x.\n\n"
1158 "The result is between 0 and pi.")
Mark Dickinsonf3718592009-12-21 15:27:41 +00001159FUNC1(acosh, m_acosh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001160 "acosh($module, x, /)\n--\n\n"
1161 "Return the inverse hyperbolic cosine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001162FUNC1(asin, asin, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001163 "asin($module, x, /)\n--\n\n"
Giovanni Cappellottodc3f99f2019-07-13 09:59:55 -04001164 "Return the arc sine (measured in radians) of x.\n\n"
1165 "The result is between -pi/2 and pi/2.")
Mark Dickinsonf3718592009-12-21 15:27:41 +00001166FUNC1(asinh, m_asinh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001167 "asinh($module, x, /)\n--\n\n"
1168 "Return the inverse hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001169FUNC1(atan, atan, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001170 "atan($module, x, /)\n--\n\n"
Giovanni Cappellottodc3f99f2019-07-13 09:59:55 -04001171 "Return the arc tangent (measured in radians) of x.\n\n"
1172 "The result is between -pi/2 and pi/2.")
Christian Heimese57950f2008-04-21 13:08:03 +00001173FUNC2(atan2, m_atan2,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001174 "atan2($module, y, x, /)\n--\n\n"
1175 "Return the arc tangent (measured in radians) of y/x.\n\n"
Tim Petersfe71f812001-08-07 22:10:00 +00001176 "Unlike atan(y/x), the signs of both x and y are considered.")
Mark Dickinsonf3718592009-12-21 15:27:41 +00001177FUNC1(atanh, m_atanh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001178 "atanh($module, x, /)\n--\n\n"
1179 "Return the inverse hyperbolic tangent of x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +00001180
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001181/*[clinic input]
1182math.ceil
1183
1184 x as number: object
1185 /
1186
1187Return the ceiling of x as an Integral.
1188
1189This is the smallest integer >= x.
1190[clinic start generated code]*/
1191
1192static PyObject *
1193math_ceil(PyObject *module, PyObject *number)
1194/*[clinic end generated code: output=6c3b8a78bc201c67 input=2725352806399cab]*/
1195{
Benjamin Petersonce798522012-01-22 11:24:29 -05001196 _Py_IDENTIFIER(__ceil__);
Guido van Rossum13e05de2007-08-23 22:56:55 +00001197
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001198 if (!PyFloat_CheckExact(number)) {
1199 PyObject *method = _PyObject_LookupSpecial(number, &PyId___ceil__);
1200 if (method != NULL) {
1201 PyObject *result = _PyObject_CallNoArg(method);
1202 Py_DECREF(method);
1203 return result;
1204 }
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001205 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 return NULL;
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001207 }
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001208 double x = PyFloat_AsDouble(number);
1209 if (x == -1.0 && PyErr_Occurred())
1210 return NULL;
1211
1212 return PyLong_FromDouble(ceil(x));
Guido van Rossum13e05de2007-08-23 22:56:55 +00001213}
1214
Christian Heimes072c0f12008-01-03 23:01:04 +00001215FUNC2(copysign, copysign,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001216 "copysign($module, x, y, /)\n--\n\n"
1217 "Return a float with the magnitude (absolute value) of x but the sign of y.\n\n"
1218 "On platforms that support signed zeros, copysign(1.0, -0.0)\n"
1219 "returns -1.0.\n")
Christian Heimes53876d92008-04-19 00:31:39 +00001220FUNC1(cos, cos, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001221 "cos($module, x, /)\n--\n\n"
1222 "Return the cosine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001223FUNC1(cosh, cosh, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001224 "cosh($module, x, /)\n--\n\n"
1225 "Return the hyperbolic cosine of x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +00001226FUNC1A(erf, m_erf,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001227 "erf($module, x, /)\n--\n\n"
1228 "Error function at x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +00001229FUNC1A(erfc, m_erfc,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001230 "erfc($module, x, /)\n--\n\n"
1231 "Complementary error function at x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001232FUNC1(exp, exp, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001233 "exp($module, x, /)\n--\n\n"
1234 "Return e raised to the power of x.")
Mark Dickinson664b5112009-12-16 20:23:42 +00001235FUNC1(expm1, m_expm1, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001236 "expm1($module, x, /)\n--\n\n"
1237 "Return exp(x)-1.\n\n"
Mark Dickinson664b5112009-12-16 20:23:42 +00001238 "This function avoids the loss of precision involved in the direct "
1239 "evaluation of exp(x)-1 for small x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001240FUNC1(fabs, fabs, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001241 "fabs($module, x, /)\n--\n\n"
1242 "Return the absolute value of the float x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +00001243
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001244/*[clinic input]
1245math.floor
1246
1247 x as number: object
1248 /
1249
1250Return the floor of x as an Integral.
1251
1252This is the largest integer <= x.
1253[clinic start generated code]*/
1254
1255static PyObject *
1256math_floor(PyObject *module, PyObject *number)
1257/*[clinic end generated code: output=c6a65c4884884b8a input=63af6b5d7ebcc3d6]*/
1258{
Benjamin Petersonce798522012-01-22 11:24:29 -05001259 _Py_IDENTIFIER(__floor__);
Guido van Rossum13e05de2007-08-23 22:56:55 +00001260
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001261 if (!PyFloat_CheckExact(number)) {
1262 PyObject *method = _PyObject_LookupSpecial(number, &PyId___floor__);
1263 if (method != NULL) {
1264 PyObject *result = _PyObject_CallNoArg(method);
1265 Py_DECREF(method);
1266 return result;
1267 }
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001268 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 return NULL;
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001270 }
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001271 double x = PyFloat_AsDouble(number);
1272 if (x == -1.0 && PyErr_Occurred())
1273 return NULL;
1274
1275 return PyLong_FromDouble(floor(x));
Guido van Rossum13e05de2007-08-23 22:56:55 +00001276}
1277
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001278FUNC1A(gamma, m_tgamma,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001279 "gamma($module, x, /)\n--\n\n"
1280 "Gamma function at x.")
Mark Dickinson05d2e082009-12-11 20:17:17 +00001281FUNC1A(lgamma, m_lgamma,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001282 "lgamma($module, x, /)\n--\n\n"
1283 "Natural logarithm of absolute value of Gamma function at x.")
Mark Dickinsonbe64d952010-07-07 16:21:29 +00001284FUNC1(log1p, m_log1p, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001285 "log1p($module, x, /)\n--\n\n"
1286 "Return the natural logarithm of 1+x (base e).\n\n"
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001287 "The result is computed in a way which is accurate for x near zero.")
Mark Dickinsona0ce3752017-04-05 18:34:27 +01001288FUNC2(remainder, m_remainder,
1289 "remainder($module, x, y, /)\n--\n\n"
1290 "Difference between x and the closest integer multiple of y.\n\n"
1291 "Return x - n*y where n*y is the closest integer multiple of y.\n"
1292 "In the case where x is exactly halfway between two multiples of\n"
1293 "y, the nearest even value of n is used. The result is always exact.")
Christian Heimes53876d92008-04-19 00:31:39 +00001294FUNC1(sin, sin, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001295 "sin($module, x, /)\n--\n\n"
1296 "Return the sine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001297FUNC1(sinh, sinh, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001298 "sinh($module, x, /)\n--\n\n"
1299 "Return the hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001300FUNC1(sqrt, sqrt, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001301 "sqrt($module, x, /)\n--\n\n"
1302 "Return the square root of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001303FUNC1(tan, tan, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001304 "tan($module, x, /)\n--\n\n"
1305 "Return the tangent of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001306FUNC1(tanh, tanh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001307 "tanh($module, x, /)\n--\n\n"
1308 "Return the hyperbolic tangent of x.")
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001309
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001310/* Precision summation function as msum() by Raymond Hettinger in
1311 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
1312 enhanced with the exact partials sum and roundoff from Mark
1313 Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
1314 See those links for more details, proofs and other references.
1315
1316 Note 1: IEEE 754R floating point semantics are assumed,
1317 but the current implementation does not re-establish special
1318 value semantics across iterations (i.e. handling -Inf + Inf).
1319
1320 Note 2: No provision is made for intermediate overflow handling;
Georg Brandlf78e02b2008-06-10 17:40:04 +00001321 therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001322 sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
1323 overflow of the first partial sum.
1324
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001325 Note 3: The intermediate values lo, yr, and hi are declared volatile so
1326 aggressive compilers won't algebraically reduce lo to always be exactly 0.0.
Georg Brandlf78e02b2008-06-10 17:40:04 +00001327 Also, the volatile declaration forces the values to be stored in memory as
1328 regular doubles instead of extended long precision (80-bit) values. This
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001329 prevents double rounding because any addition or subtraction of two doubles
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 can be resolved exactly into double-sized hi and lo values. As long as the
Georg Brandlf78e02b2008-06-10 17:40:04 +00001331 hi value gets forced into a double before yr and lo are computed, the extra
1332 bits in downstream extended precision operations (x87 for example) will be
1333 exactly zero and therefore can be losslessly stored back into a double,
1334 thereby preventing double rounding.
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001335
1336 Note 4: A similar implementation is in Modules/cmathmodule.c.
1337 Be sure to update both when making changes.
1338
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001339 Note 5: The signature of math.fsum() differs from builtins.sum()
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001340 because the start argument doesn't make sense in the context of
1341 accurate summation. Since the partials table is collapsed before
1342 returning a result, sum(seq2, start=sum(seq1)) may not equal the
1343 accurate result returned by sum(itertools.chain(seq1, seq2)).
1344*/
1345
1346#define NUM_PARTIALS 32 /* initial partials array size, on stack */
1347
1348/* Extend the partials array p[] by doubling its size. */
1349static int /* non-zero on error */
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001350_fsum_realloc(double **p_ptr, Py_ssize_t n,
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001351 double *ps, Py_ssize_t *m_ptr)
1352{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 void *v = NULL;
1354 Py_ssize_t m = *m_ptr;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 m += m; /* double */
Victor Stinner049e5092014-08-17 22:20:00 +02001357 if (n < m && (size_t)m < ((size_t)PY_SSIZE_T_MAX / sizeof(double))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 double *p = *p_ptr;
1359 if (p == ps) {
1360 v = PyMem_Malloc(sizeof(double) * m);
1361 if (v != NULL)
1362 memcpy(v, ps, sizeof(double) * n);
1363 }
1364 else
1365 v = PyMem_Realloc(p, sizeof(double) * m);
1366 }
1367 if (v == NULL) { /* size overflow or no memory */
1368 PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
1369 return 1;
1370 }
1371 *p_ptr = (double*) v;
1372 *m_ptr = m;
1373 return 0;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001374}
1375
1376/* Full precision summation of a sequence of floats.
1377
1378 def msum(iterable):
1379 partials = [] # sorted, non-overlapping partial sums
1380 for x in iterable:
Mark Dickinsonfdb0acc2010-06-25 20:22:24 +00001381 i = 0
1382 for y in partials:
1383 if abs(x) < abs(y):
1384 x, y = y, x
1385 hi = x + y
1386 lo = y - (hi - x)
1387 if lo:
1388 partials[i] = lo
1389 i += 1
1390 x = hi
1391 partials[i:] = [x]
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001392 return sum_exact(partials)
1393
1394 Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
1395 are exactly equal to x+y. The inner loop applies hi/lo summation to each
1396 partial so that the list of partial sums remains exact.
1397
1398 Sum_exact() adds the partial sums exactly and correctly rounds the final
1399 result (using the round-half-to-even rule). The items in partials remain
1400 non-zero, non-special, non-overlapping and strictly increasing in
1401 magnitude, but possibly not all having the same sign.
1402
1403 Depends on IEEE 754 arithmetic guarantees and half-even rounding.
1404*/
1405
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001406/*[clinic input]
1407math.fsum
1408
1409 seq: object
1410 /
1411
1412Return an accurate floating point sum of values in the iterable seq.
1413
1414Assumes IEEE-754 floating point arithmetic.
1415[clinic start generated code]*/
1416
1417static PyObject *
1418math_fsum(PyObject *module, PyObject *seq)
1419/*[clinic end generated code: output=ba5c672b87fe34fc input=c51b7d8caf6f6e82]*/
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001420{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 PyObject *item, *iter, *sum = NULL;
1422 Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
1423 double x, y, t, ps[NUM_PARTIALS], *p = ps;
1424 double xsave, special_sum = 0.0, inf_sum = 0.0;
1425 volatile double hi, yr, lo;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 iter = PyObject_GetIter(seq);
1428 if (iter == NULL)
1429 return NULL;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 for(;;) { /* for x in iterable */
1432 assert(0 <= n && n <= m);
1433 assert((m == NUM_PARTIALS && p == ps) ||
1434 (m > NUM_PARTIALS && p != NULL));
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 item = PyIter_Next(iter);
1437 if (item == NULL) {
1438 if (PyErr_Occurred())
1439 goto _fsum_error;
1440 break;
1441 }
Raymond Hettingercfd735e2019-01-29 20:39:53 -08001442 ASSIGN_DOUBLE(x, item, error_with_item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 Py_DECREF(item);
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 xsave = x;
1446 for (i = j = 0; j < n; j++) { /* for y in partials */
1447 y = p[j];
1448 if (fabs(x) < fabs(y)) {
1449 t = x; x = y; y = t;
1450 }
1451 hi = x + y;
1452 yr = hi - x;
1453 lo = y - yr;
1454 if (lo != 0.0)
1455 p[i++] = lo;
1456 x = hi;
1457 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 n = i; /* ps[i:] = [x] */
1460 if (x != 0.0) {
1461 if (! Py_IS_FINITE(x)) {
1462 /* a nonfinite x could arise either as
1463 a result of intermediate overflow, or
1464 as a result of a nan or inf in the
1465 summands */
1466 if (Py_IS_FINITE(xsave)) {
1467 PyErr_SetString(PyExc_OverflowError,
1468 "intermediate overflow in fsum");
1469 goto _fsum_error;
1470 }
1471 if (Py_IS_INFINITY(xsave))
1472 inf_sum += xsave;
1473 special_sum += xsave;
1474 /* reset partials */
1475 n = 0;
1476 }
1477 else if (n >= m && _fsum_realloc(&p, n, ps, &m))
1478 goto _fsum_error;
1479 else
1480 p[n++] = x;
1481 }
1482 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 if (special_sum != 0.0) {
1485 if (Py_IS_NAN(inf_sum))
1486 PyErr_SetString(PyExc_ValueError,
1487 "-inf + inf in fsum");
1488 else
1489 sum = PyFloat_FromDouble(special_sum);
1490 goto _fsum_error;
1491 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 hi = 0.0;
1494 if (n > 0) {
1495 hi = p[--n];
1496 /* sum_exact(ps, hi) from the top, stop when the sum becomes
1497 inexact. */
1498 while (n > 0) {
1499 x = hi;
1500 y = p[--n];
1501 assert(fabs(y) < fabs(x));
1502 hi = x + y;
1503 yr = hi - x;
1504 lo = y - yr;
1505 if (lo != 0.0)
1506 break;
1507 }
1508 /* Make half-even rounding work across multiple partials.
1509 Needed so that sum([1e-16, 1, 1e16]) will round-up the last
1510 digit to two instead of down to zero (the 1e-16 makes the 1
1511 slightly closer to two). With a potential 1 ULP rounding
1512 error fixed-up, math.fsum() can guarantee commutativity. */
1513 if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
1514 (lo > 0.0 && p[n-1] > 0.0))) {
1515 y = lo * 2.0;
1516 x = hi + y;
1517 yr = x - hi;
1518 if (y == yr)
1519 hi = x;
1520 }
1521 }
1522 sum = PyFloat_FromDouble(hi);
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001523
Raymond Hettingercfd735e2019-01-29 20:39:53 -08001524 _fsum_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 Py_DECREF(iter);
1526 if (p != ps)
1527 PyMem_Free(p);
1528 return sum;
Raymond Hettingercfd735e2019-01-29 20:39:53 -08001529
1530 error_with_item:
1531 Py_DECREF(item);
1532 goto _fsum_error;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001533}
1534
1535#undef NUM_PARTIALS
1536
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001537
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001538static unsigned long
1539count_set_bits(unsigned long n)
1540{
1541 unsigned long count = 0;
1542 while (n != 0) {
1543 ++count;
1544 n &= n - 1; /* clear least significant bit */
1545 }
1546 return count;
1547}
1548
Mark Dickinson73934b92019-05-18 12:29:50 +01001549/* Integer square root
1550
1551Given a nonnegative integer `n`, we want to compute the largest integer
1552`a` for which `a * a <= n`, or equivalently the integer part of the exact
1553square root of `n`.
1554
1555We use an adaptive-precision pure-integer version of Newton's iteration. Given
1556a positive integer `n`, the algorithm produces at each iteration an integer
1557approximation `a` to the square root of `n >> s` for some even integer `s`,
1558with `s` decreasing as the iterations progress. On the final iteration, `s` is
1559zero and we have an approximation to the square root of `n` itself.
1560
1561At every step, the approximation `a` is strictly within 1.0 of the true square
1562root, so we have
1563
1564 (a - 1)**2 < (n >> s) < (a + 1)**2
1565
1566After the final iteration, a check-and-correct step is needed to determine
1567whether `a` or `a - 1` gives the desired integer square root of `n`.
1568
1569The algorithm is remarkable in its simplicity. There's no need for a
1570per-iteration check-and-correct step, and termination is straightforward: the
1571number of iterations is known in advance (it's exactly `floor(log2(log2(n)))`
1572for `n > 1`). The only tricky part of the correctness proof is in establishing
1573that the bound `(a - 1)**2 < (n >> s) < (a + 1)**2` is maintained from one
1574iteration to the next. A sketch of the proof of this is given below.
1575
1576In addition to the proof sketch, a formal, computer-verified proof
1577of correctness (using Lean) of an equivalent recursive algorithm can be found
1578here:
1579
1580 https://github.com/mdickinson/snippets/blob/master/proofs/isqrt/src/isqrt.lean
1581
1582
1583Here's Python code equivalent to the C implementation below:
1584
1585 def isqrt(n):
1586 """
1587 Return the integer part of the square root of the input.
1588 """
1589 n = operator.index(n)
1590
1591 if n < 0:
1592 raise ValueError("isqrt() argument must be nonnegative")
1593 if n == 0:
1594 return 0
1595
1596 c = (n.bit_length() - 1) // 2
1597 a = 1
1598 d = 0
1599 for s in reversed(range(c.bit_length())):
Mark Dickinson2dfeaa92019-06-16 17:53:21 +01001600 # Loop invariant: (a-1)**2 < (n >> 2*(c - d)) < (a+1)**2
Mark Dickinson73934b92019-05-18 12:29:50 +01001601 e = d
1602 d = c >> s
1603 a = (a << d - e - 1) + (n >> 2*c - e - d + 1) // a
Mark Dickinson73934b92019-05-18 12:29:50 +01001604
1605 return a - (a*a > n)
1606
1607
1608Sketch of proof of correctness
1609------------------------------
1610
1611The delicate part of the correctness proof is showing that the loop invariant
1612is preserved from one iteration to the next. That is, just before the line
1613
1614 a = (a << d - e - 1) + (n >> 2*c - e - d + 1) // a
1615
1616is executed in the above code, we know that
1617
1618 (1) (a - 1)**2 < (n >> 2*(c - e)) < (a + 1)**2.
1619
1620(since `e` is always the value of `d` from the previous iteration). We must
1621prove that after that line is executed, we have
1622
1623 (a - 1)**2 < (n >> 2*(c - d)) < (a + 1)**2
1624
Min ho Kimf7d72e42019-07-06 07:39:32 +10001625To facilitate the proof, we make some changes of notation. Write `m` for
Mark Dickinson73934b92019-05-18 12:29:50 +01001626`n >> 2*(c-d)`, and write `b` for the new value of `a`, so
1627
1628 b = (a << d - e - 1) + (n >> 2*c - e - d + 1) // a
1629
1630or equivalently:
1631
1632 (2) b = (a << d - e - 1) + (m >> d - e + 1) // a
1633
1634Then we can rewrite (1) as:
1635
1636 (3) (a - 1)**2 < (m >> 2*(d - e)) < (a + 1)**2
1637
1638and we must show that (b - 1)**2 < m < (b + 1)**2.
1639
1640From this point on, we switch to mathematical notation, so `/` means exact
1641division rather than integer division and `^` is used for exponentiation. We
1642use the `√` symbol for the exact square root. In (3), we can remove the
1643implicit floor operation to give:
1644
1645 (4) (a - 1)^2 < m / 4^(d - e) < (a + 1)^2
1646
1647Taking square roots throughout (4), scaling by `2^(d-e)`, and rearranging gives
1648
1649 (5) 0 <= | 2^(d-e)a - √m | < 2^(d-e)
1650
1651Squaring and dividing through by `2^(d-e+1) a` gives
1652
1653 (6) 0 <= 2^(d-e-1) a + m / (2^(d-e+1) a) - √m < 2^(d-e-1) / a
1654
1655We'll show below that `2^(d-e-1) <= a`. Given that, we can replace the
1656right-hand side of (6) with `1`, and now replacing the central
1657term `m / (2^(d-e+1) a)` with its floor in (6) gives
1658
1659 (7) -1 < 2^(d-e-1) a + m // 2^(d-e+1) a - √m < 1
1660
1661Or equivalently, from (2):
1662
1663 (7) -1 < b - √m < 1
1664
1665and rearranging gives that `(b-1)^2 < m < (b+1)^2`, which is what we needed
1666to prove.
1667
1668We're not quite done: we still have to prove the inequality `2^(d - e - 1) <=
1669a` that was used to get line (7) above. From the definition of `c`, we have
1670`4^c <= n`, which implies
1671
1672 (8) 4^d <= m
1673
1674also, since `e == d >> 1`, `d` is at most `2e + 1`, from which it follows
1675that `2d - 2e - 1 <= d` and hence that
1676
1677 (9) 4^(2d - 2e - 1) <= m
1678
1679Dividing both sides by `4^(d - e)` gives
1680
1681 (10) 4^(d - e - 1) <= m / 4^(d - e)
1682
1683But we know from (4) that `m / 4^(d-e) < (a + 1)^2`, hence
1684
1685 (11) 4^(d - e - 1) < (a + 1)^2
1686
1687Now taking square roots of both sides and observing that both `2^(d-e-1)` and
1688`a` are integers gives `2^(d - e - 1) <= a`, which is what we needed. This
1689completes the proof sketch.
1690
1691*/
1692
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001693
1694/* Approximate square root of a large 64-bit integer.
1695
1696 Given `n` satisfying `2**62 <= n < 2**64`, return `a`
1697 satisfying `(a - 1)**2 < n < (a + 1)**2`. */
1698
1699static uint64_t
1700_approximate_isqrt(uint64_t n)
1701{
1702 uint32_t u = 1U + (n >> 62);
1703 u = (u << 1) + (n >> 59) / u;
1704 u = (u << 3) + (n >> 53) / u;
1705 u = (u << 7) + (n >> 41) / u;
1706 return (u << 15) + (n >> 17) / u;
1707}
1708
Mark Dickinson73934b92019-05-18 12:29:50 +01001709/*[clinic input]
1710math.isqrt
1711
1712 n: object
1713 /
1714
1715Return the integer part of the square root of the input.
1716[clinic start generated code]*/
1717
1718static PyObject *
1719math_isqrt(PyObject *module, PyObject *n)
1720/*[clinic end generated code: output=35a6f7f980beab26 input=5b6e7ae4fa6c43d6]*/
1721{
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001722 int a_too_large, c_bit_length;
Mark Dickinson73934b92019-05-18 12:29:50 +01001723 size_t c, d;
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001724 uint64_t m, u;
Mark Dickinson73934b92019-05-18 12:29:50 +01001725 PyObject *a = NULL, *b;
1726
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001727 n = _PyNumber_Index(n);
Mark Dickinson73934b92019-05-18 12:29:50 +01001728 if (n == NULL) {
1729 return NULL;
1730 }
1731
1732 if (_PyLong_Sign(n) < 0) {
1733 PyErr_SetString(
1734 PyExc_ValueError,
1735 "isqrt() argument must be nonnegative");
1736 goto error;
1737 }
1738 if (_PyLong_Sign(n) == 0) {
1739 Py_DECREF(n);
1740 return PyLong_FromLong(0);
1741 }
1742
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001743 /* c = (n.bit_length() - 1) // 2 */
Mark Dickinson73934b92019-05-18 12:29:50 +01001744 c = _PyLong_NumBits(n);
1745 if (c == (size_t)(-1)) {
1746 goto error;
1747 }
1748 c = (c - 1U) / 2U;
1749
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001750 /* Fast path: if c <= 31 then n < 2**64 and we can compute directly with a
1751 fast, almost branch-free algorithm. In the final correction, we use `u*u
1752 - 1 >= m` instead of the simpler `u*u > m` in order to get the correct
1753 result in the corner case where `u=2**32`. */
1754 if (c <= 31U) {
1755 m = (uint64_t)PyLong_AsUnsignedLongLong(n);
1756 Py_DECREF(n);
1757 if (m == (uint64_t)(-1) && PyErr_Occurred()) {
1758 return NULL;
1759 }
1760 u = _approximate_isqrt(m << (62U - 2U*c)) >> (31U - c);
1761 u -= u * u - 1U >= m;
1762 return PyLong_FromUnsignedLongLong((unsigned long long)u);
Mark Dickinson73934b92019-05-18 12:29:50 +01001763 }
1764
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001765 /* Slow path: n >= 2**64. We perform the first five iterations in C integer
1766 arithmetic, then switch to using Python long integers. */
1767
1768 /* From n >= 2**64 it follows that c.bit_length() >= 6. */
1769 c_bit_length = 6;
1770 while ((c >> c_bit_length) > 0U) {
1771 ++c_bit_length;
1772 }
1773
1774 /* Initialise d and a. */
1775 d = c >> (c_bit_length - 5);
1776 b = _PyLong_Rshift(n, 2U*c - 62U);
1777 if (b == NULL) {
1778 goto error;
1779 }
1780 m = (uint64_t)PyLong_AsUnsignedLongLong(b);
1781 Py_DECREF(b);
1782 if (m == (uint64_t)(-1) && PyErr_Occurred()) {
1783 goto error;
1784 }
1785 u = _approximate_isqrt(m) >> (31U - d);
1786 a = PyLong_FromUnsignedLongLong((unsigned long long)u);
Mark Dickinson73934b92019-05-18 12:29:50 +01001787 if (a == NULL) {
1788 goto error;
1789 }
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001790
1791 for (int s = c_bit_length - 6; s >= 0; --s) {
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03001792 PyObject *q;
Mark Dickinson73934b92019-05-18 12:29:50 +01001793 size_t e = d;
1794
1795 d = c >> s;
1796
1797 /* q = (n >> 2*c - e - d + 1) // a */
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03001798 q = _PyLong_Rshift(n, 2U*c - d - e + 1U);
Mark Dickinson73934b92019-05-18 12:29:50 +01001799 if (q == NULL) {
1800 goto error;
1801 }
1802 Py_SETREF(q, PyNumber_FloorDivide(q, a));
1803 if (q == NULL) {
1804 goto error;
1805 }
1806
1807 /* a = (a << d - 1 - e) + q */
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03001808 Py_SETREF(a, _PyLong_Lshift(a, d - 1U - e));
Mark Dickinson73934b92019-05-18 12:29:50 +01001809 if (a == NULL) {
1810 Py_DECREF(q);
1811 goto error;
1812 }
1813 Py_SETREF(a, PyNumber_Add(a, q));
1814 Py_DECREF(q);
1815 if (a == NULL) {
1816 goto error;
1817 }
1818 }
1819
1820 /* The correct result is either a or a - 1. Figure out which, and
1821 decrement a if necessary. */
1822
1823 /* a_too_large = n < a * a */
1824 b = PyNumber_Multiply(a, a);
1825 if (b == NULL) {
1826 goto error;
1827 }
1828 a_too_large = PyObject_RichCompareBool(n, b, Py_LT);
1829 Py_DECREF(b);
1830 if (a_too_large == -1) {
1831 goto error;
1832 }
1833
1834 if (a_too_large) {
1835 Py_SETREF(a, PyNumber_Subtract(a, _PyLong_One));
1836 }
1837 Py_DECREF(n);
1838 return a;
1839
1840 error:
1841 Py_XDECREF(a);
1842 Py_DECREF(n);
1843 return NULL;
1844}
1845
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001846/* Divide-and-conquer factorial algorithm
1847 *
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07001848 * Based on the formula and pseudo-code provided at:
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001849 * http://www.luschny.de/math/factorial/binarysplitfact.html
1850 *
1851 * Faster algorithms exist, but they're more complicated and depend on
Ezio Melotti9527afd2010-07-08 15:03:02 +00001852 * a fast prime factorization algorithm.
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001853 *
1854 * Notes on the algorithm
1855 * ----------------------
1856 *
1857 * factorial(n) is written in the form 2**k * m, with m odd. k and m are
1858 * computed separately, and then combined using a left shift.
1859 *
1860 * The function factorial_odd_part computes the odd part m (i.e., the greatest
1861 * odd divisor) of factorial(n), using the formula:
1862 *
1863 * factorial_odd_part(n) =
1864 *
1865 * product_{i >= 0} product_{0 < j <= n / 2**i, j odd} j
1866 *
1867 * Example: factorial_odd_part(20) =
1868 *
1869 * (1) *
1870 * (1) *
1871 * (1 * 3 * 5) *
1872 * (1 * 3 * 5 * 7 * 9)
1873 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1874 *
1875 * Here i goes from large to small: the first term corresponds to i=4 (any
1876 * larger i gives an empty product), and the last term corresponds to i=0.
1877 * Each term can be computed from the last by multiplying by the extra odd
1878 * numbers required: e.g., to get from the penultimate term to the last one,
1879 * we multiply by (11 * 13 * 15 * 17 * 19).
1880 *
1881 * To see a hint of why this formula works, here are the same numbers as above
1882 * but with the even parts (i.e., the appropriate powers of 2) included. For
1883 * each subterm in the product for i, we multiply that subterm by 2**i:
1884 *
1885 * factorial(20) =
1886 *
1887 * (16) *
1888 * (8) *
1889 * (4 * 12 * 20) *
1890 * (2 * 6 * 10 * 14 * 18) *
1891 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1892 *
1893 * The factorial_partial_product function computes the product of all odd j in
1894 * range(start, stop) for given start and stop. It's used to compute the
1895 * partial products like (11 * 13 * 15 * 17 * 19) in the example above. It
1896 * operates recursively, repeatedly splitting the range into two roughly equal
1897 * pieces until the subranges are small enough to be computed using only C
1898 * integer arithmetic.
1899 *
1900 * The two-valuation k (i.e., the exponent of the largest power of 2 dividing
1901 * the factorial) is computed independently in the main math_factorial
1902 * function. By standard results, its value is:
1903 *
1904 * two_valuation = n//2 + n//4 + n//8 + ....
1905 *
1906 * It can be shown (e.g., by complete induction on n) that two_valuation is
1907 * equal to n - count_set_bits(n), where count_set_bits(n) gives the number of
1908 * '1'-bits in the binary expansion of n.
1909 */
1910
1911/* factorial_partial_product: Compute product(range(start, stop, 2)) using
1912 * divide and conquer. Assumes start and stop are odd and stop > start.
1913 * max_bits must be >= bit_length(stop - 2). */
1914
1915static PyObject *
1916factorial_partial_product(unsigned long start, unsigned long stop,
1917 unsigned long max_bits)
1918{
1919 unsigned long midpoint, num_operands;
1920 PyObject *left = NULL, *right = NULL, *result = NULL;
1921
1922 /* If the return value will fit an unsigned long, then we can
1923 * multiply in a tight, fast loop where each multiply is O(1).
1924 * Compute an upper bound on the number of bits required to store
1925 * the answer.
1926 *
1927 * Storing some integer z requires floor(lg(z))+1 bits, which is
1928 * conveniently the value returned by bit_length(z). The
1929 * product x*y will require at most
1930 * bit_length(x) + bit_length(y) bits to store, based
1931 * on the idea that lg product = lg x + lg y.
1932 *
1933 * We know that stop - 2 is the largest number to be multiplied. From
1934 * there, we have: bit_length(answer) <= num_operands *
1935 * bit_length(stop - 2)
1936 */
1937
1938 num_operands = (stop - start) / 2;
1939 /* The "num_operands <= 8 * SIZEOF_LONG" check guards against the
1940 * unlikely case of an overflow in num_operands * max_bits. */
1941 if (num_operands <= 8 * SIZEOF_LONG &&
1942 num_operands * max_bits <= 8 * SIZEOF_LONG) {
1943 unsigned long j, total;
1944 for (total = start, j = start + 2; j < stop; j += 2)
1945 total *= j;
1946 return PyLong_FromUnsignedLong(total);
1947 }
1948
1949 /* find midpoint of range(start, stop), rounded up to next odd number. */
1950 midpoint = (start + num_operands) | 1;
1951 left = factorial_partial_product(start, midpoint,
Niklas Fiekasc5b79002020-01-16 15:09:19 +01001952 _Py_bit_length(midpoint - 2));
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001953 if (left == NULL)
1954 goto error;
1955 right = factorial_partial_product(midpoint, stop, max_bits);
1956 if (right == NULL)
1957 goto error;
1958 result = PyNumber_Multiply(left, right);
1959
1960 error:
1961 Py_XDECREF(left);
1962 Py_XDECREF(right);
1963 return result;
1964}
1965
1966/* factorial_odd_part: compute the odd part of factorial(n). */
1967
1968static PyObject *
1969factorial_odd_part(unsigned long n)
1970{
1971 long i;
1972 unsigned long v, lower, upper;
1973 PyObject *partial, *tmp, *inner, *outer;
1974
1975 inner = PyLong_FromLong(1);
1976 if (inner == NULL)
1977 return NULL;
1978 outer = inner;
1979 Py_INCREF(outer);
1980
1981 upper = 3;
Niklas Fiekasc5b79002020-01-16 15:09:19 +01001982 for (i = _Py_bit_length(n) - 2; i >= 0; i--) {
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001983 v = n >> i;
1984 if (v <= 2)
1985 continue;
1986 lower = upper;
1987 /* (v + 1) | 1 = least odd integer strictly larger than n / 2**i */
1988 upper = (v + 1) | 1;
1989 /* Here inner is the product of all odd integers j in the range (0,
1990 n/2**(i+1)]. The factorial_partial_product call below gives the
1991 product of all odd integers j in the range (n/2**(i+1), n/2**i]. */
Niklas Fiekasc5b79002020-01-16 15:09:19 +01001992 partial = factorial_partial_product(lower, upper, _Py_bit_length(upper-2));
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001993 /* inner *= partial */
1994 if (partial == NULL)
1995 goto error;
1996 tmp = PyNumber_Multiply(inner, partial);
1997 Py_DECREF(partial);
1998 if (tmp == NULL)
1999 goto error;
2000 Py_DECREF(inner);
2001 inner = tmp;
2002 /* Now inner is the product of all odd integers j in the range (0,
2003 n/2**i], giving the inner product in the formula above. */
2004
2005 /* outer *= inner; */
2006 tmp = PyNumber_Multiply(outer, inner);
2007 if (tmp == NULL)
2008 goto error;
2009 Py_DECREF(outer);
2010 outer = tmp;
2011 }
Mark Dickinson76464492012-10-25 10:46:28 +01002012 Py_DECREF(inner);
2013 return outer;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002014
2015 error:
2016 Py_DECREF(outer);
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002017 Py_DECREF(inner);
Mark Dickinson76464492012-10-25 10:46:28 +01002018 return NULL;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002019}
2020
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002021
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002022/* Lookup table for small factorial values */
2023
2024static const unsigned long SmallFactorials[] = {
2025 1, 1, 2, 6, 24, 120, 720, 5040, 40320,
2026 362880, 3628800, 39916800, 479001600,
2027#if SIZEOF_LONG >= 8
2028 6227020800, 87178291200, 1307674368000,
2029 20922789888000, 355687428096000, 6402373705728000,
2030 121645100408832000, 2432902008176640000
2031#endif
2032};
2033
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002034/*[clinic input]
2035math.factorial
2036
2037 x as arg: object
2038 /
2039
2040Find x!.
2041
2042Raise a ValueError if x is negative or non-integral.
2043[clinic start generated code]*/
2044
Barry Warsaw8b43b191996-12-09 22:32:36 +00002045static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002046math_factorial(PyObject *module, PyObject *arg)
2047/*[clinic end generated code: output=6686f26fae00e9ca input=6d1c8105c0d91fb4]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002048{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03002049 long x, two_valuation;
Mark Dickinson5990d282014-04-10 09:29:39 -04002050 int overflow;
Serhiy Storchaka578c3952020-05-26 18:43:38 +03002051 PyObject *result, *odd_part;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002052
Serhiy Storchaka578c3952020-05-26 18:43:38 +03002053 x = PyLong_AsLongAndOverflow(arg, &overflow);
Mark Dickinson5990d282014-04-10 09:29:39 -04002054 if (x == -1 && PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 return NULL;
Mark Dickinson5990d282014-04-10 09:29:39 -04002056 }
2057 else if (overflow == 1) {
2058 PyErr_Format(PyExc_OverflowError,
2059 "factorial() argument should not exceed %ld",
2060 LONG_MAX);
2061 return NULL;
2062 }
2063 else if (overflow == -1 || x < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002065 "factorial() not defined for negative values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 return NULL;
2067 }
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002068
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002069 /* use lookup table if x is small */
Victor Stinner63941882011-09-29 00:42:28 +02002070 if (x < (long)Py_ARRAY_LENGTH(SmallFactorials))
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002071 return PyLong_FromUnsignedLong(SmallFactorials[x]);
2072
2073 /* else express in the form odd_part * 2**two_valuation, and compute as
2074 odd_part << two_valuation. */
2075 odd_part = factorial_odd_part(x);
2076 if (odd_part == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03002078 two_valuation = x - count_set_bits(x);
2079 result = _PyLong_Lshift(odd_part, two_valuation);
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002080 Py_DECREF(odd_part);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 return result;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002082}
2083
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002084
2085/*[clinic input]
2086math.trunc
2087
2088 x: object
2089 /
2090
2091Truncates the Real x to the nearest Integral toward 0.
2092
2093Uses the __trunc__ magic method.
2094[clinic start generated code]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002095
2096static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002097math_trunc(PyObject *module, PyObject *x)
2098/*[clinic end generated code: output=34b9697b707e1031 input=2168b34e0a09134d]*/
Christian Heimes400adb02008-02-01 08:12:03 +00002099{
Benjamin Petersonce798522012-01-22 11:24:29 -05002100 _Py_IDENTIFIER(__trunc__);
Benjamin Petersonb0125892010-07-02 13:35:17 +00002101 PyObject *trunc, *result;
Christian Heimes400adb02008-02-01 08:12:03 +00002102
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02002103 if (PyFloat_CheckExact(x)) {
2104 return PyFloat_Type.tp_as_number->nb_int(x);
2105 }
2106
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002107 if (Py_TYPE(x)->tp_dict == NULL) {
2108 if (PyType_Ready(Py_TYPE(x)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 return NULL;
2110 }
Christian Heimes400adb02008-02-01 08:12:03 +00002111
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002112 trunc = _PyObject_LookupSpecial(x, &PyId___trunc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 if (trunc == NULL) {
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00002114 if (!PyErr_Occurred())
2115 PyErr_Format(PyExc_TypeError,
2116 "type %.100s doesn't define __trunc__ method",
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002117 Py_TYPE(x)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 return NULL;
2119 }
Victor Stinnerf17c3de2016-12-06 18:46:19 +01002120 result = _PyObject_CallNoArg(trunc);
Benjamin Petersonb0125892010-07-02 13:35:17 +00002121 Py_DECREF(trunc);
2122 return result;
Christian Heimes400adb02008-02-01 08:12:03 +00002123}
2124
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002125
2126/*[clinic input]
2127math.frexp
2128
2129 x: double
2130 /
2131
2132Return the mantissa and exponent of x, as pair (m, e).
2133
2134m is a float and e is an int, such that x = m * 2.**e.
2135If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.
2136[clinic start generated code]*/
Christian Heimes400adb02008-02-01 08:12:03 +00002137
2138static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002139math_frexp_impl(PyObject *module, double x)
2140/*[clinic end generated code: output=03e30d252a15ad4a input=96251c9e208bc6e9]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00002141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 /* deal with special cases directly, to sidestep platform
2144 differences */
2145 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
2146 i = 0;
2147 }
2148 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 x = frexp(x, &i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 }
2151 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +00002152}
2153
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002154
2155/*[clinic input]
2156math.ldexp
2157
2158 x: double
2159 i: object
2160 /
2161
2162Return x * (2**i).
2163
2164This is essentially the inverse of frexp().
2165[clinic start generated code]*/
Guido van Rossumc6e22901998-12-04 19:26:43 +00002166
Barry Warsaw8b43b191996-12-09 22:32:36 +00002167static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002168math_ldexp_impl(PyObject *module, double x, PyObject *i)
2169/*[clinic end generated code: output=b6892f3c2df9cc6a input=17d5970c1a40a8c1]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00002170{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002171 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 long exp;
2173 int overflow;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00002174
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002175 if (PyLong_Check(i)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 /* on overflow, replace exponent with either LONG_MAX
2177 or LONG_MIN, depending on the sign. */
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002178 exp = PyLong_AsLongAndOverflow(i, &overflow);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 if (exp == -1 && PyErr_Occurred())
2180 return NULL;
2181 if (overflow)
2182 exp = overflow < 0 ? LONG_MIN : LONG_MAX;
2183 }
2184 else {
2185 PyErr_SetString(PyExc_TypeError,
Serhiy Storchaka95949422013-08-27 19:40:23 +03002186 "Expected an int as second argument to ldexp.");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 return NULL;
2188 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00002189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 if (x == 0. || !Py_IS_FINITE(x)) {
2191 /* NaNs, zeros and infinities are returned unchanged */
2192 r = x;
2193 errno = 0;
2194 } else if (exp > INT_MAX) {
2195 /* overflow */
2196 r = copysign(Py_HUGE_VAL, x);
2197 errno = ERANGE;
2198 } else if (exp < INT_MIN) {
2199 /* underflow to +-0 */
2200 r = copysign(0., x);
2201 errno = 0;
2202 } else {
2203 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 r = ldexp(x, (int)exp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 if (Py_IS_INFINITY(r))
2206 errno = ERANGE;
2207 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00002208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 if (errno && is_error(r))
2210 return NULL;
2211 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +00002212}
2213
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002214
2215/*[clinic input]
2216math.modf
2217
2218 x: double
2219 /
2220
2221Return the fractional and integer parts of x.
2222
2223Both results carry the sign of x and are floats.
2224[clinic start generated code]*/
Guido van Rossumc6e22901998-12-04 19:26:43 +00002225
Barry Warsaw8b43b191996-12-09 22:32:36 +00002226static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002227math_modf_impl(PyObject *module, double x)
2228/*[clinic end generated code: output=90cee0260014c3c0 input=b4cfb6786afd9035]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00002229{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002230 double y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 /* some platforms don't do the right thing for NaNs and
2232 infinities, so we take care of special cases directly. */
2233 if (!Py_IS_FINITE(x)) {
2234 if (Py_IS_INFINITY(x))
2235 return Py_BuildValue("(dd)", copysign(0., x), x);
2236 else if (Py_IS_NAN(x))
2237 return Py_BuildValue("(dd)", x, x);
2238 }
Christian Heimesa342c012008-04-20 21:01:16 +00002239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 x = modf(x, &y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +00002243}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002244
Guido van Rossumc6e22901998-12-04 19:26:43 +00002245
Serhiy Storchaka95949422013-08-27 19:40:23 +03002246/* A decent logarithm is easy to compute even for huge ints, but libm can't
Tim Peters78526162001-09-05 00:53:45 +00002247 do that by itself -- loghelper can. func is log or log10, and name is
Serhiy Storchaka95949422013-08-27 19:40:23 +03002248 "log" or "log10". Note that overflow of the result isn't possible: an int
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002249 can contain no more than INT_MAX * SHIFT bits, so has value certainly less
2250 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 +00002251 small enough to fit in an IEEE single. log and log10 are even smaller.
Serhiy Storchaka95949422013-08-27 19:40:23 +03002252 However, intermediate overflow is possible for an int if the number of bits
2253 in that int is larger than PY_SSIZE_T_MAX. */
Tim Peters78526162001-09-05 00:53:45 +00002254
2255static PyObject*
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002256loghelper(PyObject* arg, double (*func)(double), const char *funcname)
Tim Peters78526162001-09-05 00:53:45 +00002257{
Serhiy Storchaka95949422013-08-27 19:40:23 +03002258 /* If it is int, do it ourselves. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 if (PyLong_Check(arg)) {
Mark Dickinsonc6037172010-09-29 19:06:36 +00002260 double x, result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 Py_ssize_t e;
Mark Dickinsonc6037172010-09-29 19:06:36 +00002262
2263 /* Negative or zero inputs give a ValueError. */
2264 if (Py_SIZE(arg) <= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 PyErr_SetString(PyExc_ValueError,
2266 "math domain error");
2267 return NULL;
2268 }
Mark Dickinsonfa41e602010-09-28 07:22:27 +00002269
Mark Dickinsonc6037172010-09-29 19:06:36 +00002270 x = PyLong_AsDouble(arg);
2271 if (x == -1.0 && PyErr_Occurred()) {
2272 if (!PyErr_ExceptionMatches(PyExc_OverflowError))
2273 return NULL;
2274 /* Here the conversion to double overflowed, but it's possible
2275 to compute the log anyway. Clear the exception and continue. */
2276 PyErr_Clear();
2277 x = _PyLong_Frexp((PyLongObject *)arg, &e);
2278 if (x == -1.0 && PyErr_Occurred())
2279 return NULL;
2280 /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */
2281 result = func(x) + func(2.0) * e;
2282 }
2283 else
2284 /* Successfully converted x to a double. */
2285 result = func(x);
2286 return PyFloat_FromDouble(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 }
Tim Peters78526162001-09-05 00:53:45 +00002288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 /* Else let libm handle it by itself. */
2290 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +00002291}
2292
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002293
2294/*[clinic input]
2295math.log
2296
2297 x: object
2298 [
2299 base: object(c_default="NULL") = math.e
2300 ]
2301 /
2302
2303Return the logarithm of x to the given base.
2304
2305If the base not specified, returns the natural logarithm (base e) of x.
2306[clinic start generated code]*/
2307
Tim Peters78526162001-09-05 00:53:45 +00002308static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002309math_log_impl(PyObject *module, PyObject *x, int group_right_1,
2310 PyObject *base)
2311/*[clinic end generated code: output=7b5a39e526b73fc9 input=0f62d5726cbfebbd]*/
Tim Peters78526162001-09-05 00:53:45 +00002312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 PyObject *num, *den;
2314 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +00002315
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002316 num = loghelper(x, m_log, "log");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 if (num == NULL || base == NULL)
2318 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +00002319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 den = loghelper(base, m_log, "log");
2321 if (den == NULL) {
2322 Py_DECREF(num);
2323 return NULL;
2324 }
Raymond Hettinger866964c2002-12-14 19:51:34 +00002325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 ans = PyNumber_TrueDivide(num, den);
2327 Py_DECREF(num);
2328 Py_DECREF(den);
2329 return ans;
Tim Peters78526162001-09-05 00:53:45 +00002330}
2331
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002332
2333/*[clinic input]
2334math.log2
2335
2336 x: object
2337 /
2338
2339Return the base 2 logarithm of x.
2340[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002341
2342static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002343math_log2(PyObject *module, PyObject *x)
2344/*[clinic end generated code: output=5425899a4d5d6acb input=08321262bae4f39b]*/
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02002345{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002346 return loghelper(x, m_log2, "log2");
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02002347}
2348
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002349
2350/*[clinic input]
2351math.log10
2352
2353 x: object
2354 /
2355
2356Return the base 10 logarithm of x.
2357[clinic start generated code]*/
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02002358
2359static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002360math_log10(PyObject *module, PyObject *x)
2361/*[clinic end generated code: output=be72a64617df9c6f input=b2469d02c6469e53]*/
Tim Peters78526162001-09-05 00:53:45 +00002362{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002363 return loghelper(x, m_log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +00002364}
2365
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002366
2367/*[clinic input]
2368math.fmod
2369
2370 x: double
2371 y: double
2372 /
2373
2374Return fmod(x, y), according to platform C.
2375
2376x % y may differ.
2377[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002378
Christian Heimes53876d92008-04-19 00:31:39 +00002379static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002380math_fmod_impl(PyObject *module, double x, double y)
2381/*[clinic end generated code: output=7559d794343a27b5 input=4f84caa8cfc26a03]*/
Christian Heimes53876d92008-04-19 00:31:39 +00002382{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002383 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 /* fmod(x, +/-Inf) returns x for finite x. */
2385 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
2386 return PyFloat_FromDouble(x);
2387 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 r = fmod(x, y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 if (Py_IS_NAN(r)) {
2390 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
2391 errno = EDOM;
2392 else
2393 errno = 0;
2394 }
2395 if (errno && is_error(r))
2396 return NULL;
2397 else
2398 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00002399}
2400
Raymond Hettinger13990742018-08-11 11:26:36 -07002401/*
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002402Given an *n* length *vec* of values and a value *max*, compute:
Raymond Hettinger13990742018-08-11 11:26:36 -07002403
Raymond Hettingerc630e102018-08-11 18:39:05 -07002404 max * sqrt(sum((x / max) ** 2 for x in vec))
Raymond Hettinger13990742018-08-11 11:26:36 -07002405
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002406The value of the *max* variable must be non-negative and
Raymond Hettinger216aaaa2018-11-09 01:06:02 -08002407equal to the absolute value of the largest magnitude
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002408entry in the vector. If n==0, then *max* should be 0.0.
2409If an infinity is present in the vec, *max* should be INF.
Raymond Hettingerc630e102018-08-11 18:39:05 -07002410
2411The *found_nan* variable indicates whether some member of
2412the *vec* is a NaN.
Raymond Hettinger21786f52018-08-28 22:47:24 -07002413
2414To improve accuracy and to increase the number of cases where
2415vector_norm() is commutative, we use a variant of Neumaier
2416summation specialized to exploit that we always know that
2417|csum| >= |x|.
2418
2419The *csum* variable tracks the cumulative sum and *frac* tracks
2420the cumulative fractional errors at each step. Since this
2421variant assumes that |csum| >= |x| at each step, we establish
2422the precondition by starting the accumulation from 1.0 which
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002423represents the largest possible value of (x/max)**2.
2424
2425After the loop is finished, the initial 1.0 is subtracted out
2426for a net zero effect on the final sum. Since *csum* will be
2427greater than 1.0, the subtraction of 1.0 will not cause
2428fractional digits to be dropped from *csum*.
Raymond Hettinger21786f52018-08-28 22:47:24 -07002429
Raymond Hettinger13990742018-08-11 11:26:36 -07002430*/
2431
2432static inline double
Raymond Hettingerc630e102018-08-11 18:39:05 -07002433vector_norm(Py_ssize_t n, double *vec, double max, int found_nan)
Raymond Hettinger13990742018-08-11 11:26:36 -07002434{
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002435 double x, csum = 1.0, oldcsum, frac = 0.0;
Raymond Hettinger13990742018-08-11 11:26:36 -07002436 Py_ssize_t i;
2437
Raymond Hettingerc630e102018-08-11 18:39:05 -07002438 if (Py_IS_INFINITY(max)) {
2439 return max;
2440 }
2441 if (found_nan) {
2442 return Py_NAN;
2443 }
Raymond Hettingerf3267142018-09-02 13:34:21 -07002444 if (max == 0.0 || n <= 1) {
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002445 return max;
Raymond Hettinger13990742018-08-11 11:26:36 -07002446 }
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002447 for (i=0 ; i < n ; i++) {
Raymond Hettinger13990742018-08-11 11:26:36 -07002448 x = vec[i];
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002449 assert(Py_IS_FINITE(x) && fabs(x) <= max);
Raymond Hettinger13990742018-08-11 11:26:36 -07002450 x /= max;
Raymond Hettinger21786f52018-08-28 22:47:24 -07002451 x = x*x;
Raymond Hettinger13990742018-08-11 11:26:36 -07002452 oldcsum = csum;
2453 csum += x;
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002454 assert(csum >= x);
Raymond Hettinger21786f52018-08-28 22:47:24 -07002455 frac += (oldcsum - csum) + x;
Raymond Hettinger13990742018-08-11 11:26:36 -07002456 }
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002457 return max * sqrt(csum - 1.0 + frac);
Raymond Hettinger13990742018-08-11 11:26:36 -07002458}
2459
Raymond Hettingerc630e102018-08-11 18:39:05 -07002460#define NUM_STACK_ELEMS 16
2461
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002462/*[clinic input]
2463math.dist
2464
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002465 p: object
2466 q: object
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002467 /
2468
2469Return the Euclidean distance between two points p and q.
2470
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002471The points should be specified as sequences (or iterables) of
2472coordinates. Both inputs must have the same dimension.
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002473
2474Roughly equivalent to:
2475 sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
2476[clinic start generated code]*/
2477
2478static PyObject *
2479math_dist_impl(PyObject *module, PyObject *p, PyObject *q)
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002480/*[clinic end generated code: output=56bd9538d06bbcfe input=74e85e1b6092e68e]*/
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002481{
2482 PyObject *item;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002483 double max = 0.0;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002484 double x, px, qx, result;
2485 Py_ssize_t i, m, n;
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002486 int found_nan = 0, p_allocated = 0, q_allocated = 0;
Raymond Hettingerc630e102018-08-11 18:39:05 -07002487 double diffs_on_stack[NUM_STACK_ELEMS];
2488 double *diffs = diffs_on_stack;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002489
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002490 if (!PyTuple_Check(p)) {
2491 p = PySequence_Tuple(p);
2492 if (p == NULL) {
2493 return NULL;
2494 }
2495 p_allocated = 1;
2496 }
2497 if (!PyTuple_Check(q)) {
2498 q = PySequence_Tuple(q);
2499 if (q == NULL) {
2500 if (p_allocated) {
2501 Py_DECREF(p);
2502 }
2503 return NULL;
2504 }
2505 q_allocated = 1;
2506 }
2507
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002508 m = PyTuple_GET_SIZE(p);
2509 n = PyTuple_GET_SIZE(q);
2510 if (m != n) {
2511 PyErr_SetString(PyExc_ValueError,
2512 "both points must have the same number of dimensions");
2513 return NULL;
2514
2515 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002516 if (n > NUM_STACK_ELEMS) {
2517 diffs = (double *) PyObject_Malloc(n * sizeof(double));
2518 if (diffs == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07002519 return PyErr_NoMemory();
Raymond Hettingerc630e102018-08-11 18:39:05 -07002520 }
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002521 }
2522 for (i=0 ; i<n ; i++) {
2523 item = PyTuple_GET_ITEM(p, i);
Raymond Hettingercfd735e2019-01-29 20:39:53 -08002524 ASSIGN_DOUBLE(px, item, error_exit);
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002525 item = PyTuple_GET_ITEM(q, i);
Raymond Hettingercfd735e2019-01-29 20:39:53 -08002526 ASSIGN_DOUBLE(qx, item, error_exit);
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002527 x = fabs(px - qx);
2528 diffs[i] = x;
2529 found_nan |= Py_IS_NAN(x);
2530 if (x > max) {
2531 max = x;
2532 }
2533 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002534 result = vector_norm(n, diffs, max, found_nan);
2535 if (diffs != diffs_on_stack) {
2536 PyObject_Free(diffs);
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002537 }
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002538 if (p_allocated) {
2539 Py_DECREF(p);
2540 }
2541 if (q_allocated) {
2542 Py_DECREF(q);
2543 }
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002544 return PyFloat_FromDouble(result);
Raymond Hettingerc630e102018-08-11 18:39:05 -07002545
2546 error_exit:
2547 if (diffs != diffs_on_stack) {
2548 PyObject_Free(diffs);
2549 }
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002550 if (p_allocated) {
2551 Py_DECREF(p);
2552 }
2553 if (q_allocated) {
2554 Py_DECREF(q);
2555 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002556 return NULL;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002557}
2558
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002559/* AC: cannot convert yet, waiting for *args support */
Christian Heimes53876d92008-04-19 00:31:39 +00002560static PyObject *
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002561math_hypot(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Christian Heimes53876d92008-04-19 00:31:39 +00002562{
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002563 Py_ssize_t i;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002564 PyObject *item;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002565 double max = 0.0;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002566 double x, result;
2567 int found_nan = 0;
Raymond Hettingerc630e102018-08-11 18:39:05 -07002568 double coord_on_stack[NUM_STACK_ELEMS];
2569 double *coordinates = coord_on_stack;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002570
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002571 if (nargs > NUM_STACK_ELEMS) {
2572 coordinates = (double *) PyObject_Malloc(nargs * sizeof(double));
Zackery Spytz4c49da02018-12-07 03:11:30 -07002573 if (coordinates == NULL) {
2574 return PyErr_NoMemory();
2575 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002576 }
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002577 for (i = 0; i < nargs; i++) {
2578 item = args[i];
Raymond Hettingercfd735e2019-01-29 20:39:53 -08002579 ASSIGN_DOUBLE(x, item, error_exit);
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002580 x = fabs(x);
2581 coordinates[i] = x;
2582 found_nan |= Py_IS_NAN(x);
2583 if (x > max) {
2584 max = x;
2585 }
2586 }
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002587 result = vector_norm(nargs, coordinates, max, found_nan);
Raymond Hettingerc630e102018-08-11 18:39:05 -07002588 if (coordinates != coord_on_stack) {
2589 PyObject_Free(coordinates);
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002590 }
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002591 return PyFloat_FromDouble(result);
Raymond Hettingerc630e102018-08-11 18:39:05 -07002592
2593 error_exit:
2594 if (coordinates != coord_on_stack) {
2595 PyObject_Free(coordinates);
2596 }
2597 return NULL;
Christian Heimes53876d92008-04-19 00:31:39 +00002598}
2599
Raymond Hettingerc630e102018-08-11 18:39:05 -07002600#undef NUM_STACK_ELEMS
2601
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002602PyDoc_STRVAR(math_hypot_doc,
2603 "hypot(*coordinates) -> value\n\n\
2604Multidimensional Euclidean distance from the origin to a point.\n\
2605\n\
2606Roughly equivalent to:\n\
2607 sqrt(sum(x**2 for x in coordinates))\n\
2608\n\
2609For a two dimensional point (x, y), gives the hypotenuse\n\
2610using the Pythagorean theorem: sqrt(x*x + y*y).\n\
2611\n\
2612For example, the hypotenuse of a 3/4/5 right triangle is:\n\
2613\n\
2614 >>> hypot(3.0, 4.0)\n\
2615 5.0\n\
2616");
Christian Heimes53876d92008-04-19 00:31:39 +00002617
2618/* pow can't use math_2, but needs its own wrapper: the problem is
2619 that an infinite result can arise either as a result of overflow
2620 (in which case OverflowError should be raised) or as a result of
2621 e.g. 0.**-5. (for which ValueError needs to be raised.)
2622*/
2623
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002624/*[clinic input]
2625math.pow
Christian Heimes53876d92008-04-19 00:31:39 +00002626
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002627 x: double
2628 y: double
2629 /
2630
2631Return x**y (x to the power of y).
2632[clinic start generated code]*/
2633
2634static PyObject *
2635math_pow_impl(PyObject *module, double x, double y)
2636/*[clinic end generated code: output=fff93e65abccd6b0 input=c26f1f6075088bfd]*/
2637{
2638 double r;
2639 int odd_y;
Christian Heimesa342c012008-04-20 21:01:16 +00002640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 /* deal directly with IEEE specials, to cope with problems on various
2642 platforms whose semantics don't exactly match C99 */
2643 r = 0.; /* silence compiler warning */
2644 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
2645 errno = 0;
2646 if (Py_IS_NAN(x))
2647 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
2648 else if (Py_IS_NAN(y))
2649 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
2650 else if (Py_IS_INFINITY(x)) {
2651 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
2652 if (y > 0.)
2653 r = odd_y ? x : fabs(x);
2654 else if (y == 0.)
2655 r = 1.;
2656 else /* y < 0. */
2657 r = odd_y ? copysign(0., x) : 0.;
2658 }
2659 else if (Py_IS_INFINITY(y)) {
2660 if (fabs(x) == 1.0)
2661 r = 1.;
2662 else if (y > 0. && fabs(x) > 1.0)
2663 r = y;
2664 else if (y < 0. && fabs(x) < 1.0) {
2665 r = -y; /* result is +inf */
2666 if (x == 0.) /* 0**-inf: divide-by-zero */
2667 errno = EDOM;
2668 }
2669 else
2670 r = 0.;
2671 }
2672 }
2673 else {
2674 /* let libm handle finite**finite */
2675 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 r = pow(x, y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 /* a NaN result should arise only from (-ve)**(finite
2678 non-integer); in this case we want to raise ValueError. */
2679 if (!Py_IS_FINITE(r)) {
2680 if (Py_IS_NAN(r)) {
2681 errno = EDOM;
2682 }
2683 /*
2684 an infinite result here arises either from:
2685 (A) (+/-0.)**negative (-> divide-by-zero)
2686 (B) overflow of x**y with x and y finite
2687 */
2688 else if (Py_IS_INFINITY(r)) {
2689 if (x == 0.)
2690 errno = EDOM;
2691 else
2692 errno = ERANGE;
2693 }
2694 }
2695 }
Christian Heimes53876d92008-04-19 00:31:39 +00002696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 if (errno && is_error(r))
2698 return NULL;
2699 else
2700 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00002701}
2702
Christian Heimes53876d92008-04-19 00:31:39 +00002703
Christian Heimes072c0f12008-01-03 23:01:04 +00002704static const double degToRad = Py_MATH_PI / 180.0;
2705static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002706
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002707/*[clinic input]
2708math.degrees
2709
2710 x: double
2711 /
2712
2713Convert angle x from radians to degrees.
2714[clinic start generated code]*/
2715
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002716static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002717math_degrees_impl(PyObject *module, double x)
2718/*[clinic end generated code: output=7fea78b294acd12f input=81e016555d6e3660]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002719{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002720 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002721}
2722
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002723
2724/*[clinic input]
2725math.radians
2726
2727 x: double
2728 /
2729
2730Convert angle x from degrees to radians.
2731[clinic start generated code]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002732
2733static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002734math_radians_impl(PyObject *module, double x)
2735/*[clinic end generated code: output=34daa47caf9b1590 input=91626fc489fe3d63]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 return PyFloat_FromDouble(x * degToRad);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002738}
2739
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002740
2741/*[clinic input]
2742math.isfinite
2743
2744 x: double
2745 /
2746
2747Return True if x is neither an infinity nor a NaN, and False otherwise.
2748[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002749
Christian Heimes072c0f12008-01-03 23:01:04 +00002750static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002751math_isfinite_impl(PyObject *module, double x)
2752/*[clinic end generated code: output=8ba1f396440c9901 input=46967d254812e54a]*/
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002753{
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002754 return PyBool_FromLong((long)Py_IS_FINITE(x));
2755}
2756
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002757
2758/*[clinic input]
2759math.isnan
2760
2761 x: double
2762 /
2763
2764Return True if x is a NaN (not a number), and False otherwise.
2765[clinic start generated code]*/
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002766
2767static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002768math_isnan_impl(PyObject *module, double x)
2769/*[clinic end generated code: output=f537b4d6df878c3e input=935891e66083f46a]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002770{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00002772}
2773
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002774
2775/*[clinic input]
2776math.isinf
2777
2778 x: double
2779 /
2780
2781Return True if x is a positive or negative infinity, and False otherwise.
2782[clinic start generated code]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002783
2784static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002785math_isinf_impl(PyObject *module, double x)
2786/*[clinic end generated code: output=9f00cbec4de7b06b input=32630e4212cf961f]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002787{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002788 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00002789}
2790
Christian Heimes072c0f12008-01-03 23:01:04 +00002791
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002792/*[clinic input]
2793math.isclose -> bool
2794
2795 a: double
2796 b: double
2797 *
2798 rel_tol: double = 1e-09
2799 maximum difference for being considered "close", relative to the
2800 magnitude of the input values
2801 abs_tol: double = 0.0
2802 maximum difference for being considered "close", regardless of the
2803 magnitude of the input values
2804
2805Determine whether two floating point numbers are close in value.
2806
2807Return True if a is close in value to b, and False otherwise.
2808
2809For the values to be considered close, the difference between them
2810must be smaller than at least one of the tolerances.
2811
2812-inf, inf and NaN behave similarly to the IEEE 754 Standard. That
2813is, NaN is not close to anything, even itself. inf and -inf are
2814only close to themselves.
2815[clinic start generated code]*/
2816
2817static int
2818math_isclose_impl(PyObject *module, double a, double b, double rel_tol,
2819 double abs_tol)
2820/*[clinic end generated code: output=b73070207511952d input=f28671871ea5bfba]*/
Tal Einatd5519ed2015-05-31 22:05:00 +03002821{
Tal Einatd5519ed2015-05-31 22:05:00 +03002822 double diff = 0.0;
Tal Einatd5519ed2015-05-31 22:05:00 +03002823
2824 /* sanity check on the inputs */
2825 if (rel_tol < 0.0 || abs_tol < 0.0 ) {
2826 PyErr_SetString(PyExc_ValueError,
2827 "tolerances must be non-negative");
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002828 return -1;
Tal Einatd5519ed2015-05-31 22:05:00 +03002829 }
2830
2831 if ( a == b ) {
2832 /* short circuit exact equality -- needed to catch two infinities of
2833 the same sign. And perhaps speeds things up a bit sometimes.
2834 */
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002835 return 1;
Tal Einatd5519ed2015-05-31 22:05:00 +03002836 }
2837
2838 /* This catches the case of two infinities of opposite sign, or
2839 one infinity and one finite number. Two infinities of opposite
2840 sign would otherwise have an infinite relative tolerance.
2841 Two infinities of the same sign are caught by the equality check
2842 above.
2843 */
2844
2845 if (Py_IS_INFINITY(a) || Py_IS_INFINITY(b)) {
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002846 return 0;
Tal Einatd5519ed2015-05-31 22:05:00 +03002847 }
2848
2849 /* now do the regular computation
2850 this is essentially the "weak" test from the Boost library
2851 */
2852
2853 diff = fabs(b - a);
2854
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002855 return (((diff <= fabs(rel_tol * b)) ||
2856 (diff <= fabs(rel_tol * a))) ||
2857 (diff <= abs_tol));
Tal Einatd5519ed2015-05-31 22:05:00 +03002858}
2859
Pablo Galindo04114112019-03-09 19:18:08 +00002860static inline int
2861_check_long_mult_overflow(long a, long b) {
2862
2863 /* From Python2's int_mul code:
2864
2865 Integer overflow checking for * is painful: Python tried a couple ways, but
2866 they didn't work on all platforms, or failed in endcases (a product of
2867 -sys.maxint-1 has been a particular pain).
2868
2869 Here's another way:
2870
2871 The native long product x*y is either exactly right or *way* off, being
2872 just the last n bits of the true product, where n is the number of bits
2873 in a long (the delivered product is the true product plus i*2**n for
2874 some integer i).
2875
2876 The native double product (double)x * (double)y is subject to three
2877 rounding errors: on a sizeof(long)==8 box, each cast to double can lose
2878 info, and even on a sizeof(long)==4 box, the multiplication can lose info.
2879 But, unlike the native long product, it's not in *range* trouble: even
2880 if sizeof(long)==32 (256-bit longs), the product easily fits in the
2881 dynamic range of a double. So the leading 50 (or so) bits of the double
2882 product are correct.
2883
2884 We check these two ways against each other, and declare victory if they're
2885 approximately the same. Else, because the native long product is the only
2886 one that can lose catastrophic amounts of information, it's the native long
2887 product that must have overflowed.
2888
2889 */
2890
2891 long longprod = (long)((unsigned long)a * b);
2892 double doubleprod = (double)a * (double)b;
2893 double doubled_longprod = (double)longprod;
2894
2895 if (doubled_longprod == doubleprod) {
2896 return 0;
2897 }
2898
2899 const double diff = doubled_longprod - doubleprod;
2900 const double absdiff = diff >= 0.0 ? diff : -diff;
2901 const double absprod = doubleprod >= 0.0 ? doubleprod : -doubleprod;
2902
2903 if (32.0 * absdiff <= absprod) {
2904 return 0;
2905 }
2906
2907 return 1;
2908}
Tal Einatd5519ed2015-05-31 22:05:00 +03002909
Pablo Galindobc098512019-02-07 07:04:02 +00002910/*[clinic input]
2911math.prod
2912
2913 iterable: object
2914 /
2915 *
2916 start: object(c_default="NULL") = 1
2917
2918Calculate the product of all the elements in the input iterable.
2919
2920The default start value for the product is 1.
2921
2922When the iterable is empty, return the start value. This function is
2923intended specifically for use with numeric values and may reject
2924non-numeric types.
2925[clinic start generated code]*/
2926
2927static PyObject *
2928math_prod_impl(PyObject *module, PyObject *iterable, PyObject *start)
2929/*[clinic end generated code: output=36153bedac74a198 input=4c5ab0682782ed54]*/
2930{
2931 PyObject *result = start;
2932 PyObject *temp, *item, *iter;
2933
2934 iter = PyObject_GetIter(iterable);
2935 if (iter == NULL) {
2936 return NULL;
2937 }
2938
2939 if (result == NULL) {
2940 result = PyLong_FromLong(1);
2941 if (result == NULL) {
2942 Py_DECREF(iter);
2943 return NULL;
2944 }
2945 } else {
2946 Py_INCREF(result);
2947 }
2948#ifndef SLOW_PROD
2949 /* Fast paths for integers keeping temporary products in C.
2950 * Assumes all inputs are the same type.
2951 * If the assumption fails, default to use PyObjects instead.
2952 */
2953 if (PyLong_CheckExact(result)) {
2954 int overflow;
2955 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2956 /* If this already overflowed, don't even enter the loop. */
2957 if (overflow == 0) {
2958 Py_DECREF(result);
2959 result = NULL;
2960 }
2961 /* Loop over all the items in the iterable until we finish, we overflow
2962 * or we found a non integer element */
2963 while(result == NULL) {
2964 item = PyIter_Next(iter);
2965 if (item == NULL) {
2966 Py_DECREF(iter);
2967 if (PyErr_Occurred()) {
2968 return NULL;
2969 }
2970 return PyLong_FromLong(i_result);
2971 }
2972 if (PyLong_CheckExact(item)) {
2973 long b = PyLong_AsLongAndOverflow(item, &overflow);
Pablo Galindo04114112019-03-09 19:18:08 +00002974 if (overflow == 0 && !_check_long_mult_overflow(i_result, b)) {
2975 long x = i_result * b;
Pablo Galindobc098512019-02-07 07:04:02 +00002976 i_result = x;
2977 Py_DECREF(item);
2978 continue;
2979 }
2980 }
2981 /* Either overflowed or is not an int.
2982 * Restore real objects and process normally */
2983 result = PyLong_FromLong(i_result);
2984 if (result == NULL) {
2985 Py_DECREF(item);
2986 Py_DECREF(iter);
2987 return NULL;
2988 }
2989 temp = PyNumber_Multiply(result, item);
2990 Py_DECREF(result);
2991 Py_DECREF(item);
2992 result = temp;
2993 if (result == NULL) {
2994 Py_DECREF(iter);
2995 return NULL;
2996 }
2997 }
2998 }
2999
3000 /* Fast paths for floats keeping temporary products in C.
3001 * Assumes all inputs are the same type.
3002 * If the assumption fails, default to use PyObjects instead.
3003 */
3004 if (PyFloat_CheckExact(result)) {
3005 double f_result = PyFloat_AS_DOUBLE(result);
3006 Py_DECREF(result);
3007 result = NULL;
3008 while(result == NULL) {
3009 item = PyIter_Next(iter);
3010 if (item == NULL) {
3011 Py_DECREF(iter);
3012 if (PyErr_Occurred()) {
3013 return NULL;
3014 }
3015 return PyFloat_FromDouble(f_result);
3016 }
3017 if (PyFloat_CheckExact(item)) {
3018 f_result *= PyFloat_AS_DOUBLE(item);
3019 Py_DECREF(item);
3020 continue;
3021 }
3022 if (PyLong_CheckExact(item)) {
3023 long value;
3024 int overflow;
3025 value = PyLong_AsLongAndOverflow(item, &overflow);
3026 if (!overflow) {
3027 f_result *= (double)value;
3028 Py_DECREF(item);
3029 continue;
3030 }
3031 }
3032 result = PyFloat_FromDouble(f_result);
3033 if (result == NULL) {
3034 Py_DECREF(item);
3035 Py_DECREF(iter);
3036 return NULL;
3037 }
3038 temp = PyNumber_Multiply(result, item);
3039 Py_DECREF(result);
3040 Py_DECREF(item);
3041 result = temp;
3042 if (result == NULL) {
3043 Py_DECREF(iter);
3044 return NULL;
3045 }
3046 }
3047 }
3048#endif
3049 /* Consume rest of the iterable (if any) that could not be handled
3050 * by specialized functions above.*/
3051 for(;;) {
3052 item = PyIter_Next(iter);
3053 if (item == NULL) {
3054 /* error, or end-of-sequence */
3055 if (PyErr_Occurred()) {
3056 Py_DECREF(result);
3057 result = NULL;
3058 }
3059 break;
3060 }
3061 temp = PyNumber_Multiply(result, item);
3062 Py_DECREF(result);
3063 Py_DECREF(item);
3064 result = temp;
3065 if (result == NULL)
3066 break;
3067 }
3068 Py_DECREF(iter);
3069 return result;
3070}
3071
3072
Yash Aggarwal4a686502019-06-01 12:51:27 +05303073/*[clinic input]
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003074math.perm
3075
3076 n: object
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003077 k: object = None
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003078 /
3079
3080Number of ways to choose k items from n items without repetition and with order.
3081
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003082Evaluates to n! / (n - k)! when k <= n and evaluates
3083to zero when k > n.
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003084
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003085If k is not specified or is None, then k defaults to n
3086and the function returns n!.
3087
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003088Raises TypeError if either of the arguments are not integers.
3089Raises ValueError if either of the arguments are negative.
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003090[clinic start generated code]*/
3091
3092static PyObject *
3093math_perm_impl(PyObject *module, PyObject *n, PyObject *k)
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003094/*[clinic end generated code: output=e021a25469653e23 input=5311c5a00f359b53]*/
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003095{
3096 PyObject *result = NULL, *factor = NULL;
3097 int overflow, cmp;
3098 long long i, factors;
3099
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003100 if (k == Py_None) {
3101 return math_factorial(module, n);
3102 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003103 n = PyNumber_Index(n);
3104 if (n == NULL) {
3105 return NULL;
3106 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003107 k = PyNumber_Index(k);
3108 if (k == NULL) {
3109 Py_DECREF(n);
3110 return NULL;
3111 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003112
3113 if (Py_SIZE(n) < 0) {
3114 PyErr_SetString(PyExc_ValueError,
3115 "n must be a non-negative integer");
3116 goto error;
3117 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003118 if (Py_SIZE(k) < 0) {
3119 PyErr_SetString(PyExc_ValueError,
3120 "k must be a non-negative integer");
3121 goto error;
3122 }
3123
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003124 cmp = PyObject_RichCompareBool(n, k, Py_LT);
3125 if (cmp != 0) {
3126 if (cmp > 0) {
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003127 result = PyLong_FromLong(0);
3128 goto done;
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003129 }
3130 goto error;
3131 }
3132
3133 factors = PyLong_AsLongLongAndOverflow(k, &overflow);
3134 if (overflow > 0) {
3135 PyErr_Format(PyExc_OverflowError,
3136 "k must not exceed %lld",
3137 LLONG_MAX);
3138 goto error;
3139 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003140 else if (factors == -1) {
3141 /* k is nonnegative, so a return value of -1 can only indicate error */
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003142 goto error;
3143 }
3144
3145 if (factors == 0) {
3146 result = PyLong_FromLong(1);
3147 goto done;
3148 }
3149
3150 result = n;
3151 Py_INCREF(result);
3152 if (factors == 1) {
3153 goto done;
3154 }
3155
3156 factor = n;
3157 Py_INCREF(factor);
3158 for (i = 1; i < factors; ++i) {
3159 Py_SETREF(factor, PyNumber_Subtract(factor, _PyLong_One));
3160 if (factor == NULL) {
3161 goto error;
3162 }
3163 Py_SETREF(result, PyNumber_Multiply(result, factor));
3164 if (result == NULL) {
3165 goto error;
3166 }
3167 }
3168 Py_DECREF(factor);
3169
3170done:
3171 Py_DECREF(n);
3172 Py_DECREF(k);
3173 return result;
3174
3175error:
3176 Py_XDECREF(factor);
3177 Py_XDECREF(result);
3178 Py_DECREF(n);
3179 Py_DECREF(k);
3180 return NULL;
3181}
3182
3183
3184/*[clinic input]
Yash Aggarwal4a686502019-06-01 12:51:27 +05303185math.comb
3186
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003187 n: object
3188 k: object
3189 /
Yash Aggarwal4a686502019-06-01 12:51:27 +05303190
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003191Number of ways to choose k items from n items without repetition and without order.
Yash Aggarwal4a686502019-06-01 12:51:27 +05303192
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003193Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates
3194to zero when k > n.
Yash Aggarwal4a686502019-06-01 12:51:27 +05303195
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003196Also called the binomial coefficient because it is equivalent
3197to the coefficient of k-th term in polynomial expansion of the
3198expression (1 + x)**n.
3199
3200Raises TypeError if either of the arguments are not integers.
3201Raises ValueError if either of the arguments are negative.
Yash Aggarwal4a686502019-06-01 12:51:27 +05303202
3203[clinic start generated code]*/
3204
3205static PyObject *
3206math_comb_impl(PyObject *module, PyObject *n, PyObject *k)
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003207/*[clinic end generated code: output=bd2cec8d854f3493 input=9a05315af2518709]*/
Yash Aggarwal4a686502019-06-01 12:51:27 +05303208{
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003209 PyObject *result = NULL, *factor = NULL, *temp;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303210 int overflow, cmp;
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003211 long long i, factors;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303212
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003213 n = PyNumber_Index(n);
3214 if (n == NULL) {
3215 return NULL;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303216 }
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003217 k = PyNumber_Index(k);
3218 if (k == NULL) {
3219 Py_DECREF(n);
3220 return NULL;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303221 }
3222
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003223 if (Py_SIZE(n) < 0) {
3224 PyErr_SetString(PyExc_ValueError,
3225 "n must be a non-negative integer");
3226 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303227 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003228 if (Py_SIZE(k) < 0) {
3229 PyErr_SetString(PyExc_ValueError,
3230 "k must be a non-negative integer");
3231 goto error;
3232 }
3233
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003234 /* k = min(k, n - k) */
3235 temp = PyNumber_Subtract(n, k);
3236 if (temp == NULL) {
3237 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303238 }
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003239 if (Py_SIZE(temp) < 0) {
3240 Py_DECREF(temp);
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003241 result = PyLong_FromLong(0);
3242 goto done;
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003243 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003244 cmp = PyObject_RichCompareBool(temp, k, Py_LT);
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003245 if (cmp > 0) {
3246 Py_SETREF(k, temp);
Yash Aggarwal4a686502019-06-01 12:51:27 +05303247 }
3248 else {
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003249 Py_DECREF(temp);
3250 if (cmp < 0) {
3251 goto error;
3252 }
Yash Aggarwal4a686502019-06-01 12:51:27 +05303253 }
3254
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003255 factors = PyLong_AsLongLongAndOverflow(k, &overflow);
3256 if (overflow > 0) {
Yash Aggarwal4a686502019-06-01 12:51:27 +05303257 PyErr_Format(PyExc_OverflowError,
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003258 "min(n - k, k) must not exceed %lld",
Yash Aggarwal4a686502019-06-01 12:51:27 +05303259 LLONG_MAX);
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003260 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303261 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003262 if (factors == -1) {
3263 /* k is nonnegative, so a return value of -1 can only indicate error */
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003264 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303265 }
3266
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003267 if (factors == 0) {
3268 result = PyLong_FromLong(1);
3269 goto done;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303270 }
3271
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003272 result = n;
3273 Py_INCREF(result);
3274 if (factors == 1) {
3275 goto done;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303276 }
3277
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003278 factor = n;
3279 Py_INCREF(factor);
3280 for (i = 1; i < factors; ++i) {
3281 Py_SETREF(factor, PyNumber_Subtract(factor, _PyLong_One));
3282 if (factor == NULL) {
3283 goto error;
3284 }
3285 Py_SETREF(result, PyNumber_Multiply(result, factor));
3286 if (result == NULL) {
3287 goto error;
3288 }
Yash Aggarwal4a686502019-06-01 12:51:27 +05303289
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003290 temp = PyLong_FromUnsignedLongLong((unsigned long long)i + 1);
3291 if (temp == NULL) {
3292 goto error;
3293 }
3294 Py_SETREF(result, PyNumber_FloorDivide(result, temp));
3295 Py_DECREF(temp);
3296 if (result == NULL) {
3297 goto error;
3298 }
3299 }
3300 Py_DECREF(factor);
Yash Aggarwal4a686502019-06-01 12:51:27 +05303301
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003302done:
3303 Py_DECREF(n);
3304 Py_DECREF(k);
3305 return result;
3306
3307error:
3308 Py_XDECREF(factor);
3309 Py_XDECREF(result);
3310 Py_DECREF(n);
3311 Py_DECREF(k);
Yash Aggarwal4a686502019-06-01 12:51:27 +05303312 return NULL;
3313}
3314
3315
Victor Stinner100fafc2020-01-12 02:15:42 +01003316/*[clinic input]
3317math.nextafter
3318
3319 x: double
3320 y: double
3321 /
3322
3323Return the next floating-point value after x towards y.
3324[clinic start generated code]*/
3325
3326static PyObject *
3327math_nextafter_impl(PyObject *module, double x, double y)
3328/*[clinic end generated code: output=750c8266c1c540ce input=02b2d50cd1d9f9b6]*/
3329{
Victor Stinner85ead4f2020-01-21 11:14:10 +01003330#if defined(_AIX)
3331 if (x == y) {
3332 /* On AIX 7.1, libm nextafter(-0.0, +0.0) returns -0.0.
3333 Bug fixed in bos.adt.libm 7.2.2.0 by APAR IV95512. */
3334 return PyFloat_FromDouble(y);
3335 }
3336#endif
3337 return PyFloat_FromDouble(nextafter(x, y));
Victor Stinner100fafc2020-01-12 02:15:42 +01003338}
3339
3340
Victor Stinner0b2ab212020-01-13 12:44:35 +01003341/*[clinic input]
3342math.ulp -> double
3343
3344 x: double
3345 /
3346
3347Return the value of the least significant bit of the float x.
3348[clinic start generated code]*/
3349
3350static double
3351math_ulp_impl(PyObject *module, double x)
3352/*[clinic end generated code: output=f5207867a9384dd4 input=31f9bfbbe373fcaa]*/
3353{
3354 if (Py_IS_NAN(x)) {
3355 return x;
3356 }
3357 x = fabs(x);
3358 if (Py_IS_INFINITY(x)) {
3359 return x;
3360 }
3361 double inf = m_inf();
3362 double x2 = nextafter(x, inf);
3363 if (Py_IS_INFINITY(x2)) {
3364 /* special case: x is the largest positive representable float */
3365 x2 = nextafter(x, -inf);
3366 return x - x2;
3367 }
3368 return x2 - x;
3369}
3370
Dong-hee Na5be82412020-03-31 23:33:22 +09003371static int
3372math_exec(PyObject *module)
3373{
3374 if (PyModule_AddObject(module, "pi", PyFloat_FromDouble(Py_MATH_PI)) < 0) {
3375 return -1;
3376 }
3377 if (PyModule_AddObject(module, "e", PyFloat_FromDouble(Py_MATH_E)) < 0) {
3378 return -1;
3379 }
3380 // 2pi
3381 if (PyModule_AddObject(module, "tau", PyFloat_FromDouble(Py_MATH_TAU)) < 0) {
3382 return -1;
3383 }
3384 if (PyModule_AddObject(module, "inf", PyFloat_FromDouble(m_inf())) < 0) {
3385 return -1;
3386 }
3387#if !defined(PY_NO_SHORT_FLOAT_REPR) || defined(Py_NAN)
3388 if (PyModule_AddObject(module, "nan", PyFloat_FromDouble(m_nan())) < 0) {
3389 return -1;
3390 }
3391#endif
3392 return 0;
3393}
Victor Stinner0b2ab212020-01-13 12:44:35 +01003394
Barry Warsaw8b43b191996-12-09 22:32:36 +00003395static PyMethodDef math_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003396 {"acos", math_acos, METH_O, math_acos_doc},
3397 {"acosh", math_acosh, METH_O, math_acosh_doc},
3398 {"asin", math_asin, METH_O, math_asin_doc},
3399 {"asinh", math_asinh, METH_O, math_asinh_doc},
3400 {"atan", math_atan, METH_O, math_atan_doc},
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003401 {"atan2", (PyCFunction)(void(*)(void))math_atan2, METH_FASTCALL, math_atan2_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003402 {"atanh", math_atanh, METH_O, math_atanh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003403 MATH_CEIL_METHODDEF
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003404 {"copysign", (PyCFunction)(void(*)(void))math_copysign, METH_FASTCALL, math_copysign_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003405 {"cos", math_cos, METH_O, math_cos_doc},
3406 {"cosh", math_cosh, METH_O, math_cosh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003407 MATH_DEGREES_METHODDEF
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07003408 MATH_DIST_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003409 {"erf", math_erf, METH_O, math_erf_doc},
3410 {"erfc", math_erfc, METH_O, math_erfc_doc},
3411 {"exp", math_exp, METH_O, math_exp_doc},
3412 {"expm1", math_expm1, METH_O, math_expm1_doc},
3413 {"fabs", math_fabs, METH_O, math_fabs_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003414 MATH_FACTORIAL_METHODDEF
3415 MATH_FLOOR_METHODDEF
3416 MATH_FMOD_METHODDEF
3417 MATH_FREXP_METHODDEF
3418 MATH_FSUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003419 {"gamma", math_gamma, METH_O, math_gamma_doc},
Serhiy Storchaka559e7f12020-02-23 13:21:29 +02003420 {"gcd", (PyCFunction)(void(*)(void))math_gcd, METH_FASTCALL, math_gcd_doc},
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003421 {"hypot", (PyCFunction)(void(*)(void))math_hypot, METH_FASTCALL, math_hypot_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003422 MATH_ISCLOSE_METHODDEF
3423 MATH_ISFINITE_METHODDEF
3424 MATH_ISINF_METHODDEF
3425 MATH_ISNAN_METHODDEF
Mark Dickinson73934b92019-05-18 12:29:50 +01003426 MATH_ISQRT_METHODDEF
Serhiy Storchaka559e7f12020-02-23 13:21:29 +02003427 {"lcm", (PyCFunction)(void(*)(void))math_lcm, METH_FASTCALL, math_lcm_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003428 MATH_LDEXP_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003429 {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003430 MATH_LOG_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003431 {"log1p", math_log1p, METH_O, math_log1p_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003432 MATH_LOG10_METHODDEF
3433 MATH_LOG2_METHODDEF
3434 MATH_MODF_METHODDEF
3435 MATH_POW_METHODDEF
3436 MATH_RADIANS_METHODDEF
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003437 {"remainder", (PyCFunction)(void(*)(void))math_remainder, METH_FASTCALL, math_remainder_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003438 {"sin", math_sin, METH_O, math_sin_doc},
3439 {"sinh", math_sinh, METH_O, math_sinh_doc},
3440 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
3441 {"tan", math_tan, METH_O, math_tan_doc},
3442 {"tanh", math_tanh, METH_O, math_tanh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003443 MATH_TRUNC_METHODDEF
Pablo Galindobc098512019-02-07 07:04:02 +00003444 MATH_PROD_METHODDEF
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003445 MATH_PERM_METHODDEF
Yash Aggarwal4a686502019-06-01 12:51:27 +05303446 MATH_COMB_METHODDEF
Victor Stinner100fafc2020-01-12 02:15:42 +01003447 MATH_NEXTAFTER_METHODDEF
Victor Stinner0b2ab212020-01-13 12:44:35 +01003448 MATH_ULP_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003449 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003450};
3451
Dong-hee Na5be82412020-03-31 23:33:22 +09003452static PyModuleDef_Slot math_slots[] = {
3453 {Py_mod_exec, math_exec},
3454 {0, NULL}
3455};
Guido van Rossumc6e22901998-12-04 19:26:43 +00003456
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003457PyDoc_STRVAR(module_doc,
Ned Batchelder6faad352019-05-17 05:59:14 -04003458"This module provides access to the mathematical functions\n"
3459"defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00003460
Martin v. Löwis1a214512008-06-11 05:26:20 +00003461static struct PyModuleDef mathmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003462 PyModuleDef_HEAD_INIT,
Dong-hee Na5be82412020-03-31 23:33:22 +09003463 .m_name = "math",
3464 .m_doc = module_doc,
3465 .m_size = 0,
3466 .m_methods = math_methods,
3467 .m_slots = math_slots,
Martin v. Löwis1a214512008-06-11 05:26:20 +00003468};
3469
Mark Hammondfe51c6d2002-08-02 02:27:13 +00003470PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003471PyInit_math(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003472{
Dong-hee Na5be82412020-03-31 23:33:22 +09003473 return PyModuleDef_Init(&mathmodule);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003474}