blob: a2a2db29be343d8eaef3106fc36d0f97bfa665bb [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"
Victor Stinner37834132020-10-27 17:12:53 +010058#include "pycore_long.h" // _PyLong_GetZero()
Mark Dickinson664b5112009-12-16 20:23:42 +000059#include "_math.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000060
Serhiy Storchakac9ea9332017-01-19 18:13:09 +020061#include "clinic/mathmodule.c.h"
62
63/*[clinic input]
64module math
65[clinic start generated code]*/
66/*[clinic end generated code: output=da39a3ee5e6b4b0d input=76bc7002685dd942]*/
67
68
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000069/*
70 sin(pi*x), giving accurate results for all finite x (especially x
71 integral or close to an integer). This is here for use in the
72 reflection formula for the gamma function. It conforms to IEEE
73 754-2008 for finite arguments, but not for infinities or nans.
74*/
Tim Petersa40c7932001-09-05 22:36:56 +000075
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000076static const double pi = 3.141592653589793238462643383279502884197;
Mark Dickinson9c91eb82010-07-07 16:17:31 +000077static const double logpi = 1.144729885849400174143427351353058711647;
Louie Lu7a264642017-03-31 01:05:10 +080078#if !defined(HAVE_ERF) || !defined(HAVE_ERFC)
79static const double sqrtpi = 1.772453850905516027298167483341145182798;
80#endif /* !defined(HAVE_ERF) || !defined(HAVE_ERFC) */
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000081
Raymond Hettingercfd735e2019-01-29 20:39:53 -080082
83/* Version of PyFloat_AsDouble() with in-line fast paths
84 for exact floats and integers. Gives a substantial
85 speed improvement for extracting float arguments.
86*/
87
88#define ASSIGN_DOUBLE(target_var, obj, error_label) \
89 if (PyFloat_CheckExact(obj)) { \
90 target_var = PyFloat_AS_DOUBLE(obj); \
91 } \
92 else if (PyLong_CheckExact(obj)) { \
93 target_var = PyLong_AsDouble(obj); \
94 if (target_var == -1.0 && PyErr_Occurred()) { \
95 goto error_label; \
96 } \
97 } \
98 else { \
99 target_var = PyFloat_AsDouble(obj); \
100 if (target_var == -1.0 && PyErr_Occurred()) { \
101 goto error_label; \
102 } \
103 }
104
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000105static double
Dima Pasechnikf57cd822019-02-26 06:36:11 +0000106m_sinpi(double x)
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000107{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 double y, r;
109 int n;
110 /* this function should only ever be called for finite arguments */
111 assert(Py_IS_FINITE(x));
112 y = fmod(fabs(x), 2.0);
113 n = (int)round(2.0*y);
114 assert(0 <= n && n <= 4);
115 switch (n) {
116 case 0:
117 r = sin(pi*y);
118 break;
119 case 1:
120 r = cos(pi*(y-0.5));
121 break;
122 case 2:
123 /* N.B. -sin(pi*(y-1.0)) is *not* equivalent: it would give
124 -0.0 instead of 0.0 when y == 1.0. */
125 r = sin(pi*(1.0-y));
126 break;
127 case 3:
128 r = -cos(pi*(y-1.5));
129 break;
130 case 4:
131 r = sin(pi*(y-2.0));
132 break;
133 default:
Barry Warsawb2e57942017-09-14 18:13:16 -0700134 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 }
136 return copysign(1.0, x)*r;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000137}
138
139/* Implementation of the real gamma function. In extensive but non-exhaustive
140 random tests, this function proved accurate to within <= 10 ulps across the
141 entire float domain. Note that accuracy may depend on the quality of the
142 system math functions, the pow function in particular. Special cases
143 follow C99 annex F. The parameters and method are tailored to platforms
144 whose double format is the IEEE 754 binary64 format.
145
146 Method: for x > 0.0 we use the Lanczos approximation with parameters N=13
147 and g=6.024680040776729583740234375; these parameters are amongst those
148 used by the Boost library. Following Boost (again), we re-express the
149 Lanczos sum as a rational function, and compute it that way. The
150 coefficients below were computed independently using MPFR, and have been
151 double-checked against the coefficients in the Boost source code.
152
153 For x < 0.0 we use the reflection formula.
154
155 There's one minor tweak that deserves explanation: Lanczos' formula for
156 Gamma(x) involves computing pow(x+g-0.5, x-0.5) / exp(x+g-0.5). For many x
157 values, x+g-0.5 can be represented exactly. However, in cases where it
158 can't be represented exactly the small error in x+g-0.5 can be magnified
159 significantly by the pow and exp calls, especially for large x. A cheap
160 correction is to multiply by (1 + e*g/(x+g-0.5)), where e is the error
161 involved in the computation of x+g-0.5 (that is, e = computed value of
162 x+g-0.5 - exact value of x+g-0.5). Here's the proof:
163
164 Correction factor
165 -----------------
166 Write x+g-0.5 = y-e, where y is exactly representable as an IEEE 754
167 double, and e is tiny. Then:
168
169 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) = pow(y-e, x-0.5)/exp(y-e)
170 = pow(y, x-0.5)/exp(y) * C,
171
172 where the correction_factor C is given by
173
174 C = pow(1-e/y, x-0.5) * exp(e)
175
176 Since e is tiny, pow(1-e/y, x-0.5) ~ 1-(x-0.5)*e/y, and exp(x) ~ 1+e, so:
177
178 C ~ (1-(x-0.5)*e/y) * (1+e) ~ 1 + e*(y-(x-0.5))/y
179
180 But y-(x-0.5) = g+e, and g+e ~ g. So we get C ~ 1 + e*g/y, and
181
182 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) ~ pow(y, x-0.5)/exp(y) * (1 + e*g/y),
183
184 Note that for accuracy, when computing r*C it's better to do
185
186 r + e*g/y*r;
187
188 than
189
190 r * (1 + e*g/y);
191
192 since the addition in the latter throws away most of the bits of
193 information in e*g/y.
194*/
195
196#define LANCZOS_N 13
197static const double lanczos_g = 6.024680040776729583740234375;
198static const double lanczos_g_minus_half = 5.524680040776729583740234375;
199static const double lanczos_num_coeffs[LANCZOS_N] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 23531376880.410759688572007674451636754734846804940,
201 42919803642.649098768957899047001988850926355848959,
202 35711959237.355668049440185451547166705960488635843,
203 17921034426.037209699919755754458931112671403265390,
204 6039542586.3520280050642916443072979210699388420708,
205 1439720407.3117216736632230727949123939715485786772,
206 248874557.86205415651146038641322942321632125127801,
207 31426415.585400194380614231628318205362874684987640,
208 2876370.6289353724412254090516208496135991145378768,
209 186056.26539522349504029498971604569928220784236328,
210 8071.6720023658162106380029022722506138218516325024,
211 210.82427775157934587250973392071336271166969580291,
212 2.5066282746310002701649081771338373386264310793408
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000213};
214
215/* denominator is x*(x+1)*...*(x+LANCZOS_N-2) */
216static const double lanczos_den_coeffs[LANCZOS_N] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 0.0, 39916800.0, 120543840.0, 150917976.0, 105258076.0, 45995730.0,
218 13339535.0, 2637558.0, 357423.0, 32670.0, 1925.0, 66.0, 1.0};
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000219
220/* gamma values for small positive integers, 1 though NGAMMA_INTEGRAL */
221#define NGAMMA_INTEGRAL 23
222static const double gamma_integral[NGAMMA_INTEGRAL] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0,
224 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0,
225 1307674368000.0, 20922789888000.0, 355687428096000.0,
226 6402373705728000.0, 121645100408832000.0, 2432902008176640000.0,
227 51090942171709440000.0, 1124000727777607680000.0,
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000228};
229
230/* Lanczos' sum L_g(x), for positive x */
231
232static double
233lanczos_sum(double x)
234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 double num = 0.0, den = 0.0;
236 int i;
237 assert(x > 0.0);
238 /* evaluate the rational function lanczos_sum(x). For large
239 x, the obvious algorithm risks overflow, so we instead
240 rescale the denominator and numerator of the rational
241 function by x**(1-LANCZOS_N) and treat this as a
242 rational function in 1/x. This also reduces the error for
243 larger x values. The choice of cutoff point (5.0 below) is
244 somewhat arbitrary; in tests, smaller cutoff values than
245 this resulted in lower accuracy. */
246 if (x < 5.0) {
247 for (i = LANCZOS_N; --i >= 0; ) {
248 num = num * x + lanczos_num_coeffs[i];
249 den = den * x + lanczos_den_coeffs[i];
250 }
251 }
252 else {
253 for (i = 0; i < LANCZOS_N; i++) {
254 num = num / x + lanczos_num_coeffs[i];
255 den = den / x + lanczos_den_coeffs[i];
256 }
257 }
258 return num/den;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000259}
260
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +0000261/* Constant for +infinity, generated in the same way as float('inf'). */
262
263static double
264m_inf(void)
265{
266#ifndef PY_NO_SHORT_FLOAT_REPR
267 return _Py_dg_infinity(0);
268#else
269 return Py_HUGE_VAL;
270#endif
271}
272
273/* Constant nan value, generated in the same way as float('nan'). */
274/* We don't currently assume that Py_NAN is defined everywhere. */
275
276#if !defined(PY_NO_SHORT_FLOAT_REPR) || defined(Py_NAN)
277
278static double
279m_nan(void)
280{
281#ifndef PY_NO_SHORT_FLOAT_REPR
282 return _Py_dg_stdnan(0);
283#else
284 return Py_NAN;
285#endif
286}
287
288#endif
289
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000290static double
291m_tgamma(double x)
292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 double absx, r, y, z, sqrtpow;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 /* special cases */
296 if (!Py_IS_FINITE(x)) {
297 if (Py_IS_NAN(x) || x > 0.0)
298 return x; /* tgamma(nan) = nan, tgamma(inf) = inf */
299 else {
300 errno = EDOM;
301 return Py_NAN; /* tgamma(-inf) = nan, invalid */
302 }
303 }
304 if (x == 0.0) {
305 errno = EDOM;
Mark Dickinson50203a62011-09-25 15:26:43 +0100306 /* tgamma(+-0.0) = +-inf, divide-by-zero */
307 return copysign(Py_HUGE_VAL, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 /* integer arguments */
311 if (x == floor(x)) {
312 if (x < 0.0) {
313 errno = EDOM; /* tgamma(n) = nan, invalid for */
314 return Py_NAN; /* negative integers n */
315 }
316 if (x <= NGAMMA_INTEGRAL)
317 return gamma_integral[(int)x - 1];
318 }
319 absx = fabs(x);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 /* tiny arguments: tgamma(x) ~ 1/x for x near 0 */
322 if (absx < 1e-20) {
323 r = 1.0/x;
324 if (Py_IS_INFINITY(r))
325 errno = ERANGE;
326 return r;
327 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 /* large arguments: assuming IEEE 754 doubles, tgamma(x) overflows for
330 x > 200, and underflows to +-0.0 for x < -200, not a negative
331 integer. */
332 if (absx > 200.0) {
333 if (x < 0.0) {
Dima Pasechnikf57cd822019-02-26 06:36:11 +0000334 return 0.0/m_sinpi(x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 }
336 else {
337 errno = ERANGE;
338 return Py_HUGE_VAL;
339 }
340 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 y = absx + lanczos_g_minus_half;
343 /* compute error in sum */
344 if (absx > lanczos_g_minus_half) {
345 /* note: the correction can be foiled by an optimizing
346 compiler that (incorrectly) thinks that an expression like
347 a + b - a - b can be optimized to 0.0. This shouldn't
348 happen in a standards-conforming compiler. */
349 double q = y - absx;
350 z = q - lanczos_g_minus_half;
351 }
352 else {
353 double q = y - lanczos_g_minus_half;
354 z = q - absx;
355 }
356 z = z * lanczos_g / y;
357 if (x < 0.0) {
Dima Pasechnikf57cd822019-02-26 06:36:11 +0000358 r = -pi / m_sinpi(absx) / absx * exp(y) / lanczos_sum(absx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 r -= z * r;
360 if (absx < 140.0) {
361 r /= pow(y, absx - 0.5);
362 }
363 else {
364 sqrtpow = pow(y, absx / 2.0 - 0.25);
365 r /= sqrtpow;
366 r /= sqrtpow;
367 }
368 }
369 else {
370 r = lanczos_sum(absx) / exp(y);
371 r += z * r;
372 if (absx < 140.0) {
373 r *= pow(y, absx - 0.5);
374 }
375 else {
376 sqrtpow = pow(y, absx / 2.0 - 0.25);
377 r *= sqrtpow;
378 r *= sqrtpow;
379 }
380 }
381 if (Py_IS_INFINITY(r))
382 errno = ERANGE;
383 return r;
Guido van Rossum8832b621991-12-16 15:44:24 +0000384}
385
Christian Heimes53876d92008-04-19 00:31:39 +0000386/*
Mark Dickinson05d2e082009-12-11 20:17:17 +0000387 lgamma: natural log of the absolute value of the Gamma function.
388 For large arguments, Lanczos' formula works extremely well here.
389*/
390
391static double
392m_lgamma(double x)
393{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200394 double r;
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200395 double absx;
Mark Dickinson05d2e082009-12-11 20:17:17 +0000396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 /* special cases */
398 if (!Py_IS_FINITE(x)) {
399 if (Py_IS_NAN(x))
400 return x; /* lgamma(nan) = nan */
401 else
402 return Py_HUGE_VAL; /* lgamma(+-inf) = +inf */
403 }
Mark Dickinson05d2e082009-12-11 20:17:17 +0000404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 /* integer arguments */
406 if (x == floor(x) && x <= 2.0) {
407 if (x <= 0.0) {
408 errno = EDOM; /* lgamma(n) = inf, divide-by-zero for */
409 return Py_HUGE_VAL; /* integers n <= 0 */
410 }
411 else {
412 return 0.0; /* lgamma(1) = lgamma(2) = 0.0 */
413 }
414 }
Mark Dickinson05d2e082009-12-11 20:17:17 +0000415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 absx = fabs(x);
417 /* tiny arguments: lgamma(x) ~ -log(fabs(x)) for small x */
418 if (absx < 1e-20)
419 return -log(absx);
Mark Dickinson05d2e082009-12-11 20:17:17 +0000420
Mark Dickinson9c91eb82010-07-07 16:17:31 +0000421 /* Lanczos' formula. We could save a fraction of a ulp in accuracy by
422 having a second set of numerator coefficients for lanczos_sum that
423 absorbed the exp(-lanczos_g) term, and throwing out the lanczos_g
424 subtraction below; it's probably not worth it. */
425 r = log(lanczos_sum(absx)) - lanczos_g;
426 r += (absx - 0.5) * (log(absx + lanczos_g - 0.5) - 1);
427 if (x < 0.0)
428 /* Use reflection formula to get value for negative x. */
Dima Pasechnikf57cd822019-02-26 06:36:11 +0000429 r = logpi - log(fabs(m_sinpi(absx))) - log(absx) - r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 if (Py_IS_INFINITY(r))
431 errno = ERANGE;
432 return r;
Mark Dickinson05d2e082009-12-11 20:17:17 +0000433}
434
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200435#if !defined(HAVE_ERF) || !defined(HAVE_ERFC)
436
Mark Dickinson45f992a2009-12-19 11:20:49 +0000437/*
438 Implementations of the error function erf(x) and the complementary error
439 function erfc(x).
440
Brett Cannon45adb312016-01-15 09:38:24 -0800441 Method: we use a series approximation for erf for small x, and a continued
442 fraction approximation for erfc(x) for larger x;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000443 combined with the relations erf(-x) = -erf(x) and erfc(x) = 1.0 - erf(x),
444 this gives us erf(x) and erfc(x) for all x.
445
446 The series expansion used is:
447
448 erf(x) = x*exp(-x*x)/sqrt(pi) * [
449 2/1 + 4/3 x**2 + 8/15 x**4 + 16/105 x**6 + ...]
450
451 The coefficient of x**(2k-2) here is 4**k*factorial(k)/factorial(2*k).
452 This series converges well for smallish x, but slowly for larger x.
453
454 The continued fraction expansion used is:
455
456 erfc(x) = x*exp(-x*x)/sqrt(pi) * [1/(0.5 + x**2 -) 0.5/(2.5 + x**2 - )
457 3.0/(4.5 + x**2 - ) 7.5/(6.5 + x**2 - ) ...]
458
459 after the first term, the general term has the form:
460
461 k*(k-0.5)/(2*k+0.5 + x**2 - ...).
462
463 This expansion converges fast for larger x, but convergence becomes
464 infinitely slow as x approaches 0.0. The (somewhat naive) continued
465 fraction evaluation algorithm used below also risks overflow for large x;
466 but for large x, erfc(x) == 0.0 to within machine precision. (For
467 example, erfc(30.0) is approximately 2.56e-393).
468
469 Parameters: use series expansion for abs(x) < ERF_SERIES_CUTOFF and
470 continued fraction expansion for ERF_SERIES_CUTOFF <= abs(x) <
471 ERFC_CONTFRAC_CUTOFF. ERFC_SERIES_TERMS and ERFC_CONTFRAC_TERMS are the
472 numbers of terms to use for the relevant expansions. */
473
474#define ERF_SERIES_CUTOFF 1.5
475#define ERF_SERIES_TERMS 25
476#define ERFC_CONTFRAC_CUTOFF 30.0
477#define ERFC_CONTFRAC_TERMS 50
478
479/*
480 Error function, via power series.
481
482 Given a finite float x, return an approximation to erf(x).
483 Converges reasonably fast for small x.
484*/
485
486static double
487m_erf_series(double x)
488{
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000489 double x2, acc, fk, result;
490 int i, saved_errno;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 x2 = x * x;
493 acc = 0.0;
494 fk = (double)ERF_SERIES_TERMS + 0.5;
495 for (i = 0; i < ERF_SERIES_TERMS; i++) {
496 acc = 2.0 + x2 * acc / fk;
497 fk -= 1.0;
498 }
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000499 /* Make sure the exp call doesn't affect errno;
500 see m_erfc_contfrac for more. */
501 saved_errno = errno;
502 result = acc * x * exp(-x2) / sqrtpi;
503 errno = saved_errno;
504 return result;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000505}
506
507/*
508 Complementary error function, via continued fraction expansion.
509
510 Given a positive float x, return an approximation to erfc(x). Converges
511 reasonably fast for x large (say, x > 2.0), and should be safe from
512 overflow if x and nterms are not too large. On an IEEE 754 machine, with x
513 <= 30.0, we're safe up to nterms = 100. For x >= 30.0, erfc(x) is smaller
514 than the smallest representable nonzero float. */
515
516static double
517m_erfc_contfrac(double x)
518{
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000519 double x2, a, da, p, p_last, q, q_last, b, result;
520 int i, saved_errno;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 if (x >= ERFC_CONTFRAC_CUTOFF)
523 return 0.0;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 x2 = x*x;
526 a = 0.0;
527 da = 0.5;
528 p = 1.0; p_last = 0.0;
529 q = da + x2; q_last = 1.0;
530 for (i = 0; i < ERFC_CONTFRAC_TERMS; i++) {
531 double temp;
532 a += da;
533 da += 2.0;
534 b = da + x2;
535 temp = p; p = b*p - a*p_last; p_last = temp;
536 temp = q; q = b*q - a*q_last; q_last = temp;
537 }
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000538 /* Issue #8986: On some platforms, exp sets errno on underflow to zero;
539 save the current errno value so that we can restore it later. */
540 saved_errno = errno;
541 result = p / q * x * exp(-x2) / sqrtpi;
542 errno = saved_errno;
543 return result;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000544}
545
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200546#endif /* !defined(HAVE_ERF) || !defined(HAVE_ERFC) */
547
Mark Dickinson45f992a2009-12-19 11:20:49 +0000548/* Error function erf(x), for general x */
549
550static double
551m_erf(double x)
552{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200553#ifdef HAVE_ERF
554 return erf(x);
555#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 double absx, cf;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 if (Py_IS_NAN(x))
559 return x;
560 absx = fabs(x);
561 if (absx < ERF_SERIES_CUTOFF)
562 return m_erf_series(x);
563 else {
564 cf = m_erfc_contfrac(absx);
565 return x > 0.0 ? 1.0 - cf : cf - 1.0;
566 }
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200567#endif
Mark Dickinson45f992a2009-12-19 11:20:49 +0000568}
569
570/* Complementary error function erfc(x), for general x. */
571
572static double
573m_erfc(double x)
574{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200575#ifdef HAVE_ERFC
576 return erfc(x);
577#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 double absx, cf;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 if (Py_IS_NAN(x))
581 return x;
582 absx = fabs(x);
583 if (absx < ERF_SERIES_CUTOFF)
584 return 1.0 - m_erf_series(x);
585 else {
586 cf = m_erfc_contfrac(absx);
587 return x > 0.0 ? cf : 2.0 - cf;
588 }
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200589#endif
Mark Dickinson45f992a2009-12-19 11:20:49 +0000590}
Mark Dickinson05d2e082009-12-11 20:17:17 +0000591
592/*
Christian Heimese57950f2008-04-21 13:08:03 +0000593 wrapper for atan2 that deals directly with special cases before
594 delegating to the platform libm for the remaining cases. This
595 is necessary to get consistent behaviour across platforms.
596 Windows, FreeBSD and alpha Tru64 are amongst platforms that don't
597 always follow C99.
598*/
599
600static double
601m_atan2(double y, double x)
602{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 if (Py_IS_NAN(x) || Py_IS_NAN(y))
604 return Py_NAN;
605 if (Py_IS_INFINITY(y)) {
606 if (Py_IS_INFINITY(x)) {
607 if (copysign(1., x) == 1.)
608 /* atan2(+-inf, +inf) == +-pi/4 */
609 return copysign(0.25*Py_MATH_PI, y);
610 else
611 /* atan2(+-inf, -inf) == +-pi*3/4 */
612 return copysign(0.75*Py_MATH_PI, y);
613 }
614 /* atan2(+-inf, x) == +-pi/2 for finite x */
615 return copysign(0.5*Py_MATH_PI, y);
616 }
617 if (Py_IS_INFINITY(x) || y == 0.) {
618 if (copysign(1., x) == 1.)
619 /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */
620 return copysign(0., y);
621 else
622 /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */
623 return copysign(Py_MATH_PI, y);
624 }
625 return atan2(y, x);
Christian Heimese57950f2008-04-21 13:08:03 +0000626}
627
Mark Dickinsona0ce3752017-04-05 18:34:27 +0100628
629/* IEEE 754-style remainder operation: x - n*y where n*y is the nearest
630 multiple of y to x, taking n even in the case of a tie. Assuming an IEEE 754
631 binary floating-point format, the result is always exact. */
632
633static double
634m_remainder(double x, double y)
635{
636 /* Deal with most common case first. */
637 if (Py_IS_FINITE(x) && Py_IS_FINITE(y)) {
638 double absx, absy, c, m, r;
639
640 if (y == 0.0) {
641 return Py_NAN;
642 }
643
644 absx = fabs(x);
645 absy = fabs(y);
646 m = fmod(absx, absy);
647
648 /*
649 Warning: some subtlety here. What we *want* to know at this point is
650 whether the remainder m is less than, equal to, or greater than half
651 of absy. However, we can't do that comparison directly because we
Mark Dickinson01484702019-07-13 16:50:03 +0100652 can't be sure that 0.5*absy is representable (the multiplication
Mark Dickinsona0ce3752017-04-05 18:34:27 +0100653 might incur precision loss due to underflow). So instead we compare
654 m with the complement c = absy - m: m < 0.5*absy if and only if m <
655 c, and so on. The catch is that absy - m might also not be
656 representable, but it turns out that it doesn't matter:
657
658 - if m > 0.5*absy then absy - m is exactly representable, by
659 Sterbenz's lemma, so m > c
660 - if m == 0.5*absy then again absy - m is exactly representable
661 and m == c
662 - if m < 0.5*absy then either (i) 0.5*absy is exactly representable,
663 in which case 0.5*absy < absy - m, so 0.5*absy <= c and hence m <
664 c, or (ii) absy is tiny, either subnormal or in the lowest normal
665 binade. Then absy - m is exactly representable and again m < c.
666 */
667
668 c = absy - m;
669 if (m < c) {
670 r = m;
671 }
672 else if (m > c) {
673 r = -c;
674 }
675 else {
676 /*
677 Here absx is exactly halfway between two multiples of absy,
678 and we need to choose the even multiple. x now has the form
679
680 absx = n * absy + m
681
682 for some integer n (recalling that m = 0.5*absy at this point).
683 If n is even we want to return m; if n is odd, we need to
684 return -m.
685
686 So
687
688 0.5 * (absx - m) = (n/2) * absy
689
690 and now reducing modulo absy gives us:
691
692 | m, if n is odd
693 fmod(0.5 * (absx - m), absy) = |
694 | 0, if n is even
695
696 Now m - 2.0 * fmod(...) gives the desired result: m
697 if n is even, -m if m is odd.
698
699 Note that all steps in fmod(0.5 * (absx - m), absy)
700 will be computed exactly, with no rounding error
701 introduced.
702 */
703 assert(m == c);
704 r = m - 2.0 * fmod(0.5 * (absx - m), absy);
705 }
706 return copysign(1.0, x) * r;
707 }
708
709 /* Special values. */
710 if (Py_IS_NAN(x)) {
711 return x;
712 }
713 if (Py_IS_NAN(y)) {
714 return y;
715 }
716 if (Py_IS_INFINITY(x)) {
717 return Py_NAN;
718 }
719 assert(Py_IS_INFINITY(y));
720 return x;
721}
722
723
Christian Heimese57950f2008-04-21 13:08:03 +0000724/*
Mark Dickinsone675f082008-12-11 21:56:00 +0000725 Various platforms (Solaris, OpenBSD) do nonstandard things for log(0),
726 log(-ve), log(NaN). Here are wrappers for log and log10 that deal with
727 special values directly, passing positive non-special values through to
728 the system log/log10.
729 */
730
731static double
732m_log(double x)
733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 if (Py_IS_FINITE(x)) {
735 if (x > 0.0)
736 return log(x);
737 errno = EDOM;
738 if (x == 0.0)
739 return -Py_HUGE_VAL; /* log(0) = -inf */
740 else
741 return Py_NAN; /* log(-ve) = nan */
742 }
743 else if (Py_IS_NAN(x))
744 return x; /* log(nan) = nan */
745 else if (x > 0.0)
746 return x; /* log(inf) = inf */
747 else {
748 errno = EDOM;
749 return Py_NAN; /* log(-inf) = nan */
750 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000751}
752
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200753/*
754 log2: log to base 2.
755
756 Uses an algorithm that should:
Mark Dickinson83b8c0b2011-05-09 08:40:20 +0100757
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200758 (a) produce exact results for powers of 2, and
Mark Dickinson83b8c0b2011-05-09 08:40:20 +0100759 (b) give a monotonic log2 (for positive finite floats),
760 assuming that the system log is monotonic.
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200761*/
762
763static double
764m_log2(double x)
765{
766 if (!Py_IS_FINITE(x)) {
767 if (Py_IS_NAN(x))
768 return x; /* log2(nan) = nan */
769 else if (x > 0.0)
770 return x; /* log2(+inf) = +inf */
771 else {
772 errno = EDOM;
773 return Py_NAN; /* log2(-inf) = nan, invalid-operation */
774 }
775 }
776
777 if (x > 0.0) {
Victor Stinner8f9f8d62011-05-09 12:45:41 +0200778#ifdef HAVE_LOG2
779 return log2(x);
780#else
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200781 double m;
782 int e;
783 m = frexp(x, &e);
784 /* We want log2(m * 2**e) == log(m) / log(2) + e. Care is needed when
785 * x is just greater than 1.0: in that case e is 1, log(m) is negative,
786 * and we get significant cancellation error from the addition of
787 * log(m) / log(2) to e. The slight rewrite of the expression below
788 * avoids this problem.
789 */
790 if (x >= 1.0) {
791 return log(2.0 * m) / log(2.0) + (e - 1);
792 }
793 else {
794 return log(m) / log(2.0) + e;
795 }
Victor Stinner8f9f8d62011-05-09 12:45:41 +0200796#endif
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200797 }
798 else if (x == 0.0) {
799 errno = EDOM;
800 return -Py_HUGE_VAL; /* log2(0) = -inf, divide-by-zero */
801 }
802 else {
803 errno = EDOM;
Mark Dickinson23442582011-05-09 08:05:00 +0100804 return Py_NAN; /* log2(-inf) = nan, invalid-operation */
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200805 }
806}
807
Mark Dickinsone675f082008-12-11 21:56:00 +0000808static double
809m_log10(double x)
810{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 if (Py_IS_FINITE(x)) {
812 if (x > 0.0)
813 return log10(x);
814 errno = EDOM;
815 if (x == 0.0)
816 return -Py_HUGE_VAL; /* log10(0) = -inf */
817 else
818 return Py_NAN; /* log10(-ve) = nan */
819 }
820 else if (Py_IS_NAN(x))
821 return x; /* log10(nan) = nan */
822 else if (x > 0.0)
823 return x; /* log10(inf) = inf */
824 else {
825 errno = EDOM;
826 return Py_NAN; /* log10(-inf) = nan */
827 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000828}
829
830
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200831static PyObject *
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200832math_gcd(PyObject *module, PyObject * const *args, Py_ssize_t nargs)
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200833{
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200834 PyObject *res, *x;
835 Py_ssize_t i;
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300836
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200837 if (nargs == 0) {
838 return PyLong_FromLong(0);
839 }
840 res = PyNumber_Index(args[0]);
841 if (res == NULL) {
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300842 return NULL;
843 }
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200844 if (nargs == 1) {
845 Py_SETREF(res, PyNumber_Absolute(res));
846 return res;
847 }
Miss Islington (bot)41159962021-05-26 16:13:17 -0700848
849 PyObject *one = _PyLong_GetOne(); // borrowed ref
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200850 for (i = 1; i < nargs; i++) {
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +0300851 x = _PyNumber_Index(args[i]);
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200852 if (x == NULL) {
853 Py_DECREF(res);
854 return NULL;
855 }
Miss Islington (bot)41159962021-05-26 16:13:17 -0700856 if (res == one) {
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200857 /* Fast path: just check arguments.
858 It is okay to use identity comparison here. */
859 Py_DECREF(x);
860 continue;
861 }
862 Py_SETREF(res, _PyLong_GCD(res, x));
863 Py_DECREF(x);
864 if (res == NULL) {
865 return NULL;
866 }
867 }
868 return res;
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300869}
870
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200871PyDoc_STRVAR(math_gcd_doc,
872"gcd($module, *integers)\n"
873"--\n"
874"\n"
875"Greatest Common Divisor.");
876
877
878static PyObject *
879long_lcm(PyObject *a, PyObject *b)
880{
881 PyObject *g, *m, *f, *ab;
882
883 if (Py_SIZE(a) == 0 || Py_SIZE(b) == 0) {
884 return PyLong_FromLong(0);
885 }
886 g = _PyLong_GCD(a, b);
887 if (g == NULL) {
888 return NULL;
889 }
890 f = PyNumber_FloorDivide(a, g);
891 Py_DECREF(g);
892 if (f == NULL) {
893 return NULL;
894 }
895 m = PyNumber_Multiply(f, b);
896 Py_DECREF(f);
897 if (m == NULL) {
898 return NULL;
899 }
900 ab = PyNumber_Absolute(m);
901 Py_DECREF(m);
902 return ab;
903}
904
905
906static PyObject *
907math_lcm(PyObject *module, PyObject * const *args, Py_ssize_t nargs)
908{
909 PyObject *res, *x;
910 Py_ssize_t i;
911
912 if (nargs == 0) {
913 return PyLong_FromLong(1);
914 }
915 res = PyNumber_Index(args[0]);
916 if (res == NULL) {
917 return NULL;
918 }
919 if (nargs == 1) {
920 Py_SETREF(res, PyNumber_Absolute(res));
921 return res;
922 }
Miss Islington (bot)41159962021-05-26 16:13:17 -0700923
924 PyObject *zero = _PyLong_GetZero(); // borrowed ref
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200925 for (i = 1; i < nargs; i++) {
926 x = PyNumber_Index(args[i]);
927 if (x == NULL) {
928 Py_DECREF(res);
929 return NULL;
930 }
Miss Islington (bot)41159962021-05-26 16:13:17 -0700931 if (res == zero) {
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200932 /* Fast path: just check arguments.
933 It is okay to use identity comparison here. */
934 Py_DECREF(x);
935 continue;
936 }
937 Py_SETREF(res, long_lcm(res, x));
938 Py_DECREF(x);
939 if (res == NULL) {
940 return NULL;
941 }
942 }
943 return res;
944}
945
946
947PyDoc_STRVAR(math_lcm_doc,
948"lcm($module, *integers)\n"
949"--\n"
950"\n"
951"Least Common Multiple.");
952
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300953
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000954/* Call is_error when errno != 0, and where x is the result libm
955 * returned. is_error will usually set up an exception and return
956 * true (1), but may return false (0) without setting up an exception.
957 */
958static int
959is_error(double x)
960{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 int result = 1; /* presumption of guilt */
962 assert(errno); /* non-zero errno is a precondition for calling */
963 if (errno == EDOM)
964 PyErr_SetString(PyExc_ValueError, "math domain error");
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 else if (errno == ERANGE) {
967 /* ANSI C generally requires libm functions to set ERANGE
968 * on overflow, but also generally *allows* them to set
969 * ERANGE on underflow too. There's no consistency about
970 * the latter across platforms.
971 * Alas, C99 never requires that errno be set.
972 * Here we suppress the underflow errors (libm functions
973 * should return a zero on underflow, and +- HUGE_VAL on
974 * overflow, so testing the result for zero suffices to
975 * distinguish the cases).
976 *
977 * On some platforms (Ubuntu/ia64) it seems that errno can be
978 * set to ERANGE for subnormal results that do *not* underflow
979 * to zero. So to be safe, we'll ignore ERANGE whenever the
980 * function result is less than one in absolute value.
981 */
982 if (fabs(x) < 1.0)
983 result = 0;
984 else
985 PyErr_SetString(PyExc_OverflowError,
986 "math range error");
987 }
988 else
989 /* Unexpected math error */
990 PyErr_SetFromErrno(PyExc_ValueError);
991 return result;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000992}
993
Mark Dickinsone675f082008-12-11 21:56:00 +0000994/*
Christian Heimes53876d92008-04-19 00:31:39 +0000995 math_1 is used to wrap a libm function f that takes a double
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200996 argument and returns a double.
Christian Heimes53876d92008-04-19 00:31:39 +0000997
998 The error reporting follows these rules, which are designed to do
999 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
1000 platforms.
1001
1002 - a NaN result from non-NaN inputs causes ValueError to be raised
1003 - an infinite result from finite inputs causes OverflowError to be
1004 raised if can_overflow is 1, or raises ValueError if can_overflow
1005 is 0.
1006 - if the result is finite and errno == EDOM then ValueError is
1007 raised
1008 - if the result is finite and nonzero and errno == ERANGE then
1009 OverflowError is raised
1010
1011 The last rule is used to catch overflow on platforms which follow
1012 C89 but for which HUGE_VAL is not an infinity.
1013
1014 For the majority of one-argument functions these rules are enough
1015 to ensure that Python's functions behave as specified in 'Annex F'
1016 of the C99 standard, with the 'invalid' and 'divide-by-zero'
1017 floating-point exceptions mapping to Python's ValueError and the
1018 'overflow' floating-point exception mapping to OverflowError.
1019 math_1 only works for functions that don't have singularities *and*
1020 the possibility of overflow; fortunately, that covers everything we
1021 care about right now.
1022*/
1023
Barry Warsaw8b43b191996-12-09 22:32:36 +00001024static PyObject *
Jeffrey Yasskinc2155832008-01-05 20:03:11 +00001025math_1_to_whatever(PyObject *arg, double (*func) (double),
Christian Heimes53876d92008-04-19 00:31:39 +00001026 PyObject *(*from_double_func) (double),
1027 int can_overflow)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001028{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 double x, r;
1030 x = PyFloat_AsDouble(arg);
1031 if (x == -1.0 && PyErr_Occurred())
1032 return NULL;
1033 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 r = (*func)(x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 if (Py_IS_NAN(r) && !Py_IS_NAN(x)) {
1036 PyErr_SetString(PyExc_ValueError,
1037 "math domain error"); /* invalid arg */
1038 return NULL;
1039 }
1040 if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) {
Benjamin Peterson2354a752012-03-13 16:13:09 -05001041 if (can_overflow)
1042 PyErr_SetString(PyExc_OverflowError,
1043 "math range error"); /* overflow */
1044 else
1045 PyErr_SetString(PyExc_ValueError,
1046 "math domain error"); /* singularity */
1047 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 }
1049 if (Py_IS_FINITE(r) && errno && is_error(r))
1050 /* this branch unnecessary on most platforms */
1051 return NULL;
Mark Dickinsonde429622008-05-01 00:19:23 +00001052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 return (*from_double_func)(r);
Christian Heimes53876d92008-04-19 00:31:39 +00001054}
1055
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001056/* variant of math_1, to be used when the function being wrapped is known to
1057 set errno properly (that is, errno = EDOM for invalid or divide-by-zero,
1058 errno = ERANGE for overflow). */
1059
1060static PyObject *
1061math_1a(PyObject *arg, double (*func) (double))
1062{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 double x, r;
1064 x = PyFloat_AsDouble(arg);
1065 if (x == -1.0 && PyErr_Occurred())
1066 return NULL;
1067 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 r = (*func)(x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 if (errno && is_error(r))
1070 return NULL;
1071 return PyFloat_FromDouble(r);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001072}
1073
Christian Heimes53876d92008-04-19 00:31:39 +00001074/*
1075 math_2 is used to wrap a libm function f that takes two double
1076 arguments and returns a double.
1077
1078 The error reporting follows these rules, which are designed to do
1079 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
1080 platforms.
1081
1082 - a NaN result from non-NaN inputs causes ValueError to be raised
1083 - an infinite result from finite inputs causes OverflowError to be
1084 raised.
1085 - if the result is finite and errno == EDOM then ValueError is
1086 raised
1087 - if the result is finite and nonzero and errno == ERANGE then
1088 OverflowError is raised
1089
1090 The last rule is used to catch overflow on platforms which follow
1091 C89 but for which HUGE_VAL is not an infinity.
1092
1093 For most two-argument functions (copysign, fmod, hypot, atan2)
1094 these rules are enough to ensure that Python's functions behave as
1095 specified in 'Annex F' of the C99 standard, with the 'invalid' and
1096 'divide-by-zero' floating-point exceptions mapping to Python's
1097 ValueError and the 'overflow' floating-point exception mapping to
1098 OverflowError.
1099*/
1100
1101static PyObject *
1102math_1(PyObject *arg, double (*func) (double), int can_overflow)
1103{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow);
Jeffrey Yasskinc2155832008-01-05 20:03:11 +00001105}
1106
1107static PyObject *
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02001108math_2(PyObject *const *args, Py_ssize_t nargs,
1109 double (*func) (double, double), const char *funcname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 double x, y, r;
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02001112 if (!_PyArg_CheckPositional(funcname, nargs, 2, 2))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 return NULL;
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02001114 x = PyFloat_AsDouble(args[0]);
Zackery Spytz5208b4b2020-03-14 04:45:32 -06001115 if (x == -1.0 && PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 return NULL;
Zackery Spytz5208b4b2020-03-14 04:45:32 -06001117 }
1118 y = PyFloat_AsDouble(args[1]);
1119 if (y == -1.0 && PyErr_Occurred()) {
1120 return NULL;
1121 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 r = (*func)(x, y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 if (Py_IS_NAN(r)) {
1125 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1126 errno = EDOM;
1127 else
1128 errno = 0;
1129 }
1130 else if (Py_IS_INFINITY(r)) {
1131 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
1132 errno = ERANGE;
1133 else
1134 errno = 0;
1135 }
1136 if (errno && is_error(r))
1137 return NULL;
1138 else
1139 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001140}
1141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142#define FUNC1(funcname, func, can_overflow, docstring) \
1143 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
1144 return math_1(args, func, can_overflow); \
1145 }\
1146 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148#define FUNC1A(funcname, func, docstring) \
1149 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
1150 return math_1a(args, func); \
1151 }\
1152 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001153
Fred Drake40c48682000-07-03 18:11:56 +00001154#define FUNC2(funcname, func, docstring) \
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02001155 static PyObject * math_##funcname(PyObject *self, PyObject *const *args, Py_ssize_t nargs) { \
1156 return math_2(args, nargs, func, #funcname); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 }\
1158 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001159
Christian Heimes53876d92008-04-19 00:31:39 +00001160FUNC1(acos, acos, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001161 "acos($module, x, /)\n--\n\n"
Giovanni Cappellottodc3f99f2019-07-13 09:59:55 -04001162 "Return the arc cosine (measured in radians) of x.\n\n"
1163 "The result is between 0 and pi.")
Mark Dickinsonf3718592009-12-21 15:27:41 +00001164FUNC1(acosh, m_acosh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001165 "acosh($module, x, /)\n--\n\n"
1166 "Return the inverse hyperbolic cosine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001167FUNC1(asin, asin, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001168 "asin($module, x, /)\n--\n\n"
Giovanni Cappellottodc3f99f2019-07-13 09:59:55 -04001169 "Return the arc sine (measured in radians) of x.\n\n"
1170 "The result is between -pi/2 and pi/2.")
Mark Dickinsonf3718592009-12-21 15:27:41 +00001171FUNC1(asinh, m_asinh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001172 "asinh($module, x, /)\n--\n\n"
1173 "Return the inverse hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001174FUNC1(atan, atan, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001175 "atan($module, x, /)\n--\n\n"
Giovanni Cappellottodc3f99f2019-07-13 09:59:55 -04001176 "Return the arc tangent (measured in radians) of x.\n\n"
1177 "The result is between -pi/2 and pi/2.")
Christian Heimese57950f2008-04-21 13:08:03 +00001178FUNC2(atan2, m_atan2,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001179 "atan2($module, y, x, /)\n--\n\n"
1180 "Return the arc tangent (measured in radians) of y/x.\n\n"
Tim Petersfe71f812001-08-07 22:10:00 +00001181 "Unlike atan(y/x), the signs of both x and y are considered.")
Mark Dickinsonf3718592009-12-21 15:27:41 +00001182FUNC1(atanh, m_atanh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001183 "atanh($module, x, /)\n--\n\n"
1184 "Return the inverse hyperbolic tangent of x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +00001185
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001186/*[clinic input]
1187math.ceil
1188
1189 x as number: object
1190 /
1191
1192Return the ceiling of x as an Integral.
1193
1194This is the smallest integer >= x.
1195[clinic start generated code]*/
1196
1197static PyObject *
1198math_ceil(PyObject *module, PyObject *number)
1199/*[clinic end generated code: output=6c3b8a78bc201c67 input=2725352806399cab]*/
1200{
Benjamin Petersonce798522012-01-22 11:24:29 -05001201 _Py_IDENTIFIER(__ceil__);
Guido van Rossum13e05de2007-08-23 22:56:55 +00001202
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001203 if (!PyFloat_CheckExact(number)) {
1204 PyObject *method = _PyObject_LookupSpecial(number, &PyId___ceil__);
1205 if (method != NULL) {
1206 PyObject *result = _PyObject_CallNoArg(method);
1207 Py_DECREF(method);
1208 return result;
1209 }
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001210 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 return NULL;
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001212 }
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001213 double x = PyFloat_AsDouble(number);
1214 if (x == -1.0 && PyErr_Occurred())
1215 return NULL;
1216
1217 return PyLong_FromDouble(ceil(x));
Guido van Rossum13e05de2007-08-23 22:56:55 +00001218}
1219
Christian Heimes072c0f12008-01-03 23:01:04 +00001220FUNC2(copysign, copysign,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001221 "copysign($module, x, y, /)\n--\n\n"
1222 "Return a float with the magnitude (absolute value) of x but the sign of y.\n\n"
1223 "On platforms that support signed zeros, copysign(1.0, -0.0)\n"
1224 "returns -1.0.\n")
Christian Heimes53876d92008-04-19 00:31:39 +00001225FUNC1(cos, cos, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001226 "cos($module, x, /)\n--\n\n"
1227 "Return the cosine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001228FUNC1(cosh, cosh, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001229 "cosh($module, x, /)\n--\n\n"
1230 "Return the hyperbolic cosine of x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +00001231FUNC1A(erf, m_erf,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001232 "erf($module, x, /)\n--\n\n"
1233 "Error function at x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +00001234FUNC1A(erfc, m_erfc,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001235 "erfc($module, x, /)\n--\n\n"
1236 "Complementary error function at x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001237FUNC1(exp, exp, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001238 "exp($module, x, /)\n--\n\n"
1239 "Return e raised to the power of x.")
Mark Dickinson664b5112009-12-16 20:23:42 +00001240FUNC1(expm1, m_expm1, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001241 "expm1($module, x, /)\n--\n\n"
1242 "Return exp(x)-1.\n\n"
Mark Dickinson664b5112009-12-16 20:23:42 +00001243 "This function avoids the loss of precision involved in the direct "
1244 "evaluation of exp(x)-1 for small x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001245FUNC1(fabs, fabs, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001246 "fabs($module, x, /)\n--\n\n"
1247 "Return the absolute value of the float x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +00001248
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001249/*[clinic input]
1250math.floor
1251
1252 x as number: object
1253 /
1254
1255Return the floor of x as an Integral.
1256
1257This is the largest integer <= x.
1258[clinic start generated code]*/
1259
1260static PyObject *
1261math_floor(PyObject *module, PyObject *number)
1262/*[clinic end generated code: output=c6a65c4884884b8a input=63af6b5d7ebcc3d6]*/
1263{
Raymond Hettinger930f4512020-06-23 11:45:25 -07001264 double x;
1265
Benjamin Petersonce798522012-01-22 11:24:29 -05001266 _Py_IDENTIFIER(__floor__);
Guido van Rossum13e05de2007-08-23 22:56:55 +00001267
Raymond Hettinger930f4512020-06-23 11:45:25 -07001268 if (PyFloat_CheckExact(number)) {
1269 x = PyFloat_AS_DOUBLE(number);
1270 }
1271 else
1272 {
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001273 PyObject *method = _PyObject_LookupSpecial(number, &PyId___floor__);
1274 if (method != NULL) {
1275 PyObject *result = _PyObject_CallNoArg(method);
1276 Py_DECREF(method);
1277 return result;
1278 }
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001279 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 return NULL;
Raymond Hettinger930f4512020-06-23 11:45:25 -07001281 x = PyFloat_AsDouble(number);
1282 if (x == -1.0 && PyErr_Occurred())
1283 return NULL;
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001284 }
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001285 return PyLong_FromDouble(floor(x));
Guido van Rossum13e05de2007-08-23 22:56:55 +00001286}
1287
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001288FUNC1A(gamma, m_tgamma,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001289 "gamma($module, x, /)\n--\n\n"
1290 "Gamma function at x.")
Mark Dickinson05d2e082009-12-11 20:17:17 +00001291FUNC1A(lgamma, m_lgamma,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001292 "lgamma($module, x, /)\n--\n\n"
1293 "Natural logarithm of absolute value of Gamma function at x.")
Mark Dickinsonbe64d952010-07-07 16:21:29 +00001294FUNC1(log1p, m_log1p, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001295 "log1p($module, x, /)\n--\n\n"
1296 "Return the natural logarithm of 1+x (base e).\n\n"
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001297 "The result is computed in a way which is accurate for x near zero.")
Mark Dickinsona0ce3752017-04-05 18:34:27 +01001298FUNC2(remainder, m_remainder,
1299 "remainder($module, x, y, /)\n--\n\n"
1300 "Difference between x and the closest integer multiple of y.\n\n"
1301 "Return x - n*y where n*y is the closest integer multiple of y.\n"
1302 "In the case where x is exactly halfway between two multiples of\n"
1303 "y, the nearest even value of n is used. The result is always exact.")
Christian Heimes53876d92008-04-19 00:31:39 +00001304FUNC1(sin, sin, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001305 "sin($module, x, /)\n--\n\n"
1306 "Return the sine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001307FUNC1(sinh, sinh, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001308 "sinh($module, x, /)\n--\n\n"
1309 "Return the hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001310FUNC1(sqrt, sqrt, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001311 "sqrt($module, x, /)\n--\n\n"
1312 "Return the square root of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001313FUNC1(tan, tan, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001314 "tan($module, x, /)\n--\n\n"
1315 "Return the tangent of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001316FUNC1(tanh, tanh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001317 "tanh($module, x, /)\n--\n\n"
1318 "Return the hyperbolic tangent of x.")
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001319
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001320/* Precision summation function as msum() by Raymond Hettinger in
1321 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
1322 enhanced with the exact partials sum and roundoff from Mark
1323 Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
1324 See those links for more details, proofs and other references.
1325
1326 Note 1: IEEE 754R floating point semantics are assumed,
1327 but the current implementation does not re-establish special
1328 value semantics across iterations (i.e. handling -Inf + Inf).
1329
1330 Note 2: No provision is made for intermediate overflow handling;
Georg Brandlf78e02b2008-06-10 17:40:04 +00001331 therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001332 sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
1333 overflow of the first partial sum.
1334
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001335 Note 3: The intermediate values lo, yr, and hi are declared volatile so
1336 aggressive compilers won't algebraically reduce lo to always be exactly 0.0.
Georg Brandlf78e02b2008-06-10 17:40:04 +00001337 Also, the volatile declaration forces the values to be stored in memory as
1338 regular doubles instead of extended long precision (80-bit) values. This
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001339 prevents double rounding because any addition or subtraction of two doubles
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 can be resolved exactly into double-sized hi and lo values. As long as the
Georg Brandlf78e02b2008-06-10 17:40:04 +00001341 hi value gets forced into a double before yr and lo are computed, the extra
1342 bits in downstream extended precision operations (x87 for example) will be
1343 exactly zero and therefore can be losslessly stored back into a double,
1344 thereby preventing double rounding.
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001345
1346 Note 4: A similar implementation is in Modules/cmathmodule.c.
1347 Be sure to update both when making changes.
1348
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001349 Note 5: The signature of math.fsum() differs from builtins.sum()
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001350 because the start argument doesn't make sense in the context of
1351 accurate summation. Since the partials table is collapsed before
1352 returning a result, sum(seq2, start=sum(seq1)) may not equal the
1353 accurate result returned by sum(itertools.chain(seq1, seq2)).
1354*/
1355
1356#define NUM_PARTIALS 32 /* initial partials array size, on stack */
1357
1358/* Extend the partials array p[] by doubling its size. */
1359static int /* non-zero on error */
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001360_fsum_realloc(double **p_ptr, Py_ssize_t n,
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001361 double *ps, Py_ssize_t *m_ptr)
1362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 void *v = NULL;
1364 Py_ssize_t m = *m_ptr;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 m += m; /* double */
Victor Stinner049e5092014-08-17 22:20:00 +02001367 if (n < m && (size_t)m < ((size_t)PY_SSIZE_T_MAX / sizeof(double))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 double *p = *p_ptr;
1369 if (p == ps) {
1370 v = PyMem_Malloc(sizeof(double) * m);
1371 if (v != NULL)
1372 memcpy(v, ps, sizeof(double) * n);
1373 }
1374 else
1375 v = PyMem_Realloc(p, sizeof(double) * m);
1376 }
1377 if (v == NULL) { /* size overflow or no memory */
1378 PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
1379 return 1;
1380 }
1381 *p_ptr = (double*) v;
1382 *m_ptr = m;
1383 return 0;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001384}
1385
1386/* Full precision summation of a sequence of floats.
1387
1388 def msum(iterable):
1389 partials = [] # sorted, non-overlapping partial sums
1390 for x in iterable:
Mark Dickinsonfdb0acc2010-06-25 20:22:24 +00001391 i = 0
1392 for y in partials:
1393 if abs(x) < abs(y):
1394 x, y = y, x
1395 hi = x + y
1396 lo = y - (hi - x)
1397 if lo:
1398 partials[i] = lo
1399 i += 1
1400 x = hi
1401 partials[i:] = [x]
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001402 return sum_exact(partials)
1403
1404 Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
1405 are exactly equal to x+y. The inner loop applies hi/lo summation to each
1406 partial so that the list of partial sums remains exact.
1407
1408 Sum_exact() adds the partial sums exactly and correctly rounds the final
1409 result (using the round-half-to-even rule). The items in partials remain
1410 non-zero, non-special, non-overlapping and strictly increasing in
1411 magnitude, but possibly not all having the same sign.
1412
1413 Depends on IEEE 754 arithmetic guarantees and half-even rounding.
1414*/
1415
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001416/*[clinic input]
1417math.fsum
1418
1419 seq: object
1420 /
1421
1422Return an accurate floating point sum of values in the iterable seq.
1423
1424Assumes IEEE-754 floating point arithmetic.
1425[clinic start generated code]*/
1426
1427static PyObject *
1428math_fsum(PyObject *module, PyObject *seq)
1429/*[clinic end generated code: output=ba5c672b87fe34fc input=c51b7d8caf6f6e82]*/
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001430{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 PyObject *item, *iter, *sum = NULL;
1432 Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
1433 double x, y, t, ps[NUM_PARTIALS], *p = ps;
1434 double xsave, special_sum = 0.0, inf_sum = 0.0;
1435 volatile double hi, yr, lo;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 iter = PyObject_GetIter(seq);
1438 if (iter == NULL)
1439 return NULL;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 for(;;) { /* for x in iterable */
1442 assert(0 <= n && n <= m);
1443 assert((m == NUM_PARTIALS && p == ps) ||
1444 (m > NUM_PARTIALS && p != NULL));
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 item = PyIter_Next(iter);
1447 if (item == NULL) {
1448 if (PyErr_Occurred())
1449 goto _fsum_error;
1450 break;
1451 }
Raymond Hettingercfd735e2019-01-29 20:39:53 -08001452 ASSIGN_DOUBLE(x, item, error_with_item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 Py_DECREF(item);
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 xsave = x;
1456 for (i = j = 0; j < n; j++) { /* for y in partials */
1457 y = p[j];
1458 if (fabs(x) < fabs(y)) {
1459 t = x; x = y; y = t;
1460 }
1461 hi = x + y;
1462 yr = hi - x;
1463 lo = y - yr;
1464 if (lo != 0.0)
1465 p[i++] = lo;
1466 x = hi;
1467 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 n = i; /* ps[i:] = [x] */
1470 if (x != 0.0) {
1471 if (! Py_IS_FINITE(x)) {
1472 /* a nonfinite x could arise either as
1473 a result of intermediate overflow, or
1474 as a result of a nan or inf in the
1475 summands */
1476 if (Py_IS_FINITE(xsave)) {
1477 PyErr_SetString(PyExc_OverflowError,
1478 "intermediate overflow in fsum");
1479 goto _fsum_error;
1480 }
1481 if (Py_IS_INFINITY(xsave))
1482 inf_sum += xsave;
1483 special_sum += xsave;
1484 /* reset partials */
1485 n = 0;
1486 }
1487 else if (n >= m && _fsum_realloc(&p, n, ps, &m))
1488 goto _fsum_error;
1489 else
1490 p[n++] = x;
1491 }
1492 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 if (special_sum != 0.0) {
1495 if (Py_IS_NAN(inf_sum))
1496 PyErr_SetString(PyExc_ValueError,
1497 "-inf + inf in fsum");
1498 else
1499 sum = PyFloat_FromDouble(special_sum);
1500 goto _fsum_error;
1501 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 hi = 0.0;
1504 if (n > 0) {
1505 hi = p[--n];
1506 /* sum_exact(ps, hi) from the top, stop when the sum becomes
1507 inexact. */
1508 while (n > 0) {
1509 x = hi;
1510 y = p[--n];
1511 assert(fabs(y) < fabs(x));
1512 hi = x + y;
1513 yr = hi - x;
1514 lo = y - yr;
1515 if (lo != 0.0)
1516 break;
1517 }
1518 /* Make half-even rounding work across multiple partials.
1519 Needed so that sum([1e-16, 1, 1e16]) will round-up the last
1520 digit to two instead of down to zero (the 1e-16 makes the 1
1521 slightly closer to two). With a potential 1 ULP rounding
1522 error fixed-up, math.fsum() can guarantee commutativity. */
1523 if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
1524 (lo > 0.0 && p[n-1] > 0.0))) {
1525 y = lo * 2.0;
1526 x = hi + y;
1527 yr = x - hi;
1528 if (y == yr)
1529 hi = x;
1530 }
1531 }
1532 sum = PyFloat_FromDouble(hi);
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001533
Raymond Hettingercfd735e2019-01-29 20:39:53 -08001534 _fsum_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 Py_DECREF(iter);
1536 if (p != ps)
1537 PyMem_Free(p);
1538 return sum;
Raymond Hettingercfd735e2019-01-29 20:39:53 -08001539
1540 error_with_item:
1541 Py_DECREF(item);
1542 goto _fsum_error;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001543}
1544
1545#undef NUM_PARTIALS
1546
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001547
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001548static unsigned long
1549count_set_bits(unsigned long n)
1550{
1551 unsigned long count = 0;
1552 while (n != 0) {
1553 ++count;
1554 n &= n - 1; /* clear least significant bit */
1555 }
1556 return count;
1557}
1558
Mark Dickinson73934b92019-05-18 12:29:50 +01001559/* Integer square root
1560
1561Given a nonnegative integer `n`, we want to compute the largest integer
1562`a` for which `a * a <= n`, or equivalently the integer part of the exact
1563square root of `n`.
1564
1565We use an adaptive-precision pure-integer version of Newton's iteration. Given
1566a positive integer `n`, the algorithm produces at each iteration an integer
1567approximation `a` to the square root of `n >> s` for some even integer `s`,
1568with `s` decreasing as the iterations progress. On the final iteration, `s` is
1569zero and we have an approximation to the square root of `n` itself.
1570
1571At every step, the approximation `a` is strictly within 1.0 of the true square
1572root, so we have
1573
1574 (a - 1)**2 < (n >> s) < (a + 1)**2
1575
1576After the final iteration, a check-and-correct step is needed to determine
1577whether `a` or `a - 1` gives the desired integer square root of `n`.
1578
1579The algorithm is remarkable in its simplicity. There's no need for a
1580per-iteration check-and-correct step, and termination is straightforward: the
1581number of iterations is known in advance (it's exactly `floor(log2(log2(n)))`
1582for `n > 1`). The only tricky part of the correctness proof is in establishing
1583that the bound `(a - 1)**2 < (n >> s) < (a + 1)**2` is maintained from one
1584iteration to the next. A sketch of the proof of this is given below.
1585
1586In addition to the proof sketch, a formal, computer-verified proof
1587of correctness (using Lean) of an equivalent recursive algorithm can be found
1588here:
1589
1590 https://github.com/mdickinson/snippets/blob/master/proofs/isqrt/src/isqrt.lean
1591
1592
1593Here's Python code equivalent to the C implementation below:
1594
1595 def isqrt(n):
1596 """
1597 Return the integer part of the square root of the input.
1598 """
1599 n = operator.index(n)
1600
1601 if n < 0:
1602 raise ValueError("isqrt() argument must be nonnegative")
1603 if n == 0:
1604 return 0
1605
1606 c = (n.bit_length() - 1) // 2
1607 a = 1
1608 d = 0
1609 for s in reversed(range(c.bit_length())):
Mark Dickinson2dfeaa92019-06-16 17:53:21 +01001610 # Loop invariant: (a-1)**2 < (n >> 2*(c - d)) < (a+1)**2
Mark Dickinson73934b92019-05-18 12:29:50 +01001611 e = d
1612 d = c >> s
1613 a = (a << d - e - 1) + (n >> 2*c - e - d + 1) // a
Mark Dickinson73934b92019-05-18 12:29:50 +01001614
1615 return a - (a*a > n)
1616
1617
1618Sketch of proof of correctness
1619------------------------------
1620
1621The delicate part of the correctness proof is showing that the loop invariant
1622is preserved from one iteration to the next. That is, just before the line
1623
1624 a = (a << d - e - 1) + (n >> 2*c - e - d + 1) // a
1625
1626is executed in the above code, we know that
1627
1628 (1) (a - 1)**2 < (n >> 2*(c - e)) < (a + 1)**2.
1629
1630(since `e` is always the value of `d` from the previous iteration). We must
1631prove that after that line is executed, we have
1632
1633 (a - 1)**2 < (n >> 2*(c - d)) < (a + 1)**2
1634
Min ho Kimf7d72e42019-07-06 07:39:32 +10001635To facilitate the proof, we make some changes of notation. Write `m` for
Mark Dickinson73934b92019-05-18 12:29:50 +01001636`n >> 2*(c-d)`, and write `b` for the new value of `a`, so
1637
1638 b = (a << d - e - 1) + (n >> 2*c - e - d + 1) // a
1639
1640or equivalently:
1641
1642 (2) b = (a << d - e - 1) + (m >> d - e + 1) // a
1643
1644Then we can rewrite (1) as:
1645
1646 (3) (a - 1)**2 < (m >> 2*(d - e)) < (a + 1)**2
1647
1648and we must show that (b - 1)**2 < m < (b + 1)**2.
1649
1650From this point on, we switch to mathematical notation, so `/` means exact
1651division rather than integer division and `^` is used for exponentiation. We
1652use the `√` symbol for the exact square root. In (3), we can remove the
1653implicit floor operation to give:
1654
1655 (4) (a - 1)^2 < m / 4^(d - e) < (a + 1)^2
1656
1657Taking square roots throughout (4), scaling by `2^(d-e)`, and rearranging gives
1658
1659 (5) 0 <= | 2^(d-e)a - √m | < 2^(d-e)
1660
1661Squaring and dividing through by `2^(d-e+1) a` gives
1662
1663 (6) 0 <= 2^(d-e-1) a + m / (2^(d-e+1) a) - √m < 2^(d-e-1) / a
1664
1665We'll show below that `2^(d-e-1) <= a`. Given that, we can replace the
1666right-hand side of (6) with `1`, and now replacing the central
1667term `m / (2^(d-e+1) a)` with its floor in (6) gives
1668
1669 (7) -1 < 2^(d-e-1) a + m // 2^(d-e+1) a - √m < 1
1670
1671Or equivalently, from (2):
1672
1673 (7) -1 < b - √m < 1
1674
1675and rearranging gives that `(b-1)^2 < m < (b+1)^2`, which is what we needed
1676to prove.
1677
1678We're not quite done: we still have to prove the inequality `2^(d - e - 1) <=
1679a` that was used to get line (7) above. From the definition of `c`, we have
1680`4^c <= n`, which implies
1681
1682 (8) 4^d <= m
1683
1684also, since `e == d >> 1`, `d` is at most `2e + 1`, from which it follows
1685that `2d - 2e - 1 <= d` and hence that
1686
1687 (9) 4^(2d - 2e - 1) <= m
1688
1689Dividing both sides by `4^(d - e)` gives
1690
1691 (10) 4^(d - e - 1) <= m / 4^(d - e)
1692
1693But we know from (4) that `m / 4^(d-e) < (a + 1)^2`, hence
1694
1695 (11) 4^(d - e - 1) < (a + 1)^2
1696
1697Now taking square roots of both sides and observing that both `2^(d-e-1)` and
1698`a` are integers gives `2^(d - e - 1) <= a`, which is what we needed. This
1699completes the proof sketch.
1700
1701*/
1702
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001703
1704/* Approximate square root of a large 64-bit integer.
1705
1706 Given `n` satisfying `2**62 <= n < 2**64`, return `a`
1707 satisfying `(a - 1)**2 < n < (a + 1)**2`. */
1708
1709static uint64_t
1710_approximate_isqrt(uint64_t n)
1711{
1712 uint32_t u = 1U + (n >> 62);
1713 u = (u << 1) + (n >> 59) / u;
1714 u = (u << 3) + (n >> 53) / u;
1715 u = (u << 7) + (n >> 41) / u;
1716 return (u << 15) + (n >> 17) / u;
1717}
1718
Mark Dickinson73934b92019-05-18 12:29:50 +01001719/*[clinic input]
1720math.isqrt
1721
1722 n: object
1723 /
1724
1725Return the integer part of the square root of the input.
1726[clinic start generated code]*/
1727
1728static PyObject *
1729math_isqrt(PyObject *module, PyObject *n)
1730/*[clinic end generated code: output=35a6f7f980beab26 input=5b6e7ae4fa6c43d6]*/
1731{
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001732 int a_too_large, c_bit_length;
Mark Dickinson73934b92019-05-18 12:29:50 +01001733 size_t c, d;
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001734 uint64_t m, u;
Mark Dickinson73934b92019-05-18 12:29:50 +01001735 PyObject *a = NULL, *b;
1736
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001737 n = _PyNumber_Index(n);
Mark Dickinson73934b92019-05-18 12:29:50 +01001738 if (n == NULL) {
1739 return NULL;
1740 }
1741
1742 if (_PyLong_Sign(n) < 0) {
1743 PyErr_SetString(
1744 PyExc_ValueError,
1745 "isqrt() argument must be nonnegative");
1746 goto error;
1747 }
1748 if (_PyLong_Sign(n) == 0) {
1749 Py_DECREF(n);
1750 return PyLong_FromLong(0);
1751 }
1752
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001753 /* c = (n.bit_length() - 1) // 2 */
Mark Dickinson73934b92019-05-18 12:29:50 +01001754 c = _PyLong_NumBits(n);
1755 if (c == (size_t)(-1)) {
1756 goto error;
1757 }
1758 c = (c - 1U) / 2U;
1759
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001760 /* Fast path: if c <= 31 then n < 2**64 and we can compute directly with a
1761 fast, almost branch-free algorithm. In the final correction, we use `u*u
1762 - 1 >= m` instead of the simpler `u*u > m` in order to get the correct
1763 result in the corner case where `u=2**32`. */
1764 if (c <= 31U) {
1765 m = (uint64_t)PyLong_AsUnsignedLongLong(n);
1766 Py_DECREF(n);
1767 if (m == (uint64_t)(-1) && PyErr_Occurred()) {
1768 return NULL;
1769 }
1770 u = _approximate_isqrt(m << (62U - 2U*c)) >> (31U - c);
1771 u -= u * u - 1U >= m;
1772 return PyLong_FromUnsignedLongLong((unsigned long long)u);
Mark Dickinson73934b92019-05-18 12:29:50 +01001773 }
1774
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001775 /* Slow path: n >= 2**64. We perform the first five iterations in C integer
1776 arithmetic, then switch to using Python long integers. */
1777
1778 /* From n >= 2**64 it follows that c.bit_length() >= 6. */
1779 c_bit_length = 6;
1780 while ((c >> c_bit_length) > 0U) {
1781 ++c_bit_length;
1782 }
1783
1784 /* Initialise d and a. */
1785 d = c >> (c_bit_length - 5);
1786 b = _PyLong_Rshift(n, 2U*c - 62U);
1787 if (b == NULL) {
1788 goto error;
1789 }
1790 m = (uint64_t)PyLong_AsUnsignedLongLong(b);
1791 Py_DECREF(b);
1792 if (m == (uint64_t)(-1) && PyErr_Occurred()) {
1793 goto error;
1794 }
1795 u = _approximate_isqrt(m) >> (31U - d);
1796 a = PyLong_FromUnsignedLongLong((unsigned long long)u);
Mark Dickinson73934b92019-05-18 12:29:50 +01001797 if (a == NULL) {
1798 goto error;
1799 }
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001800
1801 for (int s = c_bit_length - 6; s >= 0; --s) {
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03001802 PyObject *q;
Mark Dickinson73934b92019-05-18 12:29:50 +01001803 size_t e = d;
1804
1805 d = c >> s;
1806
1807 /* q = (n >> 2*c - e - d + 1) // a */
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03001808 q = _PyLong_Rshift(n, 2U*c - d - e + 1U);
Mark Dickinson73934b92019-05-18 12:29:50 +01001809 if (q == NULL) {
1810 goto error;
1811 }
1812 Py_SETREF(q, PyNumber_FloorDivide(q, a));
1813 if (q == NULL) {
1814 goto error;
1815 }
1816
1817 /* a = (a << d - 1 - e) + q */
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03001818 Py_SETREF(a, _PyLong_Lshift(a, d - 1U - e));
Mark Dickinson73934b92019-05-18 12:29:50 +01001819 if (a == NULL) {
1820 Py_DECREF(q);
1821 goto error;
1822 }
1823 Py_SETREF(a, PyNumber_Add(a, q));
1824 Py_DECREF(q);
1825 if (a == NULL) {
1826 goto error;
1827 }
1828 }
1829
1830 /* The correct result is either a or a - 1. Figure out which, and
1831 decrement a if necessary. */
1832
1833 /* a_too_large = n < a * a */
1834 b = PyNumber_Multiply(a, a);
1835 if (b == NULL) {
1836 goto error;
1837 }
1838 a_too_large = PyObject_RichCompareBool(n, b, Py_LT);
1839 Py_DECREF(b);
1840 if (a_too_large == -1) {
1841 goto error;
1842 }
1843
1844 if (a_too_large) {
Victor Stinner37834132020-10-27 17:12:53 +01001845 Py_SETREF(a, PyNumber_Subtract(a, _PyLong_GetOne()));
Mark Dickinson73934b92019-05-18 12:29:50 +01001846 }
1847 Py_DECREF(n);
1848 return a;
1849
1850 error:
1851 Py_XDECREF(a);
1852 Py_DECREF(n);
1853 return NULL;
1854}
1855
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001856/* Divide-and-conquer factorial algorithm
1857 *
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07001858 * Based on the formula and pseudo-code provided at:
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001859 * http://www.luschny.de/math/factorial/binarysplitfact.html
1860 *
1861 * Faster algorithms exist, but they're more complicated and depend on
Ezio Melotti9527afd2010-07-08 15:03:02 +00001862 * a fast prime factorization algorithm.
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001863 *
1864 * Notes on the algorithm
1865 * ----------------------
1866 *
1867 * factorial(n) is written in the form 2**k * m, with m odd. k and m are
1868 * computed separately, and then combined using a left shift.
1869 *
1870 * The function factorial_odd_part computes the odd part m (i.e., the greatest
1871 * odd divisor) of factorial(n), using the formula:
1872 *
1873 * factorial_odd_part(n) =
1874 *
1875 * product_{i >= 0} product_{0 < j <= n / 2**i, j odd} j
1876 *
1877 * Example: factorial_odd_part(20) =
1878 *
1879 * (1) *
1880 * (1) *
1881 * (1 * 3 * 5) *
Alperen Serkan Aksöz09605ad2021-03-03 16:59:52 +03001882 * (1 * 3 * 5 * 7 * 9) *
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001883 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1884 *
1885 * Here i goes from large to small: the first term corresponds to i=4 (any
1886 * larger i gives an empty product), and the last term corresponds to i=0.
1887 * Each term can be computed from the last by multiplying by the extra odd
1888 * numbers required: e.g., to get from the penultimate term to the last one,
1889 * we multiply by (11 * 13 * 15 * 17 * 19).
1890 *
1891 * To see a hint of why this formula works, here are the same numbers as above
1892 * but with the even parts (i.e., the appropriate powers of 2) included. For
1893 * each subterm in the product for i, we multiply that subterm by 2**i:
1894 *
1895 * factorial(20) =
1896 *
1897 * (16) *
1898 * (8) *
1899 * (4 * 12 * 20) *
1900 * (2 * 6 * 10 * 14 * 18) *
1901 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1902 *
1903 * The factorial_partial_product function computes the product of all odd j in
1904 * range(start, stop) for given start and stop. It's used to compute the
1905 * partial products like (11 * 13 * 15 * 17 * 19) in the example above. It
1906 * operates recursively, repeatedly splitting the range into two roughly equal
1907 * pieces until the subranges are small enough to be computed using only C
1908 * integer arithmetic.
1909 *
1910 * The two-valuation k (i.e., the exponent of the largest power of 2 dividing
1911 * the factorial) is computed independently in the main math_factorial
1912 * function. By standard results, its value is:
1913 *
1914 * two_valuation = n//2 + n//4 + n//8 + ....
1915 *
1916 * It can be shown (e.g., by complete induction on n) that two_valuation is
1917 * equal to n - count_set_bits(n), where count_set_bits(n) gives the number of
1918 * '1'-bits in the binary expansion of n.
1919 */
1920
1921/* factorial_partial_product: Compute product(range(start, stop, 2)) using
1922 * divide and conquer. Assumes start and stop are odd and stop > start.
1923 * max_bits must be >= bit_length(stop - 2). */
1924
1925static PyObject *
1926factorial_partial_product(unsigned long start, unsigned long stop,
1927 unsigned long max_bits)
1928{
1929 unsigned long midpoint, num_operands;
1930 PyObject *left = NULL, *right = NULL, *result = NULL;
1931
1932 /* If the return value will fit an unsigned long, then we can
1933 * multiply in a tight, fast loop where each multiply is O(1).
1934 * Compute an upper bound on the number of bits required to store
1935 * the answer.
1936 *
1937 * Storing some integer z requires floor(lg(z))+1 bits, which is
1938 * conveniently the value returned by bit_length(z). The
1939 * product x*y will require at most
1940 * bit_length(x) + bit_length(y) bits to store, based
1941 * on the idea that lg product = lg x + lg y.
1942 *
1943 * We know that stop - 2 is the largest number to be multiplied. From
1944 * there, we have: bit_length(answer) <= num_operands *
1945 * bit_length(stop - 2)
1946 */
1947
1948 num_operands = (stop - start) / 2;
1949 /* The "num_operands <= 8 * SIZEOF_LONG" check guards against the
1950 * unlikely case of an overflow in num_operands * max_bits. */
1951 if (num_operands <= 8 * SIZEOF_LONG &&
1952 num_operands * max_bits <= 8 * SIZEOF_LONG) {
1953 unsigned long j, total;
1954 for (total = start, j = start + 2; j < stop; j += 2)
1955 total *= j;
1956 return PyLong_FromUnsignedLong(total);
1957 }
1958
1959 /* find midpoint of range(start, stop), rounded up to next odd number. */
1960 midpoint = (start + num_operands) | 1;
1961 left = factorial_partial_product(start, midpoint,
Niklas Fiekasc5b79002020-01-16 15:09:19 +01001962 _Py_bit_length(midpoint - 2));
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001963 if (left == NULL)
1964 goto error;
1965 right = factorial_partial_product(midpoint, stop, max_bits);
1966 if (right == NULL)
1967 goto error;
1968 result = PyNumber_Multiply(left, right);
1969
1970 error:
1971 Py_XDECREF(left);
1972 Py_XDECREF(right);
1973 return result;
1974}
1975
1976/* factorial_odd_part: compute the odd part of factorial(n). */
1977
1978static PyObject *
1979factorial_odd_part(unsigned long n)
1980{
1981 long i;
1982 unsigned long v, lower, upper;
1983 PyObject *partial, *tmp, *inner, *outer;
1984
1985 inner = PyLong_FromLong(1);
1986 if (inner == NULL)
1987 return NULL;
1988 outer = inner;
1989 Py_INCREF(outer);
1990
1991 upper = 3;
Niklas Fiekasc5b79002020-01-16 15:09:19 +01001992 for (i = _Py_bit_length(n) - 2; i >= 0; i--) {
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001993 v = n >> i;
1994 if (v <= 2)
1995 continue;
1996 lower = upper;
1997 /* (v + 1) | 1 = least odd integer strictly larger than n / 2**i */
1998 upper = (v + 1) | 1;
1999 /* Here inner is the product of all odd integers j in the range (0,
2000 n/2**(i+1)]. The factorial_partial_product call below gives the
2001 product of all odd integers j in the range (n/2**(i+1), n/2**i]. */
Niklas Fiekasc5b79002020-01-16 15:09:19 +01002002 partial = factorial_partial_product(lower, upper, _Py_bit_length(upper-2));
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002003 /* inner *= partial */
2004 if (partial == NULL)
2005 goto error;
2006 tmp = PyNumber_Multiply(inner, partial);
2007 Py_DECREF(partial);
2008 if (tmp == NULL)
2009 goto error;
2010 Py_DECREF(inner);
2011 inner = tmp;
2012 /* Now inner is the product of all odd integers j in the range (0,
2013 n/2**i], giving the inner product in the formula above. */
2014
2015 /* outer *= inner; */
2016 tmp = PyNumber_Multiply(outer, inner);
2017 if (tmp == NULL)
2018 goto error;
2019 Py_DECREF(outer);
2020 outer = tmp;
2021 }
Mark Dickinson76464492012-10-25 10:46:28 +01002022 Py_DECREF(inner);
2023 return outer;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002024
2025 error:
2026 Py_DECREF(outer);
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002027 Py_DECREF(inner);
Mark Dickinson76464492012-10-25 10:46:28 +01002028 return NULL;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002029}
2030
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002031
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002032/* Lookup table for small factorial values */
2033
2034static const unsigned long SmallFactorials[] = {
2035 1, 1, 2, 6, 24, 120, 720, 5040, 40320,
2036 362880, 3628800, 39916800, 479001600,
2037#if SIZEOF_LONG >= 8
2038 6227020800, 87178291200, 1307674368000,
2039 20922789888000, 355687428096000, 6402373705728000,
2040 121645100408832000, 2432902008176640000
2041#endif
2042};
2043
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002044/*[clinic input]
2045math.factorial
2046
2047 x as arg: object
2048 /
2049
2050Find x!.
2051
2052Raise a ValueError if x is negative or non-integral.
2053[clinic start generated code]*/
2054
Barry Warsaw8b43b191996-12-09 22:32:36 +00002055static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002056math_factorial(PyObject *module, PyObject *arg)
2057/*[clinic end generated code: output=6686f26fae00e9ca input=6d1c8105c0d91fb4]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002058{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03002059 long x, two_valuation;
Mark Dickinson5990d282014-04-10 09:29:39 -04002060 int overflow;
Serhiy Storchaka578c3952020-05-26 18:43:38 +03002061 PyObject *result, *odd_part;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002062
Serhiy Storchaka578c3952020-05-26 18:43:38 +03002063 x = PyLong_AsLongAndOverflow(arg, &overflow);
Mark Dickinson5990d282014-04-10 09:29:39 -04002064 if (x == -1 && PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 return NULL;
Mark Dickinson5990d282014-04-10 09:29:39 -04002066 }
2067 else if (overflow == 1) {
2068 PyErr_Format(PyExc_OverflowError,
2069 "factorial() argument should not exceed %ld",
2070 LONG_MAX);
2071 return NULL;
2072 }
2073 else if (overflow == -1 || x < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002075 "factorial() not defined for negative values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 return NULL;
2077 }
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002078
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002079 /* use lookup table if x is small */
Victor Stinner63941882011-09-29 00:42:28 +02002080 if (x < (long)Py_ARRAY_LENGTH(SmallFactorials))
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002081 return PyLong_FromUnsignedLong(SmallFactorials[x]);
2082
2083 /* else express in the form odd_part * 2**two_valuation, and compute as
2084 odd_part << two_valuation. */
2085 odd_part = factorial_odd_part(x);
2086 if (odd_part == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03002088 two_valuation = x - count_set_bits(x);
2089 result = _PyLong_Lshift(odd_part, two_valuation);
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002090 Py_DECREF(odd_part);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 return result;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002092}
2093
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002094
2095/*[clinic input]
2096math.trunc
2097
2098 x: object
2099 /
2100
2101Truncates the Real x to the nearest Integral toward 0.
2102
2103Uses the __trunc__ magic method.
2104[clinic start generated code]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002105
2106static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002107math_trunc(PyObject *module, PyObject *x)
2108/*[clinic end generated code: output=34b9697b707e1031 input=2168b34e0a09134d]*/
Christian Heimes400adb02008-02-01 08:12:03 +00002109{
Benjamin Petersonce798522012-01-22 11:24:29 -05002110 _Py_IDENTIFIER(__trunc__);
Benjamin Petersonb0125892010-07-02 13:35:17 +00002111 PyObject *trunc, *result;
Christian Heimes400adb02008-02-01 08:12:03 +00002112
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02002113 if (PyFloat_CheckExact(x)) {
2114 return PyFloat_Type.tp_as_number->nb_int(x);
2115 }
2116
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002117 if (Py_TYPE(x)->tp_dict == NULL) {
2118 if (PyType_Ready(Py_TYPE(x)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 return NULL;
2120 }
Christian Heimes400adb02008-02-01 08:12:03 +00002121
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002122 trunc = _PyObject_LookupSpecial(x, &PyId___trunc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 if (trunc == NULL) {
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00002124 if (!PyErr_Occurred())
2125 PyErr_Format(PyExc_TypeError,
2126 "type %.100s doesn't define __trunc__ method",
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002127 Py_TYPE(x)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 return NULL;
2129 }
Victor Stinnerf17c3de2016-12-06 18:46:19 +01002130 result = _PyObject_CallNoArg(trunc);
Benjamin Petersonb0125892010-07-02 13:35:17 +00002131 Py_DECREF(trunc);
2132 return result;
Christian Heimes400adb02008-02-01 08:12:03 +00002133}
2134
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002135
2136/*[clinic input]
2137math.frexp
2138
2139 x: double
2140 /
2141
2142Return the mantissa and exponent of x, as pair (m, e).
2143
2144m is a float and e is an int, such that x = m * 2.**e.
2145If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.
2146[clinic start generated code]*/
Christian Heimes400adb02008-02-01 08:12:03 +00002147
2148static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002149math_frexp_impl(PyObject *module, double x)
2150/*[clinic end generated code: output=03e30d252a15ad4a input=96251c9e208bc6e9]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00002151{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 /* deal with special cases directly, to sidestep platform
2154 differences */
2155 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
2156 i = 0;
2157 }
2158 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 x = frexp(x, &i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 }
2161 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +00002162}
2163
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002164
2165/*[clinic input]
2166math.ldexp
2167
2168 x: double
2169 i: object
2170 /
2171
2172Return x * (2**i).
2173
2174This is essentially the inverse of frexp().
2175[clinic start generated code]*/
Guido van Rossumc6e22901998-12-04 19:26:43 +00002176
Barry Warsaw8b43b191996-12-09 22:32:36 +00002177static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002178math_ldexp_impl(PyObject *module, double x, PyObject *i)
2179/*[clinic end generated code: output=b6892f3c2df9cc6a input=17d5970c1a40a8c1]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00002180{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002181 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 long exp;
2183 int overflow;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00002184
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002185 if (PyLong_Check(i)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 /* on overflow, replace exponent with either LONG_MAX
2187 or LONG_MIN, depending on the sign. */
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002188 exp = PyLong_AsLongAndOverflow(i, &overflow);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 if (exp == -1 && PyErr_Occurred())
2190 return NULL;
2191 if (overflow)
2192 exp = overflow < 0 ? LONG_MIN : LONG_MAX;
2193 }
2194 else {
2195 PyErr_SetString(PyExc_TypeError,
Serhiy Storchaka95949422013-08-27 19:40:23 +03002196 "Expected an int as second argument to ldexp.");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 return NULL;
2198 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00002199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 if (x == 0. || !Py_IS_FINITE(x)) {
2201 /* NaNs, zeros and infinities are returned unchanged */
2202 r = x;
2203 errno = 0;
2204 } else if (exp > INT_MAX) {
2205 /* overflow */
2206 r = copysign(Py_HUGE_VAL, x);
2207 errno = ERANGE;
2208 } else if (exp < INT_MIN) {
2209 /* underflow to +-0 */
2210 r = copysign(0., x);
2211 errno = 0;
2212 } else {
2213 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 r = ldexp(x, (int)exp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 if (Py_IS_INFINITY(r))
2216 errno = ERANGE;
2217 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00002218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 if (errno && is_error(r))
2220 return NULL;
2221 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +00002222}
2223
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002224
2225/*[clinic input]
2226math.modf
2227
2228 x: double
2229 /
2230
2231Return the fractional and integer parts of x.
2232
2233Both results carry the sign of x and are floats.
2234[clinic start generated code]*/
Guido van Rossumc6e22901998-12-04 19:26:43 +00002235
Barry Warsaw8b43b191996-12-09 22:32:36 +00002236static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002237math_modf_impl(PyObject *module, double x)
2238/*[clinic end generated code: output=90cee0260014c3c0 input=b4cfb6786afd9035]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00002239{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002240 double y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 /* some platforms don't do the right thing for NaNs and
2242 infinities, so we take care of special cases directly. */
2243 if (!Py_IS_FINITE(x)) {
2244 if (Py_IS_INFINITY(x))
2245 return Py_BuildValue("(dd)", copysign(0., x), x);
2246 else if (Py_IS_NAN(x))
2247 return Py_BuildValue("(dd)", x, x);
2248 }
Christian Heimesa342c012008-04-20 21:01:16 +00002249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 x = modf(x, &y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +00002253}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002254
Guido van Rossumc6e22901998-12-04 19:26:43 +00002255
Serhiy Storchaka95949422013-08-27 19:40:23 +03002256/* A decent logarithm is easy to compute even for huge ints, but libm can't
Tim Peters78526162001-09-05 00:53:45 +00002257 do that by itself -- loghelper can. func is log or log10, and name is
Serhiy Storchaka95949422013-08-27 19:40:23 +03002258 "log" or "log10". Note that overflow of the result isn't possible: an int
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002259 can contain no more than INT_MAX * SHIFT bits, so has value certainly less
2260 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 +00002261 small enough to fit in an IEEE single. log and log10 are even smaller.
Serhiy Storchaka95949422013-08-27 19:40:23 +03002262 However, intermediate overflow is possible for an int if the number of bits
2263 in that int is larger than PY_SSIZE_T_MAX. */
Tim Peters78526162001-09-05 00:53:45 +00002264
2265static PyObject*
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002266loghelper(PyObject* arg, double (*func)(double), const char *funcname)
Tim Peters78526162001-09-05 00:53:45 +00002267{
Serhiy Storchaka95949422013-08-27 19:40:23 +03002268 /* If it is int, do it ourselves. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 if (PyLong_Check(arg)) {
Mark Dickinsonc6037172010-09-29 19:06:36 +00002270 double x, result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 Py_ssize_t e;
Mark Dickinsonc6037172010-09-29 19:06:36 +00002272
2273 /* Negative or zero inputs give a ValueError. */
2274 if (Py_SIZE(arg) <= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 PyErr_SetString(PyExc_ValueError,
2276 "math domain error");
2277 return NULL;
2278 }
Mark Dickinsonfa41e602010-09-28 07:22:27 +00002279
Mark Dickinsonc6037172010-09-29 19:06:36 +00002280 x = PyLong_AsDouble(arg);
2281 if (x == -1.0 && PyErr_Occurred()) {
2282 if (!PyErr_ExceptionMatches(PyExc_OverflowError))
2283 return NULL;
2284 /* Here the conversion to double overflowed, but it's possible
2285 to compute the log anyway. Clear the exception and continue. */
2286 PyErr_Clear();
2287 x = _PyLong_Frexp((PyLongObject *)arg, &e);
2288 if (x == -1.0 && PyErr_Occurred())
2289 return NULL;
2290 /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */
2291 result = func(x) + func(2.0) * e;
2292 }
2293 else
2294 /* Successfully converted x to a double. */
2295 result = func(x);
2296 return PyFloat_FromDouble(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 }
Tim Peters78526162001-09-05 00:53:45 +00002298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 /* Else let libm handle it by itself. */
2300 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +00002301}
2302
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002303
2304/*[clinic input]
2305math.log
2306
2307 x: object
2308 [
2309 base: object(c_default="NULL") = math.e
2310 ]
2311 /
2312
2313Return the logarithm of x to the given base.
2314
2315If the base not specified, returns the natural logarithm (base e) of x.
2316[clinic start generated code]*/
2317
Tim Peters78526162001-09-05 00:53:45 +00002318static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002319math_log_impl(PyObject *module, PyObject *x, int group_right_1,
2320 PyObject *base)
2321/*[clinic end generated code: output=7b5a39e526b73fc9 input=0f62d5726cbfebbd]*/
Tim Peters78526162001-09-05 00:53:45 +00002322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 PyObject *num, *den;
2324 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +00002325
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002326 num = loghelper(x, m_log, "log");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 if (num == NULL || base == NULL)
2328 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +00002329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 den = loghelper(base, m_log, "log");
2331 if (den == NULL) {
2332 Py_DECREF(num);
2333 return NULL;
2334 }
Raymond Hettinger866964c2002-12-14 19:51:34 +00002335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 ans = PyNumber_TrueDivide(num, den);
2337 Py_DECREF(num);
2338 Py_DECREF(den);
2339 return ans;
Tim Peters78526162001-09-05 00:53:45 +00002340}
2341
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002342
2343/*[clinic input]
2344math.log2
2345
2346 x: object
2347 /
2348
2349Return the base 2 logarithm of x.
2350[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002351
2352static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002353math_log2(PyObject *module, PyObject *x)
2354/*[clinic end generated code: output=5425899a4d5d6acb input=08321262bae4f39b]*/
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02002355{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002356 return loghelper(x, m_log2, "log2");
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02002357}
2358
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002359
2360/*[clinic input]
2361math.log10
2362
2363 x: object
2364 /
2365
2366Return the base 10 logarithm of x.
2367[clinic start generated code]*/
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02002368
2369static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002370math_log10(PyObject *module, PyObject *x)
2371/*[clinic end generated code: output=be72a64617df9c6f input=b2469d02c6469e53]*/
Tim Peters78526162001-09-05 00:53:45 +00002372{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002373 return loghelper(x, m_log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +00002374}
2375
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002376
2377/*[clinic input]
2378math.fmod
2379
2380 x: double
2381 y: double
2382 /
2383
2384Return fmod(x, y), according to platform C.
2385
2386x % y may differ.
2387[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002388
Christian Heimes53876d92008-04-19 00:31:39 +00002389static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002390math_fmod_impl(PyObject *module, double x, double y)
2391/*[clinic end generated code: output=7559d794343a27b5 input=4f84caa8cfc26a03]*/
Christian Heimes53876d92008-04-19 00:31:39 +00002392{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002393 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 /* fmod(x, +/-Inf) returns x for finite x. */
2395 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
2396 return PyFloat_FromDouble(x);
2397 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 r = fmod(x, y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 if (Py_IS_NAN(r)) {
2400 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
2401 errno = EDOM;
2402 else
2403 errno = 0;
2404 }
2405 if (errno && is_error(r))
2406 return NULL;
2407 else
2408 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00002409}
2410
Raymond Hettinger13990742018-08-11 11:26:36 -07002411/*
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002412Given a *vec* of values, compute the vector norm:
Raymond Hettinger13990742018-08-11 11:26:36 -07002413
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002414 sqrt(sum(x ** 2 for x in vec))
Raymond Hettingerfff3c282020-08-15 19:38:19 -07002415
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002416The *max* variable should be equal to the largest fabs(x).
2417The *n* variable is the length of *vec*.
2418If n==0, then *max* should be 0.0.
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002419If an infinity is present in the vec, *max* should be INF.
Raymond Hettingerc630e102018-08-11 18:39:05 -07002420The *found_nan* variable indicates whether some member of
2421the *vec* is a NaN.
Raymond Hettinger21786f52018-08-28 22:47:24 -07002422
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002423To avoid overflow/underflow and to achieve high accuracy giving results
2424that are almost always correctly rounded, four techniques are used:
Raymond Hettinger21786f52018-08-28 22:47:24 -07002425
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002426* lossless scaling using a power-of-two scaling factor
Raymond Hettinger67c998d2020-09-06 15:10:07 -07002427* accurate squaring using Veltkamp-Dekker splitting [1]
2428* compensated summation using a variant of the Neumaier algorithm [2]
2429* differential correction of the square root [3]
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002430
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002431The usual presentation of the Neumaier summation algorithm has an
2432expensive branch depending on which operand has the larger
2433magnitude. We avoid this cost by arranging the calculation so that
2434fabs(csum) is always as large as fabs(x).
Raymond Hettinger21786f52018-08-28 22:47:24 -07002435
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002436To establish the invariant, *csum* is initialized to 1.0 which is
Raymond Hettinger457d4e92020-09-13 23:33:41 -07002437always larger than x**2 after scaling or after division by *max*.
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002438After the loop is finished, the initial 1.0 is subtracted out for a
2439net zero effect on the final sum. Since *csum* will be greater than
24401.0, the subtraction of 1.0 will not cause fractional digits to be
2441dropped from *csum*.
2442
2443To get the full benefit from compensated summation, the largest
2444addend should be in the range: 0.5 <= |x| <= 1.0. Accordingly,
2445scaling or division by *max* should not be skipped even if not
2446otherwise needed to prevent overflow or loss of precision.
2447
Raymond Hettinger82e79482020-08-26 13:09:40 -07002448The assertion that hi*hi <= 1.0 is a bit subtle. Each vector element
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002449gets scaled to a magnitude below 1.0. The Veltkamp-Dekker splitting
2450algorithm gives a *hi* value that is correctly rounded to half
2451precision. When a value at or below 1.0 is correctly rounded, it
2452never goes above 1.0. And when values at or below 1.0 are squared,
2453they remain at or below 1.0, thus preserving the summation invariant.
2454
Raymond Hettinger27de2862020-08-29 09:11:04 -07002455Another interesting assertion is that csum+lo*lo == csum. In the loop,
2456each scaled vector element has a magnitude less than 1.0. After the
2457Veltkamp split, *lo* has a maximum value of 2**-27. So the maximum
2458value of *lo* squared is 2**-54. The value of ulp(1.0)/2.0 is 2**-53.
2459Given that csum >= 1.0, we have:
2460 lo**2 <= 2**-54 < 2**-53 == 1/2*ulp(1.0) <= ulp(csum)/2
2461Since lo**2 is less than 1/2 ulp(csum), we have csum+lo*lo == csum.
2462
Raymond Hettinger92c38162020-08-30 10:00:11 -07002463To minimize loss of information during the accumulation of fractional
Raymond Hettinger67c998d2020-09-06 15:10:07 -07002464values, each term has a separate accumulator. This also breaks up
2465sequential dependencies in the inner loop so the CPU can maximize
Raymond Hettinger457d4e92020-09-13 23:33:41 -07002466floating point throughput. [4] On a 2.6 GHz Haswell, adding one
Raymond Hettinger67c998d2020-09-06 15:10:07 -07002467dimension has an incremental cost of only 5ns -- for example when
2468moving from hypot(x,y) to hypot(x,y,z).
Raymond Hettinger92c38162020-08-30 10:00:11 -07002469
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002470The square root differential correction is needed because a
2471correctly rounded square root of a correctly rounded sum of
2472squares can still be off by as much as one ulp.
2473
2474The differential correction starts with a value *x* that is
2475the difference between the square of *h*, the possibly inaccurately
2476rounded square root, and the accurately computed sum of squares.
2477The correction is the first order term of the Maclaurin series
Raymond Hettinger457d4e92020-09-13 23:33:41 -07002478expansion of sqrt(h**2 + x) == h + x/(2*h) + O(x**2). [5]
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002479
2480Essentially, this differential correction is equivalent to one
Raymond Hettinger82e79482020-08-26 13:09:40 -07002481refinement step in Newton's divide-and-average square root
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002482algorithm, effectively doubling the number of accurate bits.
2483This technique is used in Dekker's SQRT2 algorithm and again in
2484Borges' ALGORITHM 4 and 5.
2485
Raymond Hettinger67c998d2020-09-06 15:10:07 -07002486Without proof for all cases, hypot() cannot claim to be always
2487correctly rounded. However for n <= 1000, prior to the final addition
2488that rounds the overall result, the internal accuracy of "h" together
2489with its correction of "x / (2.0 * h)" is at least 100 bits. [6]
2490Also, hypot() was tested against a Decimal implementation with
2491prec=300. After 100 million trials, no incorrectly rounded examples
2492were found. In addition, perfect commutativity (all permutations are
2493exactly equal) was verified for 1 billion random inputs with n=5. [7]
2494
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002495References:
2496
24971. Veltkamp-Dekker splitting: http://csclub.uwaterloo.ca/~pbarfuss/dekker1971.pdf
24982. Compensated summation: http://www.ti3.tu-harburg.de/paper/rump/Ru08b.pdf
Raymond Hettinger92c38162020-08-30 10:00:11 -070024993. Square root differential correction: https://arxiv.org/pdf/1904.09481.pdf
Raymond Hettinger457d4e92020-09-13 23:33:41 -070025004. Data dependency graph: https://bugs.python.org/file49439/hypot.png
25015. https://www.wolframalpha.com/input/?i=Maclaurin+series+sqrt%28h**2+%2B+x%29+at+x%3D0
Raymond Hettinger497126f2020-10-01 19:30:54 -070025026. Analysis of internal accuracy: https://bugs.python.org/file49484/best_frac.py
Raymond Hettinger457d4e92020-09-13 23:33:41 -070025037. Commutativity test: https://bugs.python.org/file49448/test_hypot_commutativity.py
Raymond Hettingerfff3c282020-08-15 19:38:19 -07002504
Raymond Hettinger13990742018-08-11 11:26:36 -07002505*/
2506
2507static inline double
Raymond Hettingerc630e102018-08-11 18:39:05 -07002508vector_norm(Py_ssize_t n, double *vec, double max, int found_nan)
Raymond Hettinger13990742018-08-11 11:26:36 -07002509{
Raymond Hettinger438e9fc2020-09-22 20:01:12 -07002510 const double T27 = 134217729.0; /* ldexp(1.0, 27) + 1.0) */
2511 double x, scale, oldcsum, csum = 1.0, frac1 = 0.0, frac2 = 0.0, frac3 = 0.0;
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002512 double t, hi, lo, h;
Raymond Hettingerfff3c282020-08-15 19:38:19 -07002513 int max_e;
Raymond Hettinger13990742018-08-11 11:26:36 -07002514 Py_ssize_t i;
2515
Raymond Hettingerc630e102018-08-11 18:39:05 -07002516 if (Py_IS_INFINITY(max)) {
2517 return max;
2518 }
2519 if (found_nan) {
2520 return Py_NAN;
2521 }
Raymond Hettingerf3267142018-09-02 13:34:21 -07002522 if (max == 0.0 || n <= 1) {
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002523 return max;
Raymond Hettinger13990742018-08-11 11:26:36 -07002524 }
Raymond Hettingerfff3c282020-08-15 19:38:19 -07002525 frexp(max, &max_e);
2526 if (max_e >= -1023) {
2527 scale = ldexp(1.0, -max_e);
2528 assert(max * scale >= 0.5);
2529 assert(max * scale < 1.0);
2530 for (i=0 ; i < n ; i++) {
2531 x = vec[i];
2532 assert(Py_IS_FINITE(x) && fabs(x) <= max);
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002533
Raymond Hettingerfff3c282020-08-15 19:38:19 -07002534 x *= scale;
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002535 assert(fabs(x) < 1.0);
2536
2537 t = x * T27;
2538 hi = t - (t - x);
2539 lo = x - hi;
2540 assert(hi + lo == x);
2541
2542 x = hi * hi;
Raymond Hettingerfff3c282020-08-15 19:38:19 -07002543 assert(x <= 1.0);
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002544 assert(fabs(csum) >= fabs(x));
2545 oldcsum = csum;
2546 csum += x;
Raymond Hettinger438e9fc2020-09-22 20:01:12 -07002547 frac1 += (oldcsum - csum) + x;
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002548
2549 x = 2.0 * hi * lo;
2550 assert(fabs(csum) >= fabs(x));
2551 oldcsum = csum;
2552 csum += x;
Raymond Hettinger438e9fc2020-09-22 20:01:12 -07002553 frac2 += (oldcsum - csum) + x;
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002554
Raymond Hettinger27de2862020-08-29 09:11:04 -07002555 assert(csum + lo * lo == csum);
Raymond Hettinger438e9fc2020-09-22 20:01:12 -07002556 frac3 += lo * lo;
Raymond Hettingerfff3c282020-08-15 19:38:19 -07002557 }
Raymond Hettinger438e9fc2020-09-22 20:01:12 -07002558 h = sqrt(csum - 1.0 + (frac1 + frac2 + frac3));
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002559
2560 x = h;
2561 t = x * T27;
2562 hi = t - (t - x);
2563 lo = x - hi;
2564 assert (hi + lo == x);
2565
2566 x = -hi * hi;
2567 assert(fabs(csum) >= fabs(x));
2568 oldcsum = csum;
2569 csum += x;
Raymond Hettinger438e9fc2020-09-22 20:01:12 -07002570 frac1 += (oldcsum - csum) + x;
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002571
2572 x = -2.0 * hi * lo;
2573 assert(fabs(csum) >= fabs(x));
2574 oldcsum = csum;
2575 csum += x;
Raymond Hettinger438e9fc2020-09-22 20:01:12 -07002576 frac2 += (oldcsum - csum) + x;
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002577
2578 x = -lo * lo;
2579 assert(fabs(csum) >= fabs(x));
2580 oldcsum = csum;
2581 csum += x;
Raymond Hettinger438e9fc2020-09-22 20:01:12 -07002582 frac3 += (oldcsum - csum) + x;
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002583
Raymond Hettinger438e9fc2020-09-22 20:01:12 -07002584 x = csum - 1.0 + (frac1 + frac2 + frac3);
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002585 return (h + x / (2.0 * h)) / scale;
Raymond Hettingerfff3c282020-08-15 19:38:19 -07002586 }
2587 /* When max_e < -1023, ldexp(1.0, -max_e) overflows.
2588 So instead of multiplying by a scale, we just divide by *max*.
2589 */
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002590 for (i=0 ; i < n ; i++) {
Raymond Hettinger13990742018-08-11 11:26:36 -07002591 x = vec[i];
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002592 assert(Py_IS_FINITE(x) && fabs(x) <= max);
Raymond Hettinger13990742018-08-11 11:26:36 -07002593 x /= max;
Raymond Hettinger21786f52018-08-28 22:47:24 -07002594 x = x*x;
Raymond Hettingerfff3c282020-08-15 19:38:19 -07002595 assert(x <= 1.0);
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002596 assert(fabs(csum) >= fabs(x));
Raymond Hettinger13990742018-08-11 11:26:36 -07002597 oldcsum = csum;
2598 csum += x;
Raymond Hettinger438e9fc2020-09-22 20:01:12 -07002599 frac1 += (oldcsum - csum) + x;
Raymond Hettinger13990742018-08-11 11:26:36 -07002600 }
Raymond Hettinger438e9fc2020-09-22 20:01:12 -07002601 return max * sqrt(csum - 1.0 + frac1);
Raymond Hettinger13990742018-08-11 11:26:36 -07002602}
2603
Raymond Hettingerc630e102018-08-11 18:39:05 -07002604#define NUM_STACK_ELEMS 16
2605
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002606/*[clinic input]
2607math.dist
2608
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002609 p: object
2610 q: object
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002611 /
2612
2613Return the Euclidean distance between two points p and q.
2614
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002615The points should be specified as sequences (or iterables) of
2616coordinates. Both inputs must have the same dimension.
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002617
2618Roughly equivalent to:
2619 sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
2620[clinic start generated code]*/
2621
2622static PyObject *
2623math_dist_impl(PyObject *module, PyObject *p, PyObject *q)
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002624/*[clinic end generated code: output=56bd9538d06bbcfe input=74e85e1b6092e68e]*/
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002625{
2626 PyObject *item;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002627 double max = 0.0;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002628 double x, px, qx, result;
2629 Py_ssize_t i, m, n;
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002630 int found_nan = 0, p_allocated = 0, q_allocated = 0;
Raymond Hettingerc630e102018-08-11 18:39:05 -07002631 double diffs_on_stack[NUM_STACK_ELEMS];
2632 double *diffs = diffs_on_stack;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002633
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002634 if (!PyTuple_Check(p)) {
2635 p = PySequence_Tuple(p);
2636 if (p == NULL) {
2637 return NULL;
2638 }
2639 p_allocated = 1;
2640 }
2641 if (!PyTuple_Check(q)) {
2642 q = PySequence_Tuple(q);
2643 if (q == NULL) {
2644 if (p_allocated) {
2645 Py_DECREF(p);
2646 }
2647 return NULL;
2648 }
2649 q_allocated = 1;
2650 }
2651
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002652 m = PyTuple_GET_SIZE(p);
2653 n = PyTuple_GET_SIZE(q);
2654 if (m != n) {
2655 PyErr_SetString(PyExc_ValueError,
2656 "both points must have the same number of dimensions");
2657 return NULL;
2658
2659 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002660 if (n > NUM_STACK_ELEMS) {
2661 diffs = (double *) PyObject_Malloc(n * sizeof(double));
2662 if (diffs == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07002663 return PyErr_NoMemory();
Raymond Hettingerc630e102018-08-11 18:39:05 -07002664 }
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002665 }
2666 for (i=0 ; i<n ; i++) {
2667 item = PyTuple_GET_ITEM(p, i);
Raymond Hettingercfd735e2019-01-29 20:39:53 -08002668 ASSIGN_DOUBLE(px, item, error_exit);
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002669 item = PyTuple_GET_ITEM(q, i);
Raymond Hettingercfd735e2019-01-29 20:39:53 -08002670 ASSIGN_DOUBLE(qx, item, error_exit);
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002671 x = fabs(px - qx);
2672 diffs[i] = x;
2673 found_nan |= Py_IS_NAN(x);
2674 if (x > max) {
2675 max = x;
2676 }
2677 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002678 result = vector_norm(n, diffs, max, found_nan);
2679 if (diffs != diffs_on_stack) {
2680 PyObject_Free(diffs);
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002681 }
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002682 if (p_allocated) {
2683 Py_DECREF(p);
2684 }
2685 if (q_allocated) {
2686 Py_DECREF(q);
2687 }
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002688 return PyFloat_FromDouble(result);
Raymond Hettingerc630e102018-08-11 18:39:05 -07002689
2690 error_exit:
2691 if (diffs != diffs_on_stack) {
2692 PyObject_Free(diffs);
2693 }
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002694 if (p_allocated) {
2695 Py_DECREF(p);
2696 }
2697 if (q_allocated) {
2698 Py_DECREF(q);
2699 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002700 return NULL;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002701}
2702
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002703/* AC: cannot convert yet, waiting for *args support */
Christian Heimes53876d92008-04-19 00:31:39 +00002704static PyObject *
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002705math_hypot(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Christian Heimes53876d92008-04-19 00:31:39 +00002706{
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002707 Py_ssize_t i;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002708 PyObject *item;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002709 double max = 0.0;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002710 double x, result;
2711 int found_nan = 0;
Raymond Hettingerc630e102018-08-11 18:39:05 -07002712 double coord_on_stack[NUM_STACK_ELEMS];
2713 double *coordinates = coord_on_stack;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002714
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002715 if (nargs > NUM_STACK_ELEMS) {
2716 coordinates = (double *) PyObject_Malloc(nargs * sizeof(double));
Zackery Spytz4c49da02018-12-07 03:11:30 -07002717 if (coordinates == NULL) {
2718 return PyErr_NoMemory();
2719 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002720 }
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002721 for (i = 0; i < nargs; i++) {
2722 item = args[i];
Raymond Hettingercfd735e2019-01-29 20:39:53 -08002723 ASSIGN_DOUBLE(x, item, error_exit);
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002724 x = fabs(x);
2725 coordinates[i] = x;
2726 found_nan |= Py_IS_NAN(x);
2727 if (x > max) {
2728 max = x;
2729 }
2730 }
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002731 result = vector_norm(nargs, coordinates, max, found_nan);
Raymond Hettingerc630e102018-08-11 18:39:05 -07002732 if (coordinates != coord_on_stack) {
2733 PyObject_Free(coordinates);
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002734 }
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002735 return PyFloat_FromDouble(result);
Raymond Hettingerc630e102018-08-11 18:39:05 -07002736
2737 error_exit:
2738 if (coordinates != coord_on_stack) {
2739 PyObject_Free(coordinates);
2740 }
2741 return NULL;
Christian Heimes53876d92008-04-19 00:31:39 +00002742}
2743
Raymond Hettingerc630e102018-08-11 18:39:05 -07002744#undef NUM_STACK_ELEMS
2745
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002746PyDoc_STRVAR(math_hypot_doc,
2747 "hypot(*coordinates) -> value\n\n\
2748Multidimensional Euclidean distance from the origin to a point.\n\
2749\n\
2750Roughly equivalent to:\n\
2751 sqrt(sum(x**2 for x in coordinates))\n\
2752\n\
2753For a two dimensional point (x, y), gives the hypotenuse\n\
2754using the Pythagorean theorem: sqrt(x*x + y*y).\n\
2755\n\
2756For example, the hypotenuse of a 3/4/5 right triangle is:\n\
2757\n\
2758 >>> hypot(3.0, 4.0)\n\
2759 5.0\n\
2760");
Christian Heimes53876d92008-04-19 00:31:39 +00002761
2762/* pow can't use math_2, but needs its own wrapper: the problem is
2763 that an infinite result can arise either as a result of overflow
2764 (in which case OverflowError should be raised) or as a result of
2765 e.g. 0.**-5. (for which ValueError needs to be raised.)
2766*/
2767
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002768/*[clinic input]
2769math.pow
Christian Heimes53876d92008-04-19 00:31:39 +00002770
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002771 x: double
2772 y: double
2773 /
2774
2775Return x**y (x to the power of y).
2776[clinic start generated code]*/
2777
2778static PyObject *
2779math_pow_impl(PyObject *module, double x, double y)
2780/*[clinic end generated code: output=fff93e65abccd6b0 input=c26f1f6075088bfd]*/
2781{
2782 double r;
2783 int odd_y;
Christian Heimesa342c012008-04-20 21:01:16 +00002784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 /* deal directly with IEEE specials, to cope with problems on various
2786 platforms whose semantics don't exactly match C99 */
2787 r = 0.; /* silence compiler warning */
2788 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
2789 errno = 0;
2790 if (Py_IS_NAN(x))
2791 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
2792 else if (Py_IS_NAN(y))
2793 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
2794 else if (Py_IS_INFINITY(x)) {
2795 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
2796 if (y > 0.)
2797 r = odd_y ? x : fabs(x);
2798 else if (y == 0.)
2799 r = 1.;
2800 else /* y < 0. */
2801 r = odd_y ? copysign(0., x) : 0.;
2802 }
2803 else if (Py_IS_INFINITY(y)) {
2804 if (fabs(x) == 1.0)
2805 r = 1.;
2806 else if (y > 0. && fabs(x) > 1.0)
2807 r = y;
2808 else if (y < 0. && fabs(x) < 1.0) {
2809 r = -y; /* result is +inf */
2810 if (x == 0.) /* 0**-inf: divide-by-zero */
2811 errno = EDOM;
2812 }
2813 else
2814 r = 0.;
2815 }
2816 }
2817 else {
2818 /* let libm handle finite**finite */
2819 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002820 r = pow(x, y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002821 /* a NaN result should arise only from (-ve)**(finite
2822 non-integer); in this case we want to raise ValueError. */
2823 if (!Py_IS_FINITE(r)) {
2824 if (Py_IS_NAN(r)) {
2825 errno = EDOM;
2826 }
2827 /*
2828 an infinite result here arises either from:
2829 (A) (+/-0.)**negative (-> divide-by-zero)
2830 (B) overflow of x**y with x and y finite
2831 */
2832 else if (Py_IS_INFINITY(r)) {
2833 if (x == 0.)
2834 errno = EDOM;
2835 else
2836 errno = ERANGE;
2837 }
2838 }
2839 }
Christian Heimes53876d92008-04-19 00:31:39 +00002840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002841 if (errno && is_error(r))
2842 return NULL;
2843 else
2844 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00002845}
2846
Christian Heimes53876d92008-04-19 00:31:39 +00002847
Christian Heimes072c0f12008-01-03 23:01:04 +00002848static const double degToRad = Py_MATH_PI / 180.0;
2849static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002850
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002851/*[clinic input]
2852math.degrees
2853
2854 x: double
2855 /
2856
2857Convert angle x from radians to degrees.
2858[clinic start generated code]*/
2859
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002860static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002861math_degrees_impl(PyObject *module, double x)
2862/*[clinic end generated code: output=7fea78b294acd12f input=81e016555d6e3660]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002863{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002865}
2866
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002867
2868/*[clinic input]
2869math.radians
2870
2871 x: double
2872 /
2873
2874Convert angle x from degrees to radians.
2875[clinic start generated code]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002876
2877static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002878math_radians_impl(PyObject *module, double x)
2879/*[clinic end generated code: output=34daa47caf9b1590 input=91626fc489fe3d63]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002880{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002881 return PyFloat_FromDouble(x * degToRad);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002882}
2883
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002884
2885/*[clinic input]
2886math.isfinite
2887
2888 x: double
2889 /
2890
2891Return True if x is neither an infinity nor a NaN, and False otherwise.
2892[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002893
Christian Heimes072c0f12008-01-03 23:01:04 +00002894static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002895math_isfinite_impl(PyObject *module, double x)
2896/*[clinic end generated code: output=8ba1f396440c9901 input=46967d254812e54a]*/
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002897{
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002898 return PyBool_FromLong((long)Py_IS_FINITE(x));
2899}
2900
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002901
2902/*[clinic input]
2903math.isnan
2904
2905 x: double
2906 /
2907
2908Return True if x is a NaN (not a number), and False otherwise.
2909[clinic start generated code]*/
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002910
2911static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002912math_isnan_impl(PyObject *module, double x)
2913/*[clinic end generated code: output=f537b4d6df878c3e input=935891e66083f46a]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002914{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002915 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00002916}
2917
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002918
2919/*[clinic input]
2920math.isinf
2921
2922 x: double
2923 /
2924
2925Return True if x is a positive or negative infinity, and False otherwise.
2926[clinic start generated code]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002927
2928static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002929math_isinf_impl(PyObject *module, double x)
2930/*[clinic end generated code: output=9f00cbec4de7b06b input=32630e4212cf961f]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002931{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002932 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00002933}
2934
Christian Heimes072c0f12008-01-03 23:01:04 +00002935
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002936/*[clinic input]
2937math.isclose -> bool
2938
2939 a: double
2940 b: double
2941 *
2942 rel_tol: double = 1e-09
2943 maximum difference for being considered "close", relative to the
2944 magnitude of the input values
2945 abs_tol: double = 0.0
2946 maximum difference for being considered "close", regardless of the
2947 magnitude of the input values
2948
2949Determine whether two floating point numbers are close in value.
2950
2951Return True if a is close in value to b, and False otherwise.
2952
2953For the values to be considered close, the difference between them
2954must be smaller than at least one of the tolerances.
2955
2956-inf, inf and NaN behave similarly to the IEEE 754 Standard. That
2957is, NaN is not close to anything, even itself. inf and -inf are
2958only close to themselves.
2959[clinic start generated code]*/
2960
2961static int
2962math_isclose_impl(PyObject *module, double a, double b, double rel_tol,
2963 double abs_tol)
2964/*[clinic end generated code: output=b73070207511952d input=f28671871ea5bfba]*/
Tal Einatd5519ed2015-05-31 22:05:00 +03002965{
Tal Einatd5519ed2015-05-31 22:05:00 +03002966 double diff = 0.0;
Tal Einatd5519ed2015-05-31 22:05:00 +03002967
2968 /* sanity check on the inputs */
2969 if (rel_tol < 0.0 || abs_tol < 0.0 ) {
2970 PyErr_SetString(PyExc_ValueError,
2971 "tolerances must be non-negative");
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002972 return -1;
Tal Einatd5519ed2015-05-31 22:05:00 +03002973 }
2974
2975 if ( a == b ) {
2976 /* short circuit exact equality -- needed to catch two infinities of
2977 the same sign. And perhaps speeds things up a bit sometimes.
2978 */
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002979 return 1;
Tal Einatd5519ed2015-05-31 22:05:00 +03002980 }
2981
2982 /* This catches the case of two infinities of opposite sign, or
2983 one infinity and one finite number. Two infinities of opposite
2984 sign would otherwise have an infinite relative tolerance.
2985 Two infinities of the same sign are caught by the equality check
2986 above.
2987 */
2988
2989 if (Py_IS_INFINITY(a) || Py_IS_INFINITY(b)) {
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002990 return 0;
Tal Einatd5519ed2015-05-31 22:05:00 +03002991 }
2992
2993 /* now do the regular computation
2994 this is essentially the "weak" test from the Boost library
2995 */
2996
2997 diff = fabs(b - a);
2998
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002999 return (((diff <= fabs(rel_tol * b)) ||
3000 (diff <= fabs(rel_tol * a))) ||
3001 (diff <= abs_tol));
Tal Einatd5519ed2015-05-31 22:05:00 +03003002}
3003
Pablo Galindo04114112019-03-09 19:18:08 +00003004static inline int
3005_check_long_mult_overflow(long a, long b) {
3006
3007 /* From Python2's int_mul code:
3008
3009 Integer overflow checking for * is painful: Python tried a couple ways, but
3010 they didn't work on all platforms, or failed in endcases (a product of
3011 -sys.maxint-1 has been a particular pain).
3012
3013 Here's another way:
3014
3015 The native long product x*y is either exactly right or *way* off, being
3016 just the last n bits of the true product, where n is the number of bits
3017 in a long (the delivered product is the true product plus i*2**n for
3018 some integer i).
3019
3020 The native double product (double)x * (double)y is subject to three
3021 rounding errors: on a sizeof(long)==8 box, each cast to double can lose
3022 info, and even on a sizeof(long)==4 box, the multiplication can lose info.
3023 But, unlike the native long product, it's not in *range* trouble: even
3024 if sizeof(long)==32 (256-bit longs), the product easily fits in the
3025 dynamic range of a double. So the leading 50 (or so) bits of the double
3026 product are correct.
3027
3028 We check these two ways against each other, and declare victory if they're
3029 approximately the same. Else, because the native long product is the only
3030 one that can lose catastrophic amounts of information, it's the native long
3031 product that must have overflowed.
3032
3033 */
3034
3035 long longprod = (long)((unsigned long)a * b);
3036 double doubleprod = (double)a * (double)b;
3037 double doubled_longprod = (double)longprod;
3038
3039 if (doubled_longprod == doubleprod) {
3040 return 0;
3041 }
3042
3043 const double diff = doubled_longprod - doubleprod;
3044 const double absdiff = diff >= 0.0 ? diff : -diff;
3045 const double absprod = doubleprod >= 0.0 ? doubleprod : -doubleprod;
3046
3047 if (32.0 * absdiff <= absprod) {
3048 return 0;
3049 }
3050
3051 return 1;
3052}
Tal Einatd5519ed2015-05-31 22:05:00 +03003053
Pablo Galindobc098512019-02-07 07:04:02 +00003054/*[clinic input]
3055math.prod
3056
3057 iterable: object
3058 /
3059 *
3060 start: object(c_default="NULL") = 1
3061
3062Calculate the product of all the elements in the input iterable.
3063
3064The default start value for the product is 1.
3065
3066When the iterable is empty, return the start value. This function is
3067intended specifically for use with numeric values and may reject
3068non-numeric types.
3069[clinic start generated code]*/
3070
3071static PyObject *
3072math_prod_impl(PyObject *module, PyObject *iterable, PyObject *start)
3073/*[clinic end generated code: output=36153bedac74a198 input=4c5ab0682782ed54]*/
3074{
3075 PyObject *result = start;
3076 PyObject *temp, *item, *iter;
3077
3078 iter = PyObject_GetIter(iterable);
3079 if (iter == NULL) {
3080 return NULL;
3081 }
3082
3083 if (result == NULL) {
3084 result = PyLong_FromLong(1);
3085 if (result == NULL) {
3086 Py_DECREF(iter);
3087 return NULL;
3088 }
3089 } else {
3090 Py_INCREF(result);
3091 }
3092#ifndef SLOW_PROD
3093 /* Fast paths for integers keeping temporary products in C.
3094 * Assumes all inputs are the same type.
3095 * If the assumption fails, default to use PyObjects instead.
3096 */
3097 if (PyLong_CheckExact(result)) {
3098 int overflow;
3099 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
3100 /* If this already overflowed, don't even enter the loop. */
3101 if (overflow == 0) {
3102 Py_DECREF(result);
3103 result = NULL;
3104 }
3105 /* Loop over all the items in the iterable until we finish, we overflow
3106 * or we found a non integer element */
3107 while(result == NULL) {
3108 item = PyIter_Next(iter);
3109 if (item == NULL) {
3110 Py_DECREF(iter);
3111 if (PyErr_Occurred()) {
3112 return NULL;
3113 }
3114 return PyLong_FromLong(i_result);
3115 }
3116 if (PyLong_CheckExact(item)) {
3117 long b = PyLong_AsLongAndOverflow(item, &overflow);
Pablo Galindo04114112019-03-09 19:18:08 +00003118 if (overflow == 0 && !_check_long_mult_overflow(i_result, b)) {
3119 long x = i_result * b;
Pablo Galindobc098512019-02-07 07:04:02 +00003120 i_result = x;
3121 Py_DECREF(item);
3122 continue;
3123 }
3124 }
3125 /* Either overflowed or is not an int.
3126 * Restore real objects and process normally */
3127 result = PyLong_FromLong(i_result);
3128 if (result == NULL) {
3129 Py_DECREF(item);
3130 Py_DECREF(iter);
3131 return NULL;
3132 }
3133 temp = PyNumber_Multiply(result, item);
3134 Py_DECREF(result);
3135 Py_DECREF(item);
3136 result = temp;
3137 if (result == NULL) {
3138 Py_DECREF(iter);
3139 return NULL;
3140 }
3141 }
3142 }
3143
3144 /* Fast paths for floats keeping temporary products in C.
3145 * Assumes all inputs are the same type.
3146 * If the assumption fails, default to use PyObjects instead.
3147 */
3148 if (PyFloat_CheckExact(result)) {
3149 double f_result = PyFloat_AS_DOUBLE(result);
3150 Py_DECREF(result);
3151 result = NULL;
3152 while(result == NULL) {
3153 item = PyIter_Next(iter);
3154 if (item == NULL) {
3155 Py_DECREF(iter);
3156 if (PyErr_Occurred()) {
3157 return NULL;
3158 }
3159 return PyFloat_FromDouble(f_result);
3160 }
3161 if (PyFloat_CheckExact(item)) {
3162 f_result *= PyFloat_AS_DOUBLE(item);
3163 Py_DECREF(item);
3164 continue;
3165 }
3166 if (PyLong_CheckExact(item)) {
3167 long value;
3168 int overflow;
3169 value = PyLong_AsLongAndOverflow(item, &overflow);
3170 if (!overflow) {
3171 f_result *= (double)value;
3172 Py_DECREF(item);
3173 continue;
3174 }
3175 }
3176 result = PyFloat_FromDouble(f_result);
3177 if (result == NULL) {
3178 Py_DECREF(item);
3179 Py_DECREF(iter);
3180 return NULL;
3181 }
3182 temp = PyNumber_Multiply(result, item);
3183 Py_DECREF(result);
3184 Py_DECREF(item);
3185 result = temp;
3186 if (result == NULL) {
3187 Py_DECREF(iter);
3188 return NULL;
3189 }
3190 }
3191 }
3192#endif
3193 /* Consume rest of the iterable (if any) that could not be handled
3194 * by specialized functions above.*/
3195 for(;;) {
3196 item = PyIter_Next(iter);
3197 if (item == NULL) {
3198 /* error, or end-of-sequence */
3199 if (PyErr_Occurred()) {
3200 Py_DECREF(result);
3201 result = NULL;
3202 }
3203 break;
3204 }
3205 temp = PyNumber_Multiply(result, item);
3206 Py_DECREF(result);
3207 Py_DECREF(item);
3208 result = temp;
3209 if (result == NULL)
3210 break;
3211 }
3212 Py_DECREF(iter);
3213 return result;
3214}
3215
3216
Yash Aggarwal4a686502019-06-01 12:51:27 +05303217/*[clinic input]
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003218math.perm
3219
3220 n: object
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003221 k: object = None
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003222 /
3223
3224Number of ways to choose k items from n items without repetition and with order.
3225
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003226Evaluates to n! / (n - k)! when k <= n and evaluates
3227to zero when k > n.
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003228
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003229If k is not specified or is None, then k defaults to n
3230and the function returns n!.
3231
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003232Raises TypeError if either of the arguments are not integers.
3233Raises ValueError if either of the arguments are negative.
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003234[clinic start generated code]*/
3235
3236static PyObject *
3237math_perm_impl(PyObject *module, PyObject *n, PyObject *k)
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003238/*[clinic end generated code: output=e021a25469653e23 input=5311c5a00f359b53]*/
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003239{
3240 PyObject *result = NULL, *factor = NULL;
3241 int overflow, cmp;
3242 long long i, factors;
3243
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003244 if (k == Py_None) {
3245 return math_factorial(module, n);
3246 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003247 n = PyNumber_Index(n);
3248 if (n == NULL) {
3249 return NULL;
3250 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003251 k = PyNumber_Index(k);
3252 if (k == NULL) {
3253 Py_DECREF(n);
3254 return NULL;
3255 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003256
3257 if (Py_SIZE(n) < 0) {
3258 PyErr_SetString(PyExc_ValueError,
3259 "n must be a non-negative integer");
3260 goto error;
3261 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003262 if (Py_SIZE(k) < 0) {
3263 PyErr_SetString(PyExc_ValueError,
3264 "k must be a non-negative integer");
3265 goto error;
3266 }
3267
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003268 cmp = PyObject_RichCompareBool(n, k, Py_LT);
3269 if (cmp != 0) {
3270 if (cmp > 0) {
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003271 result = PyLong_FromLong(0);
3272 goto done;
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003273 }
3274 goto error;
3275 }
3276
3277 factors = PyLong_AsLongLongAndOverflow(k, &overflow);
3278 if (overflow > 0) {
3279 PyErr_Format(PyExc_OverflowError,
3280 "k must not exceed %lld",
3281 LLONG_MAX);
3282 goto error;
3283 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003284 else if (factors == -1) {
3285 /* k is nonnegative, so a return value of -1 can only indicate error */
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003286 goto error;
3287 }
3288
3289 if (factors == 0) {
3290 result = PyLong_FromLong(1);
3291 goto done;
3292 }
3293
3294 result = n;
3295 Py_INCREF(result);
3296 if (factors == 1) {
3297 goto done;
3298 }
3299
Miss Islington (bot)41159962021-05-26 16:13:17 -07003300 factor = Py_NewRef(n);
3301 PyObject *one = _PyLong_GetOne(); // borrowed ref
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003302 for (i = 1; i < factors; ++i) {
Miss Islington (bot)41159962021-05-26 16:13:17 -07003303 Py_SETREF(factor, PyNumber_Subtract(factor, one));
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003304 if (factor == NULL) {
3305 goto error;
3306 }
3307 Py_SETREF(result, PyNumber_Multiply(result, factor));
3308 if (result == NULL) {
3309 goto error;
3310 }
3311 }
3312 Py_DECREF(factor);
3313
3314done:
3315 Py_DECREF(n);
3316 Py_DECREF(k);
3317 return result;
3318
3319error:
3320 Py_XDECREF(factor);
3321 Py_XDECREF(result);
3322 Py_DECREF(n);
3323 Py_DECREF(k);
3324 return NULL;
3325}
3326
3327
3328/*[clinic input]
Yash Aggarwal4a686502019-06-01 12:51:27 +05303329math.comb
3330
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003331 n: object
3332 k: object
3333 /
Yash Aggarwal4a686502019-06-01 12:51:27 +05303334
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003335Number of ways to choose k items from n items without repetition and without order.
Yash Aggarwal4a686502019-06-01 12:51:27 +05303336
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003337Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates
3338to zero when k > n.
Yash Aggarwal4a686502019-06-01 12:51:27 +05303339
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003340Also called the binomial coefficient because it is equivalent
3341to the coefficient of k-th term in polynomial expansion of the
3342expression (1 + x)**n.
3343
3344Raises TypeError if either of the arguments are not integers.
3345Raises ValueError if either of the arguments are negative.
Yash Aggarwal4a686502019-06-01 12:51:27 +05303346
3347[clinic start generated code]*/
3348
3349static PyObject *
3350math_comb_impl(PyObject *module, PyObject *n, PyObject *k)
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003351/*[clinic end generated code: output=bd2cec8d854f3493 input=9a05315af2518709]*/
Yash Aggarwal4a686502019-06-01 12:51:27 +05303352{
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003353 PyObject *result = NULL, *factor = NULL, *temp;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303354 int overflow, cmp;
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003355 long long i, factors;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303356
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003357 n = PyNumber_Index(n);
3358 if (n == NULL) {
3359 return NULL;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303360 }
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003361 k = PyNumber_Index(k);
3362 if (k == NULL) {
3363 Py_DECREF(n);
3364 return NULL;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303365 }
3366
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003367 if (Py_SIZE(n) < 0) {
3368 PyErr_SetString(PyExc_ValueError,
3369 "n must be a non-negative integer");
3370 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303371 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003372 if (Py_SIZE(k) < 0) {
3373 PyErr_SetString(PyExc_ValueError,
3374 "k must be a non-negative integer");
3375 goto error;
3376 }
3377
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003378 /* k = min(k, n - k) */
3379 temp = PyNumber_Subtract(n, k);
3380 if (temp == NULL) {
3381 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303382 }
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003383 if (Py_SIZE(temp) < 0) {
3384 Py_DECREF(temp);
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003385 result = PyLong_FromLong(0);
3386 goto done;
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003387 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003388 cmp = PyObject_RichCompareBool(temp, k, Py_LT);
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003389 if (cmp > 0) {
3390 Py_SETREF(k, temp);
Yash Aggarwal4a686502019-06-01 12:51:27 +05303391 }
3392 else {
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003393 Py_DECREF(temp);
3394 if (cmp < 0) {
3395 goto error;
3396 }
Yash Aggarwal4a686502019-06-01 12:51:27 +05303397 }
3398
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003399 factors = PyLong_AsLongLongAndOverflow(k, &overflow);
3400 if (overflow > 0) {
Yash Aggarwal4a686502019-06-01 12:51:27 +05303401 PyErr_Format(PyExc_OverflowError,
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003402 "min(n - k, k) must not exceed %lld",
Yash Aggarwal4a686502019-06-01 12:51:27 +05303403 LLONG_MAX);
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003404 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303405 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003406 if (factors == -1) {
3407 /* k is nonnegative, so a return value of -1 can only indicate error */
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003408 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303409 }
3410
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003411 if (factors == 0) {
3412 result = PyLong_FromLong(1);
3413 goto done;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303414 }
3415
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003416 result = n;
3417 Py_INCREF(result);
3418 if (factors == 1) {
3419 goto done;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303420 }
3421
Miss Islington (bot)41159962021-05-26 16:13:17 -07003422 factor = Py_NewRef(n);
3423 PyObject *one = _PyLong_GetOne(); // borrowed ref
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003424 for (i = 1; i < factors; ++i) {
Miss Islington (bot)41159962021-05-26 16:13:17 -07003425 Py_SETREF(factor, PyNumber_Subtract(factor, one));
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003426 if (factor == NULL) {
3427 goto error;
3428 }
3429 Py_SETREF(result, PyNumber_Multiply(result, factor));
3430 if (result == NULL) {
3431 goto error;
3432 }
Yash Aggarwal4a686502019-06-01 12:51:27 +05303433
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003434 temp = PyLong_FromUnsignedLongLong((unsigned long long)i + 1);
3435 if (temp == NULL) {
3436 goto error;
3437 }
3438 Py_SETREF(result, PyNumber_FloorDivide(result, temp));
3439 Py_DECREF(temp);
3440 if (result == NULL) {
3441 goto error;
3442 }
3443 }
3444 Py_DECREF(factor);
Yash Aggarwal4a686502019-06-01 12:51:27 +05303445
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003446done:
3447 Py_DECREF(n);
3448 Py_DECREF(k);
3449 return result;
3450
3451error:
3452 Py_XDECREF(factor);
3453 Py_XDECREF(result);
3454 Py_DECREF(n);
3455 Py_DECREF(k);
Yash Aggarwal4a686502019-06-01 12:51:27 +05303456 return NULL;
3457}
3458
3459
Victor Stinner100fafc2020-01-12 02:15:42 +01003460/*[clinic input]
3461math.nextafter
3462
3463 x: double
3464 y: double
3465 /
3466
3467Return the next floating-point value after x towards y.
3468[clinic start generated code]*/
3469
3470static PyObject *
3471math_nextafter_impl(PyObject *module, double x, double y)
3472/*[clinic end generated code: output=750c8266c1c540ce input=02b2d50cd1d9f9b6]*/
3473{
Victor Stinner85ead4f2020-01-21 11:14:10 +01003474#if defined(_AIX)
3475 if (x == y) {
3476 /* On AIX 7.1, libm nextafter(-0.0, +0.0) returns -0.0.
3477 Bug fixed in bos.adt.libm 7.2.2.0 by APAR IV95512. */
3478 return PyFloat_FromDouble(y);
3479 }
Victor Stinnerc1c34932021-01-20 15:20:13 +01003480 if (Py_IS_NAN(x)) {
Victor Stinner0837f992021-01-29 23:04:50 +01003481 return PyFloat_FromDouble(x);
Victor Stinnerc1c34932021-01-20 15:20:13 +01003482 }
3483 if (Py_IS_NAN(y)) {
Victor Stinner0837f992021-01-29 23:04:50 +01003484 return PyFloat_FromDouble(y);
Victor Stinnerc1c34932021-01-20 15:20:13 +01003485 }
Victor Stinner85ead4f2020-01-21 11:14:10 +01003486#endif
3487 return PyFloat_FromDouble(nextafter(x, y));
Victor Stinner100fafc2020-01-12 02:15:42 +01003488}
3489
3490
Victor Stinner0b2ab212020-01-13 12:44:35 +01003491/*[clinic input]
3492math.ulp -> double
3493
3494 x: double
3495 /
3496
3497Return the value of the least significant bit of the float x.
3498[clinic start generated code]*/
3499
3500static double
3501math_ulp_impl(PyObject *module, double x)
3502/*[clinic end generated code: output=f5207867a9384dd4 input=31f9bfbbe373fcaa]*/
3503{
3504 if (Py_IS_NAN(x)) {
3505 return x;
3506 }
3507 x = fabs(x);
3508 if (Py_IS_INFINITY(x)) {
3509 return x;
3510 }
3511 double inf = m_inf();
3512 double x2 = nextafter(x, inf);
3513 if (Py_IS_INFINITY(x2)) {
3514 /* special case: x is the largest positive representable float */
3515 x2 = nextafter(x, -inf);
3516 return x - x2;
3517 }
3518 return x2 - x;
3519}
3520
Dong-hee Na5be82412020-03-31 23:33:22 +09003521static int
3522math_exec(PyObject *module)
3523{
3524 if (PyModule_AddObject(module, "pi", PyFloat_FromDouble(Py_MATH_PI)) < 0) {
3525 return -1;
3526 }
3527 if (PyModule_AddObject(module, "e", PyFloat_FromDouble(Py_MATH_E)) < 0) {
3528 return -1;
3529 }
3530 // 2pi
3531 if (PyModule_AddObject(module, "tau", PyFloat_FromDouble(Py_MATH_TAU)) < 0) {
3532 return -1;
3533 }
3534 if (PyModule_AddObject(module, "inf", PyFloat_FromDouble(m_inf())) < 0) {
3535 return -1;
3536 }
3537#if !defined(PY_NO_SHORT_FLOAT_REPR) || defined(Py_NAN)
3538 if (PyModule_AddObject(module, "nan", PyFloat_FromDouble(m_nan())) < 0) {
3539 return -1;
3540 }
3541#endif
3542 return 0;
3543}
Victor Stinner0b2ab212020-01-13 12:44:35 +01003544
Barry Warsaw8b43b191996-12-09 22:32:36 +00003545static PyMethodDef math_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003546 {"acos", math_acos, METH_O, math_acos_doc},
3547 {"acosh", math_acosh, METH_O, math_acosh_doc},
3548 {"asin", math_asin, METH_O, math_asin_doc},
3549 {"asinh", math_asinh, METH_O, math_asinh_doc},
3550 {"atan", math_atan, METH_O, math_atan_doc},
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003551 {"atan2", (PyCFunction)(void(*)(void))math_atan2, METH_FASTCALL, math_atan2_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003552 {"atanh", math_atanh, METH_O, math_atanh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003553 MATH_CEIL_METHODDEF
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003554 {"copysign", (PyCFunction)(void(*)(void))math_copysign, METH_FASTCALL, math_copysign_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003555 {"cos", math_cos, METH_O, math_cos_doc},
3556 {"cosh", math_cosh, METH_O, math_cosh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003557 MATH_DEGREES_METHODDEF
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07003558 MATH_DIST_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003559 {"erf", math_erf, METH_O, math_erf_doc},
3560 {"erfc", math_erfc, METH_O, math_erfc_doc},
3561 {"exp", math_exp, METH_O, math_exp_doc},
3562 {"expm1", math_expm1, METH_O, math_expm1_doc},
3563 {"fabs", math_fabs, METH_O, math_fabs_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003564 MATH_FACTORIAL_METHODDEF
3565 MATH_FLOOR_METHODDEF
3566 MATH_FMOD_METHODDEF
3567 MATH_FREXP_METHODDEF
3568 MATH_FSUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003569 {"gamma", math_gamma, METH_O, math_gamma_doc},
Serhiy Storchaka559e7f12020-02-23 13:21:29 +02003570 {"gcd", (PyCFunction)(void(*)(void))math_gcd, METH_FASTCALL, math_gcd_doc},
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003571 {"hypot", (PyCFunction)(void(*)(void))math_hypot, METH_FASTCALL, math_hypot_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003572 MATH_ISCLOSE_METHODDEF
3573 MATH_ISFINITE_METHODDEF
3574 MATH_ISINF_METHODDEF
3575 MATH_ISNAN_METHODDEF
Mark Dickinson73934b92019-05-18 12:29:50 +01003576 MATH_ISQRT_METHODDEF
Serhiy Storchaka559e7f12020-02-23 13:21:29 +02003577 {"lcm", (PyCFunction)(void(*)(void))math_lcm, METH_FASTCALL, math_lcm_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003578 MATH_LDEXP_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003579 {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003580 MATH_LOG_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003581 {"log1p", math_log1p, METH_O, math_log1p_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003582 MATH_LOG10_METHODDEF
3583 MATH_LOG2_METHODDEF
3584 MATH_MODF_METHODDEF
3585 MATH_POW_METHODDEF
3586 MATH_RADIANS_METHODDEF
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003587 {"remainder", (PyCFunction)(void(*)(void))math_remainder, METH_FASTCALL, math_remainder_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003588 {"sin", math_sin, METH_O, math_sin_doc},
3589 {"sinh", math_sinh, METH_O, math_sinh_doc},
3590 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
3591 {"tan", math_tan, METH_O, math_tan_doc},
3592 {"tanh", math_tanh, METH_O, math_tanh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003593 MATH_TRUNC_METHODDEF
Pablo Galindobc098512019-02-07 07:04:02 +00003594 MATH_PROD_METHODDEF
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003595 MATH_PERM_METHODDEF
Yash Aggarwal4a686502019-06-01 12:51:27 +05303596 MATH_COMB_METHODDEF
Victor Stinner100fafc2020-01-12 02:15:42 +01003597 MATH_NEXTAFTER_METHODDEF
Victor Stinner0b2ab212020-01-13 12:44:35 +01003598 MATH_ULP_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003599 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003600};
3601
Dong-hee Na5be82412020-03-31 23:33:22 +09003602static PyModuleDef_Slot math_slots[] = {
3603 {Py_mod_exec, math_exec},
3604 {0, NULL}
3605};
Guido van Rossumc6e22901998-12-04 19:26:43 +00003606
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003607PyDoc_STRVAR(module_doc,
Ned Batchelder6faad352019-05-17 05:59:14 -04003608"This module provides access to the mathematical functions\n"
3609"defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00003610
Martin v. Löwis1a214512008-06-11 05:26:20 +00003611static struct PyModuleDef mathmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003612 PyModuleDef_HEAD_INIT,
Dong-hee Na5be82412020-03-31 23:33:22 +09003613 .m_name = "math",
3614 .m_doc = module_doc,
3615 .m_size = 0,
3616 .m_methods = math_methods,
3617 .m_slots = math_slots,
Martin v. Löwis1a214512008-06-11 05:26:20 +00003618};
3619
Mark Hammondfe51c6d2002-08-02 02:27:13 +00003620PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003621PyInit_math(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003622{
Dong-hee Na5be82412020-03-31 23:33:22 +09003623 return PyModuleDef_Init(&mathmodule);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003624}