blob: 86b64fb42269078b72073fedf9b00d6afcfee468 [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 }
848 for (i = 1; i < nargs; i++) {
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +0300849 x = _PyNumber_Index(args[i]);
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200850 if (x == NULL) {
851 Py_DECREF(res);
852 return NULL;
853 }
Victor Stinner37834132020-10-27 17:12:53 +0100854 if (res == _PyLong_GetOne()) {
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200855 /* Fast path: just check arguments.
856 It is okay to use identity comparison here. */
857 Py_DECREF(x);
858 continue;
859 }
860 Py_SETREF(res, _PyLong_GCD(res, x));
861 Py_DECREF(x);
862 if (res == NULL) {
863 return NULL;
864 }
865 }
866 return res;
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300867}
868
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200869PyDoc_STRVAR(math_gcd_doc,
870"gcd($module, *integers)\n"
871"--\n"
872"\n"
873"Greatest Common Divisor.");
874
875
876static PyObject *
877long_lcm(PyObject *a, PyObject *b)
878{
879 PyObject *g, *m, *f, *ab;
880
881 if (Py_SIZE(a) == 0 || Py_SIZE(b) == 0) {
882 return PyLong_FromLong(0);
883 }
884 g = _PyLong_GCD(a, b);
885 if (g == NULL) {
886 return NULL;
887 }
888 f = PyNumber_FloorDivide(a, g);
889 Py_DECREF(g);
890 if (f == NULL) {
891 return NULL;
892 }
893 m = PyNumber_Multiply(f, b);
894 Py_DECREF(f);
895 if (m == NULL) {
896 return NULL;
897 }
898 ab = PyNumber_Absolute(m);
899 Py_DECREF(m);
900 return ab;
901}
902
903
904static PyObject *
905math_lcm(PyObject *module, PyObject * const *args, Py_ssize_t nargs)
906{
907 PyObject *res, *x;
908 Py_ssize_t i;
909
910 if (nargs == 0) {
911 return PyLong_FromLong(1);
912 }
913 res = PyNumber_Index(args[0]);
914 if (res == NULL) {
915 return NULL;
916 }
917 if (nargs == 1) {
918 Py_SETREF(res, PyNumber_Absolute(res));
919 return res;
920 }
921 for (i = 1; i < nargs; i++) {
922 x = PyNumber_Index(args[i]);
923 if (x == NULL) {
924 Py_DECREF(res);
925 return NULL;
926 }
Victor Stinner37834132020-10-27 17:12:53 +0100927 if (res == _PyLong_GetZero()) {
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200928 /* Fast path: just check arguments.
929 It is okay to use identity comparison here. */
930 Py_DECREF(x);
931 continue;
932 }
933 Py_SETREF(res, long_lcm(res, x));
934 Py_DECREF(x);
935 if (res == NULL) {
936 return NULL;
937 }
938 }
939 return res;
940}
941
942
943PyDoc_STRVAR(math_lcm_doc,
944"lcm($module, *integers)\n"
945"--\n"
946"\n"
947"Least Common Multiple.");
948
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300949
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000950/* Call is_error when errno != 0, and where x is the result libm
951 * returned. is_error will usually set up an exception and return
952 * true (1), but may return false (0) without setting up an exception.
953 */
954static int
955is_error(double x)
956{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 int result = 1; /* presumption of guilt */
958 assert(errno); /* non-zero errno is a precondition for calling */
959 if (errno == EDOM)
960 PyErr_SetString(PyExc_ValueError, "math domain error");
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 else if (errno == ERANGE) {
963 /* ANSI C generally requires libm functions to set ERANGE
964 * on overflow, but also generally *allows* them to set
965 * ERANGE on underflow too. There's no consistency about
966 * the latter across platforms.
967 * Alas, C99 never requires that errno be set.
968 * Here we suppress the underflow errors (libm functions
969 * should return a zero on underflow, and +- HUGE_VAL on
970 * overflow, so testing the result for zero suffices to
971 * distinguish the cases).
972 *
973 * On some platforms (Ubuntu/ia64) it seems that errno can be
974 * set to ERANGE for subnormal results that do *not* underflow
975 * to zero. So to be safe, we'll ignore ERANGE whenever the
976 * function result is less than one in absolute value.
977 */
978 if (fabs(x) < 1.0)
979 result = 0;
980 else
981 PyErr_SetString(PyExc_OverflowError,
982 "math range error");
983 }
984 else
985 /* Unexpected math error */
986 PyErr_SetFromErrno(PyExc_ValueError);
987 return result;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000988}
989
Mark Dickinsone675f082008-12-11 21:56:00 +0000990/*
Christian Heimes53876d92008-04-19 00:31:39 +0000991 math_1 is used to wrap a libm function f that takes a double
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200992 argument and returns a double.
Christian Heimes53876d92008-04-19 00:31:39 +0000993
994 The error reporting follows these rules, which are designed to do
995 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
996 platforms.
997
998 - a NaN result from non-NaN inputs causes ValueError to be raised
999 - an infinite result from finite inputs causes OverflowError to be
1000 raised if can_overflow is 1, or raises ValueError if can_overflow
1001 is 0.
1002 - if the result is finite and errno == EDOM then ValueError is
1003 raised
1004 - if the result is finite and nonzero and errno == ERANGE then
1005 OverflowError is raised
1006
1007 The last rule is used to catch overflow on platforms which follow
1008 C89 but for which HUGE_VAL is not an infinity.
1009
1010 For the majority of one-argument functions these rules are enough
1011 to ensure that Python's functions behave as specified in 'Annex F'
1012 of the C99 standard, with the 'invalid' and 'divide-by-zero'
1013 floating-point exceptions mapping to Python's ValueError and the
1014 'overflow' floating-point exception mapping to OverflowError.
1015 math_1 only works for functions that don't have singularities *and*
1016 the possibility of overflow; fortunately, that covers everything we
1017 care about right now.
1018*/
1019
Barry Warsaw8b43b191996-12-09 22:32:36 +00001020static PyObject *
Jeffrey Yasskinc2155832008-01-05 20:03:11 +00001021math_1_to_whatever(PyObject *arg, double (*func) (double),
Christian Heimes53876d92008-04-19 00:31:39 +00001022 PyObject *(*from_double_func) (double),
1023 int can_overflow)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 double x, r;
1026 x = PyFloat_AsDouble(arg);
1027 if (x == -1.0 && PyErr_Occurred())
1028 return NULL;
1029 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 r = (*func)(x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 if (Py_IS_NAN(r) && !Py_IS_NAN(x)) {
1032 PyErr_SetString(PyExc_ValueError,
1033 "math domain error"); /* invalid arg */
1034 return NULL;
1035 }
1036 if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) {
Benjamin Peterson2354a752012-03-13 16:13:09 -05001037 if (can_overflow)
1038 PyErr_SetString(PyExc_OverflowError,
1039 "math range error"); /* overflow */
1040 else
1041 PyErr_SetString(PyExc_ValueError,
1042 "math domain error"); /* singularity */
1043 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 }
1045 if (Py_IS_FINITE(r) && errno && is_error(r))
1046 /* this branch unnecessary on most platforms */
1047 return NULL;
Mark Dickinsonde429622008-05-01 00:19:23 +00001048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 return (*from_double_func)(r);
Christian Heimes53876d92008-04-19 00:31:39 +00001050}
1051
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001052/* variant of math_1, to be used when the function being wrapped is known to
1053 set errno properly (that is, errno = EDOM for invalid or divide-by-zero,
1054 errno = ERANGE for overflow). */
1055
1056static PyObject *
1057math_1a(PyObject *arg, double (*func) (double))
1058{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 double x, r;
1060 x = PyFloat_AsDouble(arg);
1061 if (x == -1.0 && PyErr_Occurred())
1062 return NULL;
1063 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 r = (*func)(x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 if (errno && is_error(r))
1066 return NULL;
1067 return PyFloat_FromDouble(r);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001068}
1069
Christian Heimes53876d92008-04-19 00:31:39 +00001070/*
1071 math_2 is used to wrap a libm function f that takes two double
1072 arguments and returns a double.
1073
1074 The error reporting follows these rules, which are designed to do
1075 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
1076 platforms.
1077
1078 - a NaN result from non-NaN inputs causes ValueError to be raised
1079 - an infinite result from finite inputs causes OverflowError to be
1080 raised.
1081 - if the result is finite and errno == EDOM then ValueError is
1082 raised
1083 - if the result is finite and nonzero and errno == ERANGE then
1084 OverflowError is raised
1085
1086 The last rule is used to catch overflow on platforms which follow
1087 C89 but for which HUGE_VAL is not an infinity.
1088
1089 For most two-argument functions (copysign, fmod, hypot, atan2)
1090 these rules are enough to ensure that Python's functions behave as
1091 specified in 'Annex F' of the C99 standard, with the 'invalid' and
1092 'divide-by-zero' floating-point exceptions mapping to Python's
1093 ValueError and the 'overflow' floating-point exception mapping to
1094 OverflowError.
1095*/
1096
1097static PyObject *
1098math_1(PyObject *arg, double (*func) (double), int can_overflow)
1099{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow);
Jeffrey Yasskinc2155832008-01-05 20:03:11 +00001101}
1102
1103static PyObject *
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02001104math_2(PyObject *const *args, Py_ssize_t nargs,
1105 double (*func) (double, double), const char *funcname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001106{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 double x, y, r;
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02001108 if (!_PyArg_CheckPositional(funcname, nargs, 2, 2))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 return NULL;
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02001110 x = PyFloat_AsDouble(args[0]);
Zackery Spytz5208b4b2020-03-14 04:45:32 -06001111 if (x == -1.0 && PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 return NULL;
Zackery Spytz5208b4b2020-03-14 04:45:32 -06001113 }
1114 y = PyFloat_AsDouble(args[1]);
1115 if (y == -1.0 && PyErr_Occurred()) {
1116 return NULL;
1117 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 r = (*func)(x, y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 if (Py_IS_NAN(r)) {
1121 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1122 errno = EDOM;
1123 else
1124 errno = 0;
1125 }
1126 else if (Py_IS_INFINITY(r)) {
1127 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
1128 errno = ERANGE;
1129 else
1130 errno = 0;
1131 }
1132 if (errno && is_error(r))
1133 return NULL;
1134 else
1135 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001136}
1137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138#define FUNC1(funcname, func, can_overflow, docstring) \
1139 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
1140 return math_1(args, func, can_overflow); \
1141 }\
1142 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144#define FUNC1A(funcname, func, docstring) \
1145 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
1146 return math_1a(args, func); \
1147 }\
1148 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001149
Fred Drake40c48682000-07-03 18:11:56 +00001150#define FUNC2(funcname, func, docstring) \
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02001151 static PyObject * math_##funcname(PyObject *self, PyObject *const *args, Py_ssize_t nargs) { \
1152 return math_2(args, nargs, func, #funcname); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 }\
1154 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001155
Christian Heimes53876d92008-04-19 00:31:39 +00001156FUNC1(acos, acos, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001157 "acos($module, x, /)\n--\n\n"
Giovanni Cappellottodc3f99f2019-07-13 09:59:55 -04001158 "Return the arc cosine (measured in radians) of x.\n\n"
1159 "The result is between 0 and pi.")
Mark Dickinsonf3718592009-12-21 15:27:41 +00001160FUNC1(acosh, m_acosh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001161 "acosh($module, x, /)\n--\n\n"
1162 "Return the inverse hyperbolic cosine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001163FUNC1(asin, asin, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001164 "asin($module, x, /)\n--\n\n"
Giovanni Cappellottodc3f99f2019-07-13 09:59:55 -04001165 "Return the arc sine (measured in radians) of x.\n\n"
1166 "The result is between -pi/2 and pi/2.")
Mark Dickinsonf3718592009-12-21 15:27:41 +00001167FUNC1(asinh, m_asinh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001168 "asinh($module, x, /)\n--\n\n"
1169 "Return the inverse hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001170FUNC1(atan, atan, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001171 "atan($module, x, /)\n--\n\n"
Giovanni Cappellottodc3f99f2019-07-13 09:59:55 -04001172 "Return the arc tangent (measured in radians) of x.\n\n"
1173 "The result is between -pi/2 and pi/2.")
Christian Heimese57950f2008-04-21 13:08:03 +00001174FUNC2(atan2, m_atan2,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001175 "atan2($module, y, x, /)\n--\n\n"
1176 "Return the arc tangent (measured in radians) of y/x.\n\n"
Tim Petersfe71f812001-08-07 22:10:00 +00001177 "Unlike atan(y/x), the signs of both x and y are considered.")
Mark Dickinsonf3718592009-12-21 15:27:41 +00001178FUNC1(atanh, m_atanh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001179 "atanh($module, x, /)\n--\n\n"
1180 "Return the inverse hyperbolic tangent of x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +00001181
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001182/*[clinic input]
1183math.ceil
1184
1185 x as number: object
1186 /
1187
1188Return the ceiling of x as an Integral.
1189
1190This is the smallest integer >= x.
1191[clinic start generated code]*/
1192
1193static PyObject *
1194math_ceil(PyObject *module, PyObject *number)
1195/*[clinic end generated code: output=6c3b8a78bc201c67 input=2725352806399cab]*/
1196{
Benjamin Petersonce798522012-01-22 11:24:29 -05001197 _Py_IDENTIFIER(__ceil__);
Guido van Rossum13e05de2007-08-23 22:56:55 +00001198
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001199 if (!PyFloat_CheckExact(number)) {
1200 PyObject *method = _PyObject_LookupSpecial(number, &PyId___ceil__);
1201 if (method != NULL) {
1202 PyObject *result = _PyObject_CallNoArg(method);
1203 Py_DECREF(method);
1204 return result;
1205 }
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001206 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 return NULL;
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001208 }
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001209 double x = PyFloat_AsDouble(number);
1210 if (x == -1.0 && PyErr_Occurred())
1211 return NULL;
1212
1213 return PyLong_FromDouble(ceil(x));
Guido van Rossum13e05de2007-08-23 22:56:55 +00001214}
1215
Christian Heimes072c0f12008-01-03 23:01:04 +00001216FUNC2(copysign, copysign,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001217 "copysign($module, x, y, /)\n--\n\n"
1218 "Return a float with the magnitude (absolute value) of x but the sign of y.\n\n"
1219 "On platforms that support signed zeros, copysign(1.0, -0.0)\n"
1220 "returns -1.0.\n")
Christian Heimes53876d92008-04-19 00:31:39 +00001221FUNC1(cos, cos, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001222 "cos($module, x, /)\n--\n\n"
1223 "Return the cosine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001224FUNC1(cosh, cosh, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001225 "cosh($module, x, /)\n--\n\n"
1226 "Return the hyperbolic cosine of x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +00001227FUNC1A(erf, m_erf,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001228 "erf($module, x, /)\n--\n\n"
1229 "Error function at x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +00001230FUNC1A(erfc, m_erfc,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001231 "erfc($module, x, /)\n--\n\n"
1232 "Complementary error function at x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001233FUNC1(exp, exp, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001234 "exp($module, x, /)\n--\n\n"
1235 "Return e raised to the power of x.")
Mark Dickinson664b5112009-12-16 20:23:42 +00001236FUNC1(expm1, m_expm1, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001237 "expm1($module, x, /)\n--\n\n"
1238 "Return exp(x)-1.\n\n"
Mark Dickinson664b5112009-12-16 20:23:42 +00001239 "This function avoids the loss of precision involved in the direct "
1240 "evaluation of exp(x)-1 for small x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001241FUNC1(fabs, fabs, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001242 "fabs($module, x, /)\n--\n\n"
1243 "Return the absolute value of the float x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +00001244
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001245/*[clinic input]
1246math.floor
1247
1248 x as number: object
1249 /
1250
1251Return the floor of x as an Integral.
1252
1253This is the largest integer <= x.
1254[clinic start generated code]*/
1255
1256static PyObject *
1257math_floor(PyObject *module, PyObject *number)
1258/*[clinic end generated code: output=c6a65c4884884b8a input=63af6b5d7ebcc3d6]*/
1259{
Raymond Hettinger930f4512020-06-23 11:45:25 -07001260 double x;
1261
Benjamin Petersonce798522012-01-22 11:24:29 -05001262 _Py_IDENTIFIER(__floor__);
Guido van Rossum13e05de2007-08-23 22:56:55 +00001263
Raymond Hettinger930f4512020-06-23 11:45:25 -07001264 if (PyFloat_CheckExact(number)) {
1265 x = PyFloat_AS_DOUBLE(number);
1266 }
1267 else
1268 {
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001269 PyObject *method = _PyObject_LookupSpecial(number, &PyId___floor__);
1270 if (method != NULL) {
1271 PyObject *result = _PyObject_CallNoArg(method);
1272 Py_DECREF(method);
1273 return result;
1274 }
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001275 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 return NULL;
Raymond Hettinger930f4512020-06-23 11:45:25 -07001277 x = PyFloat_AsDouble(number);
1278 if (x == -1.0 && PyErr_Occurred())
1279 return NULL;
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001280 }
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001281 return PyLong_FromDouble(floor(x));
Guido van Rossum13e05de2007-08-23 22:56:55 +00001282}
1283
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001284FUNC1A(gamma, m_tgamma,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001285 "gamma($module, x, /)\n--\n\n"
1286 "Gamma function at x.")
Mark Dickinson05d2e082009-12-11 20:17:17 +00001287FUNC1A(lgamma, m_lgamma,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001288 "lgamma($module, x, /)\n--\n\n"
1289 "Natural logarithm of absolute value of Gamma function at x.")
Mark Dickinsonbe64d952010-07-07 16:21:29 +00001290FUNC1(log1p, m_log1p, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001291 "log1p($module, x, /)\n--\n\n"
1292 "Return the natural logarithm of 1+x (base e).\n\n"
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001293 "The result is computed in a way which is accurate for x near zero.")
Mark Dickinsona0ce3752017-04-05 18:34:27 +01001294FUNC2(remainder, m_remainder,
1295 "remainder($module, x, y, /)\n--\n\n"
1296 "Difference between x and the closest integer multiple of y.\n\n"
1297 "Return x - n*y where n*y is the closest integer multiple of y.\n"
1298 "In the case where x is exactly halfway between two multiples of\n"
1299 "y, the nearest even value of n is used. The result is always exact.")
Christian Heimes53876d92008-04-19 00:31:39 +00001300FUNC1(sin, sin, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001301 "sin($module, x, /)\n--\n\n"
1302 "Return the sine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001303FUNC1(sinh, sinh, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001304 "sinh($module, x, /)\n--\n\n"
1305 "Return the hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001306FUNC1(sqrt, sqrt, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001307 "sqrt($module, x, /)\n--\n\n"
1308 "Return the square root of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001309FUNC1(tan, tan, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001310 "tan($module, x, /)\n--\n\n"
1311 "Return the tangent of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001312FUNC1(tanh, tanh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001313 "tanh($module, x, /)\n--\n\n"
1314 "Return the hyperbolic tangent of x.")
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001315
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001316/* Precision summation function as msum() by Raymond Hettinger in
1317 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
1318 enhanced with the exact partials sum and roundoff from Mark
1319 Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
1320 See those links for more details, proofs and other references.
1321
1322 Note 1: IEEE 754R floating point semantics are assumed,
1323 but the current implementation does not re-establish special
1324 value semantics across iterations (i.e. handling -Inf + Inf).
1325
1326 Note 2: No provision is made for intermediate overflow handling;
Georg Brandlf78e02b2008-06-10 17:40:04 +00001327 therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001328 sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
1329 overflow of the first partial sum.
1330
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001331 Note 3: The intermediate values lo, yr, and hi are declared volatile so
1332 aggressive compilers won't algebraically reduce lo to always be exactly 0.0.
Georg Brandlf78e02b2008-06-10 17:40:04 +00001333 Also, the volatile declaration forces the values to be stored in memory as
1334 regular doubles instead of extended long precision (80-bit) values. This
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001335 prevents double rounding because any addition or subtraction of two doubles
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 can be resolved exactly into double-sized hi and lo values. As long as the
Georg Brandlf78e02b2008-06-10 17:40:04 +00001337 hi value gets forced into a double before yr and lo are computed, the extra
1338 bits in downstream extended precision operations (x87 for example) will be
1339 exactly zero and therefore can be losslessly stored back into a double,
1340 thereby preventing double rounding.
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001341
1342 Note 4: A similar implementation is in Modules/cmathmodule.c.
1343 Be sure to update both when making changes.
1344
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001345 Note 5: The signature of math.fsum() differs from builtins.sum()
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001346 because the start argument doesn't make sense in the context of
1347 accurate summation. Since the partials table is collapsed before
1348 returning a result, sum(seq2, start=sum(seq1)) may not equal the
1349 accurate result returned by sum(itertools.chain(seq1, seq2)).
1350*/
1351
1352#define NUM_PARTIALS 32 /* initial partials array size, on stack */
1353
1354/* Extend the partials array p[] by doubling its size. */
1355static int /* non-zero on error */
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001356_fsum_realloc(double **p_ptr, Py_ssize_t n,
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001357 double *ps, Py_ssize_t *m_ptr)
1358{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 void *v = NULL;
1360 Py_ssize_t m = *m_ptr;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 m += m; /* double */
Victor Stinner049e5092014-08-17 22:20:00 +02001363 if (n < m && (size_t)m < ((size_t)PY_SSIZE_T_MAX / sizeof(double))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 double *p = *p_ptr;
1365 if (p == ps) {
1366 v = PyMem_Malloc(sizeof(double) * m);
1367 if (v != NULL)
1368 memcpy(v, ps, sizeof(double) * n);
1369 }
1370 else
1371 v = PyMem_Realloc(p, sizeof(double) * m);
1372 }
1373 if (v == NULL) { /* size overflow or no memory */
1374 PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
1375 return 1;
1376 }
1377 *p_ptr = (double*) v;
1378 *m_ptr = m;
1379 return 0;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001380}
1381
1382/* Full precision summation of a sequence of floats.
1383
1384 def msum(iterable):
1385 partials = [] # sorted, non-overlapping partial sums
1386 for x in iterable:
Mark Dickinsonfdb0acc2010-06-25 20:22:24 +00001387 i = 0
1388 for y in partials:
1389 if abs(x) < abs(y):
1390 x, y = y, x
1391 hi = x + y
1392 lo = y - (hi - x)
1393 if lo:
1394 partials[i] = lo
1395 i += 1
1396 x = hi
1397 partials[i:] = [x]
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001398 return sum_exact(partials)
1399
1400 Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
1401 are exactly equal to x+y. The inner loop applies hi/lo summation to each
1402 partial so that the list of partial sums remains exact.
1403
1404 Sum_exact() adds the partial sums exactly and correctly rounds the final
1405 result (using the round-half-to-even rule). The items in partials remain
1406 non-zero, non-special, non-overlapping and strictly increasing in
1407 magnitude, but possibly not all having the same sign.
1408
1409 Depends on IEEE 754 arithmetic guarantees and half-even rounding.
1410*/
1411
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001412/*[clinic input]
1413math.fsum
1414
1415 seq: object
1416 /
1417
1418Return an accurate floating point sum of values in the iterable seq.
1419
1420Assumes IEEE-754 floating point arithmetic.
1421[clinic start generated code]*/
1422
1423static PyObject *
1424math_fsum(PyObject *module, PyObject *seq)
1425/*[clinic end generated code: output=ba5c672b87fe34fc input=c51b7d8caf6f6e82]*/
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 PyObject *item, *iter, *sum = NULL;
1428 Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
1429 double x, y, t, ps[NUM_PARTIALS], *p = ps;
1430 double xsave, special_sum = 0.0, inf_sum = 0.0;
1431 volatile double hi, yr, lo;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 iter = PyObject_GetIter(seq);
1434 if (iter == NULL)
1435 return NULL;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 for(;;) { /* for x in iterable */
1438 assert(0 <= n && n <= m);
1439 assert((m == NUM_PARTIALS && p == ps) ||
1440 (m > NUM_PARTIALS && p != NULL));
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 item = PyIter_Next(iter);
1443 if (item == NULL) {
1444 if (PyErr_Occurred())
1445 goto _fsum_error;
1446 break;
1447 }
Raymond Hettingercfd735e2019-01-29 20:39:53 -08001448 ASSIGN_DOUBLE(x, item, error_with_item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 Py_DECREF(item);
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 xsave = x;
1452 for (i = j = 0; j < n; j++) { /* for y in partials */
1453 y = p[j];
1454 if (fabs(x) < fabs(y)) {
1455 t = x; x = y; y = t;
1456 }
1457 hi = x + y;
1458 yr = hi - x;
1459 lo = y - yr;
1460 if (lo != 0.0)
1461 p[i++] = lo;
1462 x = hi;
1463 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 n = i; /* ps[i:] = [x] */
1466 if (x != 0.0) {
1467 if (! Py_IS_FINITE(x)) {
1468 /* a nonfinite x could arise either as
1469 a result of intermediate overflow, or
1470 as a result of a nan or inf in the
1471 summands */
1472 if (Py_IS_FINITE(xsave)) {
1473 PyErr_SetString(PyExc_OverflowError,
1474 "intermediate overflow in fsum");
1475 goto _fsum_error;
1476 }
1477 if (Py_IS_INFINITY(xsave))
1478 inf_sum += xsave;
1479 special_sum += xsave;
1480 /* reset partials */
1481 n = 0;
1482 }
1483 else if (n >= m && _fsum_realloc(&p, n, ps, &m))
1484 goto _fsum_error;
1485 else
1486 p[n++] = x;
1487 }
1488 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 if (special_sum != 0.0) {
1491 if (Py_IS_NAN(inf_sum))
1492 PyErr_SetString(PyExc_ValueError,
1493 "-inf + inf in fsum");
1494 else
1495 sum = PyFloat_FromDouble(special_sum);
1496 goto _fsum_error;
1497 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 hi = 0.0;
1500 if (n > 0) {
1501 hi = p[--n];
1502 /* sum_exact(ps, hi) from the top, stop when the sum becomes
1503 inexact. */
1504 while (n > 0) {
1505 x = hi;
1506 y = p[--n];
1507 assert(fabs(y) < fabs(x));
1508 hi = x + y;
1509 yr = hi - x;
1510 lo = y - yr;
1511 if (lo != 0.0)
1512 break;
1513 }
1514 /* Make half-even rounding work across multiple partials.
1515 Needed so that sum([1e-16, 1, 1e16]) will round-up the last
1516 digit to two instead of down to zero (the 1e-16 makes the 1
1517 slightly closer to two). With a potential 1 ULP rounding
1518 error fixed-up, math.fsum() can guarantee commutativity. */
1519 if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
1520 (lo > 0.0 && p[n-1] > 0.0))) {
1521 y = lo * 2.0;
1522 x = hi + y;
1523 yr = x - hi;
1524 if (y == yr)
1525 hi = x;
1526 }
1527 }
1528 sum = PyFloat_FromDouble(hi);
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001529
Raymond Hettingercfd735e2019-01-29 20:39:53 -08001530 _fsum_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 Py_DECREF(iter);
1532 if (p != ps)
1533 PyMem_Free(p);
1534 return sum;
Raymond Hettingercfd735e2019-01-29 20:39:53 -08001535
1536 error_with_item:
1537 Py_DECREF(item);
1538 goto _fsum_error;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001539}
1540
1541#undef NUM_PARTIALS
1542
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001543
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001544static unsigned long
1545count_set_bits(unsigned long n)
1546{
1547 unsigned long count = 0;
1548 while (n != 0) {
1549 ++count;
1550 n &= n - 1; /* clear least significant bit */
1551 }
1552 return count;
1553}
1554
Mark Dickinson73934b92019-05-18 12:29:50 +01001555/* Integer square root
1556
1557Given a nonnegative integer `n`, we want to compute the largest integer
1558`a` for which `a * a <= n`, or equivalently the integer part of the exact
1559square root of `n`.
1560
1561We use an adaptive-precision pure-integer version of Newton's iteration. Given
1562a positive integer `n`, the algorithm produces at each iteration an integer
1563approximation `a` to the square root of `n >> s` for some even integer `s`,
1564with `s` decreasing as the iterations progress. On the final iteration, `s` is
1565zero and we have an approximation to the square root of `n` itself.
1566
1567At every step, the approximation `a` is strictly within 1.0 of the true square
1568root, so we have
1569
1570 (a - 1)**2 < (n >> s) < (a + 1)**2
1571
1572After the final iteration, a check-and-correct step is needed to determine
1573whether `a` or `a - 1` gives the desired integer square root of `n`.
1574
1575The algorithm is remarkable in its simplicity. There's no need for a
1576per-iteration check-and-correct step, and termination is straightforward: the
1577number of iterations is known in advance (it's exactly `floor(log2(log2(n)))`
1578for `n > 1`). The only tricky part of the correctness proof is in establishing
1579that the bound `(a - 1)**2 < (n >> s) < (a + 1)**2` is maintained from one
1580iteration to the next. A sketch of the proof of this is given below.
1581
1582In addition to the proof sketch, a formal, computer-verified proof
1583of correctness (using Lean) of an equivalent recursive algorithm can be found
1584here:
1585
1586 https://github.com/mdickinson/snippets/blob/master/proofs/isqrt/src/isqrt.lean
1587
1588
1589Here's Python code equivalent to the C implementation below:
1590
1591 def isqrt(n):
1592 """
1593 Return the integer part of the square root of the input.
1594 """
1595 n = operator.index(n)
1596
1597 if n < 0:
1598 raise ValueError("isqrt() argument must be nonnegative")
1599 if n == 0:
1600 return 0
1601
1602 c = (n.bit_length() - 1) // 2
1603 a = 1
1604 d = 0
1605 for s in reversed(range(c.bit_length())):
Mark Dickinson2dfeaa92019-06-16 17:53:21 +01001606 # Loop invariant: (a-1)**2 < (n >> 2*(c - d)) < (a+1)**2
Mark Dickinson73934b92019-05-18 12:29:50 +01001607 e = d
1608 d = c >> s
1609 a = (a << d - e - 1) + (n >> 2*c - e - d + 1) // a
Mark Dickinson73934b92019-05-18 12:29:50 +01001610
1611 return a - (a*a > n)
1612
1613
1614Sketch of proof of correctness
1615------------------------------
1616
1617The delicate part of the correctness proof is showing that the loop invariant
1618is preserved from one iteration to the next. That is, just before the line
1619
1620 a = (a << d - e - 1) + (n >> 2*c - e - d + 1) // a
1621
1622is executed in the above code, we know that
1623
1624 (1) (a - 1)**2 < (n >> 2*(c - e)) < (a + 1)**2.
1625
1626(since `e` is always the value of `d` from the previous iteration). We must
1627prove that after that line is executed, we have
1628
1629 (a - 1)**2 < (n >> 2*(c - d)) < (a + 1)**2
1630
Min ho Kimf7d72e42019-07-06 07:39:32 +10001631To facilitate the proof, we make some changes of notation. Write `m` for
Mark Dickinson73934b92019-05-18 12:29:50 +01001632`n >> 2*(c-d)`, and write `b` for the new value of `a`, so
1633
1634 b = (a << d - e - 1) + (n >> 2*c - e - d + 1) // a
1635
1636or equivalently:
1637
1638 (2) b = (a << d - e - 1) + (m >> d - e + 1) // a
1639
1640Then we can rewrite (1) as:
1641
1642 (3) (a - 1)**2 < (m >> 2*(d - e)) < (a + 1)**2
1643
1644and we must show that (b - 1)**2 < m < (b + 1)**2.
1645
1646From this point on, we switch to mathematical notation, so `/` means exact
1647division rather than integer division and `^` is used for exponentiation. We
1648use the `√` symbol for the exact square root. In (3), we can remove the
1649implicit floor operation to give:
1650
1651 (4) (a - 1)^2 < m / 4^(d - e) < (a + 1)^2
1652
1653Taking square roots throughout (4), scaling by `2^(d-e)`, and rearranging gives
1654
1655 (5) 0 <= | 2^(d-e)a - √m | < 2^(d-e)
1656
1657Squaring and dividing through by `2^(d-e+1) a` gives
1658
1659 (6) 0 <= 2^(d-e-1) a + m / (2^(d-e+1) a) - √m < 2^(d-e-1) / a
1660
1661We'll show below that `2^(d-e-1) <= a`. Given that, we can replace the
1662right-hand side of (6) with `1`, and now replacing the central
1663term `m / (2^(d-e+1) a)` with its floor in (6) gives
1664
1665 (7) -1 < 2^(d-e-1) a + m // 2^(d-e+1) a - √m < 1
1666
1667Or equivalently, from (2):
1668
1669 (7) -1 < b - √m < 1
1670
1671and rearranging gives that `(b-1)^2 < m < (b+1)^2`, which is what we needed
1672to prove.
1673
1674We're not quite done: we still have to prove the inequality `2^(d - e - 1) <=
1675a` that was used to get line (7) above. From the definition of `c`, we have
1676`4^c <= n`, which implies
1677
1678 (8) 4^d <= m
1679
1680also, since `e == d >> 1`, `d` is at most `2e + 1`, from which it follows
1681that `2d - 2e - 1 <= d` and hence that
1682
1683 (9) 4^(2d - 2e - 1) <= m
1684
1685Dividing both sides by `4^(d - e)` gives
1686
1687 (10) 4^(d - e - 1) <= m / 4^(d - e)
1688
1689But we know from (4) that `m / 4^(d-e) < (a + 1)^2`, hence
1690
1691 (11) 4^(d - e - 1) < (a + 1)^2
1692
1693Now taking square roots of both sides and observing that both `2^(d-e-1)` and
1694`a` are integers gives `2^(d - e - 1) <= a`, which is what we needed. This
1695completes the proof sketch.
1696
1697*/
1698
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001699
1700/* Approximate square root of a large 64-bit integer.
1701
1702 Given `n` satisfying `2**62 <= n < 2**64`, return `a`
1703 satisfying `(a - 1)**2 < n < (a + 1)**2`. */
1704
1705static uint64_t
1706_approximate_isqrt(uint64_t n)
1707{
1708 uint32_t u = 1U + (n >> 62);
1709 u = (u << 1) + (n >> 59) / u;
1710 u = (u << 3) + (n >> 53) / u;
1711 u = (u << 7) + (n >> 41) / u;
1712 return (u << 15) + (n >> 17) / u;
1713}
1714
Mark Dickinson73934b92019-05-18 12:29:50 +01001715/*[clinic input]
1716math.isqrt
1717
1718 n: object
1719 /
1720
1721Return the integer part of the square root of the input.
1722[clinic start generated code]*/
1723
1724static PyObject *
1725math_isqrt(PyObject *module, PyObject *n)
1726/*[clinic end generated code: output=35a6f7f980beab26 input=5b6e7ae4fa6c43d6]*/
1727{
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001728 int a_too_large, c_bit_length;
Mark Dickinson73934b92019-05-18 12:29:50 +01001729 size_t c, d;
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001730 uint64_t m, u;
Mark Dickinson73934b92019-05-18 12:29:50 +01001731 PyObject *a = NULL, *b;
1732
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001733 n = _PyNumber_Index(n);
Mark Dickinson73934b92019-05-18 12:29:50 +01001734 if (n == NULL) {
1735 return NULL;
1736 }
1737
1738 if (_PyLong_Sign(n) < 0) {
1739 PyErr_SetString(
1740 PyExc_ValueError,
1741 "isqrt() argument must be nonnegative");
1742 goto error;
1743 }
1744 if (_PyLong_Sign(n) == 0) {
1745 Py_DECREF(n);
1746 return PyLong_FromLong(0);
1747 }
1748
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001749 /* c = (n.bit_length() - 1) // 2 */
Mark Dickinson73934b92019-05-18 12:29:50 +01001750 c = _PyLong_NumBits(n);
1751 if (c == (size_t)(-1)) {
1752 goto error;
1753 }
1754 c = (c - 1U) / 2U;
1755
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001756 /* Fast path: if c <= 31 then n < 2**64 and we can compute directly with a
1757 fast, almost branch-free algorithm. In the final correction, we use `u*u
1758 - 1 >= m` instead of the simpler `u*u > m` in order to get the correct
1759 result in the corner case where `u=2**32`. */
1760 if (c <= 31U) {
1761 m = (uint64_t)PyLong_AsUnsignedLongLong(n);
1762 Py_DECREF(n);
1763 if (m == (uint64_t)(-1) && PyErr_Occurred()) {
1764 return NULL;
1765 }
1766 u = _approximate_isqrt(m << (62U - 2U*c)) >> (31U - c);
1767 u -= u * u - 1U >= m;
1768 return PyLong_FromUnsignedLongLong((unsigned long long)u);
Mark Dickinson73934b92019-05-18 12:29:50 +01001769 }
1770
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001771 /* Slow path: n >= 2**64. We perform the first five iterations in C integer
1772 arithmetic, then switch to using Python long integers. */
1773
1774 /* From n >= 2**64 it follows that c.bit_length() >= 6. */
1775 c_bit_length = 6;
1776 while ((c >> c_bit_length) > 0U) {
1777 ++c_bit_length;
1778 }
1779
1780 /* Initialise d and a. */
1781 d = c >> (c_bit_length - 5);
1782 b = _PyLong_Rshift(n, 2U*c - 62U);
1783 if (b == NULL) {
1784 goto error;
1785 }
1786 m = (uint64_t)PyLong_AsUnsignedLongLong(b);
1787 Py_DECREF(b);
1788 if (m == (uint64_t)(-1) && PyErr_Occurred()) {
1789 goto error;
1790 }
1791 u = _approximate_isqrt(m) >> (31U - d);
1792 a = PyLong_FromUnsignedLongLong((unsigned long long)u);
Mark Dickinson73934b92019-05-18 12:29:50 +01001793 if (a == NULL) {
1794 goto error;
1795 }
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001796
1797 for (int s = c_bit_length - 6; s >= 0; --s) {
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03001798 PyObject *q;
Mark Dickinson73934b92019-05-18 12:29:50 +01001799 size_t e = d;
1800
1801 d = c >> s;
1802
1803 /* q = (n >> 2*c - e - d + 1) // a */
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03001804 q = _PyLong_Rshift(n, 2U*c - d - e + 1U);
Mark Dickinson73934b92019-05-18 12:29:50 +01001805 if (q == NULL) {
1806 goto error;
1807 }
1808 Py_SETREF(q, PyNumber_FloorDivide(q, a));
1809 if (q == NULL) {
1810 goto error;
1811 }
1812
1813 /* a = (a << d - 1 - e) + q */
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03001814 Py_SETREF(a, _PyLong_Lshift(a, d - 1U - e));
Mark Dickinson73934b92019-05-18 12:29:50 +01001815 if (a == NULL) {
1816 Py_DECREF(q);
1817 goto error;
1818 }
1819 Py_SETREF(a, PyNumber_Add(a, q));
1820 Py_DECREF(q);
1821 if (a == NULL) {
1822 goto error;
1823 }
1824 }
1825
1826 /* The correct result is either a or a - 1. Figure out which, and
1827 decrement a if necessary. */
1828
1829 /* a_too_large = n < a * a */
1830 b = PyNumber_Multiply(a, a);
1831 if (b == NULL) {
1832 goto error;
1833 }
1834 a_too_large = PyObject_RichCompareBool(n, b, Py_LT);
1835 Py_DECREF(b);
1836 if (a_too_large == -1) {
1837 goto error;
1838 }
1839
1840 if (a_too_large) {
Victor Stinner37834132020-10-27 17:12:53 +01001841 Py_SETREF(a, PyNumber_Subtract(a, _PyLong_GetOne()));
Mark Dickinson73934b92019-05-18 12:29:50 +01001842 }
1843 Py_DECREF(n);
1844 return a;
1845
1846 error:
1847 Py_XDECREF(a);
1848 Py_DECREF(n);
1849 return NULL;
1850}
1851
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001852/* Divide-and-conquer factorial algorithm
1853 *
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07001854 * Based on the formula and pseudo-code provided at:
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001855 * http://www.luschny.de/math/factorial/binarysplitfact.html
1856 *
1857 * Faster algorithms exist, but they're more complicated and depend on
Ezio Melotti9527afd2010-07-08 15:03:02 +00001858 * a fast prime factorization algorithm.
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001859 *
1860 * Notes on the algorithm
1861 * ----------------------
1862 *
1863 * factorial(n) is written in the form 2**k * m, with m odd. k and m are
1864 * computed separately, and then combined using a left shift.
1865 *
1866 * The function factorial_odd_part computes the odd part m (i.e., the greatest
1867 * odd divisor) of factorial(n), using the formula:
1868 *
1869 * factorial_odd_part(n) =
1870 *
1871 * product_{i >= 0} product_{0 < j <= n / 2**i, j odd} j
1872 *
1873 * Example: factorial_odd_part(20) =
1874 *
1875 * (1) *
1876 * (1) *
1877 * (1 * 3 * 5) *
1878 * (1 * 3 * 5 * 7 * 9)
1879 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1880 *
1881 * Here i goes from large to small: the first term corresponds to i=4 (any
1882 * larger i gives an empty product), and the last term corresponds to i=0.
1883 * Each term can be computed from the last by multiplying by the extra odd
1884 * numbers required: e.g., to get from the penultimate term to the last one,
1885 * we multiply by (11 * 13 * 15 * 17 * 19).
1886 *
1887 * To see a hint of why this formula works, here are the same numbers as above
1888 * but with the even parts (i.e., the appropriate powers of 2) included. For
1889 * each subterm in the product for i, we multiply that subterm by 2**i:
1890 *
1891 * factorial(20) =
1892 *
1893 * (16) *
1894 * (8) *
1895 * (4 * 12 * 20) *
1896 * (2 * 6 * 10 * 14 * 18) *
1897 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1898 *
1899 * The factorial_partial_product function computes the product of all odd j in
1900 * range(start, stop) for given start and stop. It's used to compute the
1901 * partial products like (11 * 13 * 15 * 17 * 19) in the example above. It
1902 * operates recursively, repeatedly splitting the range into two roughly equal
1903 * pieces until the subranges are small enough to be computed using only C
1904 * integer arithmetic.
1905 *
1906 * The two-valuation k (i.e., the exponent of the largest power of 2 dividing
1907 * the factorial) is computed independently in the main math_factorial
1908 * function. By standard results, its value is:
1909 *
1910 * two_valuation = n//2 + n//4 + n//8 + ....
1911 *
1912 * It can be shown (e.g., by complete induction on n) that two_valuation is
1913 * equal to n - count_set_bits(n), where count_set_bits(n) gives the number of
1914 * '1'-bits in the binary expansion of n.
1915 */
1916
1917/* factorial_partial_product: Compute product(range(start, stop, 2)) using
1918 * divide and conquer. Assumes start and stop are odd and stop > start.
1919 * max_bits must be >= bit_length(stop - 2). */
1920
1921static PyObject *
1922factorial_partial_product(unsigned long start, unsigned long stop,
1923 unsigned long max_bits)
1924{
1925 unsigned long midpoint, num_operands;
1926 PyObject *left = NULL, *right = NULL, *result = NULL;
1927
1928 /* If the return value will fit an unsigned long, then we can
1929 * multiply in a tight, fast loop where each multiply is O(1).
1930 * Compute an upper bound on the number of bits required to store
1931 * the answer.
1932 *
1933 * Storing some integer z requires floor(lg(z))+1 bits, which is
1934 * conveniently the value returned by bit_length(z). The
1935 * product x*y will require at most
1936 * bit_length(x) + bit_length(y) bits to store, based
1937 * on the idea that lg product = lg x + lg y.
1938 *
1939 * We know that stop - 2 is the largest number to be multiplied. From
1940 * there, we have: bit_length(answer) <= num_operands *
1941 * bit_length(stop - 2)
1942 */
1943
1944 num_operands = (stop - start) / 2;
1945 /* The "num_operands <= 8 * SIZEOF_LONG" check guards against the
1946 * unlikely case of an overflow in num_operands * max_bits. */
1947 if (num_operands <= 8 * SIZEOF_LONG &&
1948 num_operands * max_bits <= 8 * SIZEOF_LONG) {
1949 unsigned long j, total;
1950 for (total = start, j = start + 2; j < stop; j += 2)
1951 total *= j;
1952 return PyLong_FromUnsignedLong(total);
1953 }
1954
1955 /* find midpoint of range(start, stop), rounded up to next odd number. */
1956 midpoint = (start + num_operands) | 1;
1957 left = factorial_partial_product(start, midpoint,
Niklas Fiekasc5b79002020-01-16 15:09:19 +01001958 _Py_bit_length(midpoint - 2));
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001959 if (left == NULL)
1960 goto error;
1961 right = factorial_partial_product(midpoint, stop, max_bits);
1962 if (right == NULL)
1963 goto error;
1964 result = PyNumber_Multiply(left, right);
1965
1966 error:
1967 Py_XDECREF(left);
1968 Py_XDECREF(right);
1969 return result;
1970}
1971
1972/* factorial_odd_part: compute the odd part of factorial(n). */
1973
1974static PyObject *
1975factorial_odd_part(unsigned long n)
1976{
1977 long i;
1978 unsigned long v, lower, upper;
1979 PyObject *partial, *tmp, *inner, *outer;
1980
1981 inner = PyLong_FromLong(1);
1982 if (inner == NULL)
1983 return NULL;
1984 outer = inner;
1985 Py_INCREF(outer);
1986
1987 upper = 3;
Niklas Fiekasc5b79002020-01-16 15:09:19 +01001988 for (i = _Py_bit_length(n) - 2; i >= 0; i--) {
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001989 v = n >> i;
1990 if (v <= 2)
1991 continue;
1992 lower = upper;
1993 /* (v + 1) | 1 = least odd integer strictly larger than n / 2**i */
1994 upper = (v + 1) | 1;
1995 /* Here inner is the product of all odd integers j in the range (0,
1996 n/2**(i+1)]. The factorial_partial_product call below gives the
1997 product of all odd integers j in the range (n/2**(i+1), n/2**i]. */
Niklas Fiekasc5b79002020-01-16 15:09:19 +01001998 partial = factorial_partial_product(lower, upper, _Py_bit_length(upper-2));
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001999 /* inner *= partial */
2000 if (partial == NULL)
2001 goto error;
2002 tmp = PyNumber_Multiply(inner, partial);
2003 Py_DECREF(partial);
2004 if (tmp == NULL)
2005 goto error;
2006 Py_DECREF(inner);
2007 inner = tmp;
2008 /* Now inner is the product of all odd integers j in the range (0,
2009 n/2**i], giving the inner product in the formula above. */
2010
2011 /* outer *= inner; */
2012 tmp = PyNumber_Multiply(outer, inner);
2013 if (tmp == NULL)
2014 goto error;
2015 Py_DECREF(outer);
2016 outer = tmp;
2017 }
Mark Dickinson76464492012-10-25 10:46:28 +01002018 Py_DECREF(inner);
2019 return outer;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002020
2021 error:
2022 Py_DECREF(outer);
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002023 Py_DECREF(inner);
Mark Dickinson76464492012-10-25 10:46:28 +01002024 return NULL;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002025}
2026
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002027
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002028/* Lookup table for small factorial values */
2029
2030static const unsigned long SmallFactorials[] = {
2031 1, 1, 2, 6, 24, 120, 720, 5040, 40320,
2032 362880, 3628800, 39916800, 479001600,
2033#if SIZEOF_LONG >= 8
2034 6227020800, 87178291200, 1307674368000,
2035 20922789888000, 355687428096000, 6402373705728000,
2036 121645100408832000, 2432902008176640000
2037#endif
2038};
2039
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002040/*[clinic input]
2041math.factorial
2042
2043 x as arg: object
2044 /
2045
2046Find x!.
2047
2048Raise a ValueError if x is negative or non-integral.
2049[clinic start generated code]*/
2050
Barry Warsaw8b43b191996-12-09 22:32:36 +00002051static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002052math_factorial(PyObject *module, PyObject *arg)
2053/*[clinic end generated code: output=6686f26fae00e9ca input=6d1c8105c0d91fb4]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002054{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03002055 long x, two_valuation;
Mark Dickinson5990d282014-04-10 09:29:39 -04002056 int overflow;
Serhiy Storchaka578c3952020-05-26 18:43:38 +03002057 PyObject *result, *odd_part;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002058
Serhiy Storchaka578c3952020-05-26 18:43:38 +03002059 x = PyLong_AsLongAndOverflow(arg, &overflow);
Mark Dickinson5990d282014-04-10 09:29:39 -04002060 if (x == -1 && PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 return NULL;
Mark Dickinson5990d282014-04-10 09:29:39 -04002062 }
2063 else if (overflow == 1) {
2064 PyErr_Format(PyExc_OverflowError,
2065 "factorial() argument should not exceed %ld",
2066 LONG_MAX);
2067 return NULL;
2068 }
2069 else if (overflow == -1 || x < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002071 "factorial() not defined for negative values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 return NULL;
2073 }
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002074
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002075 /* use lookup table if x is small */
Victor Stinner63941882011-09-29 00:42:28 +02002076 if (x < (long)Py_ARRAY_LENGTH(SmallFactorials))
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002077 return PyLong_FromUnsignedLong(SmallFactorials[x]);
2078
2079 /* else express in the form odd_part * 2**two_valuation, and compute as
2080 odd_part << two_valuation. */
2081 odd_part = factorial_odd_part(x);
2082 if (odd_part == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03002084 two_valuation = x - count_set_bits(x);
2085 result = _PyLong_Lshift(odd_part, two_valuation);
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002086 Py_DECREF(odd_part);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 return result;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002088}
2089
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002090
2091/*[clinic input]
2092math.trunc
2093
2094 x: object
2095 /
2096
2097Truncates the Real x to the nearest Integral toward 0.
2098
2099Uses the __trunc__ magic method.
2100[clinic start generated code]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002101
2102static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002103math_trunc(PyObject *module, PyObject *x)
2104/*[clinic end generated code: output=34b9697b707e1031 input=2168b34e0a09134d]*/
Christian Heimes400adb02008-02-01 08:12:03 +00002105{
Benjamin Petersonce798522012-01-22 11:24:29 -05002106 _Py_IDENTIFIER(__trunc__);
Benjamin Petersonb0125892010-07-02 13:35:17 +00002107 PyObject *trunc, *result;
Christian Heimes400adb02008-02-01 08:12:03 +00002108
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02002109 if (PyFloat_CheckExact(x)) {
2110 return PyFloat_Type.tp_as_number->nb_int(x);
2111 }
2112
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002113 if (Py_TYPE(x)->tp_dict == NULL) {
2114 if (PyType_Ready(Py_TYPE(x)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 return NULL;
2116 }
Christian Heimes400adb02008-02-01 08:12:03 +00002117
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002118 trunc = _PyObject_LookupSpecial(x, &PyId___trunc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 if (trunc == NULL) {
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00002120 if (!PyErr_Occurred())
2121 PyErr_Format(PyExc_TypeError,
2122 "type %.100s doesn't define __trunc__ method",
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002123 Py_TYPE(x)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 return NULL;
2125 }
Victor Stinnerf17c3de2016-12-06 18:46:19 +01002126 result = _PyObject_CallNoArg(trunc);
Benjamin Petersonb0125892010-07-02 13:35:17 +00002127 Py_DECREF(trunc);
2128 return result;
Christian Heimes400adb02008-02-01 08:12:03 +00002129}
2130
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002131
2132/*[clinic input]
2133math.frexp
2134
2135 x: double
2136 /
2137
2138Return the mantissa and exponent of x, as pair (m, e).
2139
2140m is a float and e is an int, such that x = m * 2.**e.
2141If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.
2142[clinic start generated code]*/
Christian Heimes400adb02008-02-01 08:12:03 +00002143
2144static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002145math_frexp_impl(PyObject *module, double x)
2146/*[clinic end generated code: output=03e30d252a15ad4a input=96251c9e208bc6e9]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00002147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 /* deal with special cases directly, to sidestep platform
2150 differences */
2151 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
2152 i = 0;
2153 }
2154 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 x = frexp(x, &i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 }
2157 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +00002158}
2159
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002160
2161/*[clinic input]
2162math.ldexp
2163
2164 x: double
2165 i: object
2166 /
2167
2168Return x * (2**i).
2169
2170This is essentially the inverse of frexp().
2171[clinic start generated code]*/
Guido van Rossumc6e22901998-12-04 19:26:43 +00002172
Barry Warsaw8b43b191996-12-09 22:32:36 +00002173static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002174math_ldexp_impl(PyObject *module, double x, PyObject *i)
2175/*[clinic end generated code: output=b6892f3c2df9cc6a input=17d5970c1a40a8c1]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00002176{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002177 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 long exp;
2179 int overflow;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00002180
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002181 if (PyLong_Check(i)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 /* on overflow, replace exponent with either LONG_MAX
2183 or LONG_MIN, depending on the sign. */
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002184 exp = PyLong_AsLongAndOverflow(i, &overflow);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 if (exp == -1 && PyErr_Occurred())
2186 return NULL;
2187 if (overflow)
2188 exp = overflow < 0 ? LONG_MIN : LONG_MAX;
2189 }
2190 else {
2191 PyErr_SetString(PyExc_TypeError,
Serhiy Storchaka95949422013-08-27 19:40:23 +03002192 "Expected an int as second argument to ldexp.");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 return NULL;
2194 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00002195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 if (x == 0. || !Py_IS_FINITE(x)) {
2197 /* NaNs, zeros and infinities are returned unchanged */
2198 r = x;
2199 errno = 0;
2200 } else if (exp > INT_MAX) {
2201 /* overflow */
2202 r = copysign(Py_HUGE_VAL, x);
2203 errno = ERANGE;
2204 } else if (exp < INT_MIN) {
2205 /* underflow to +-0 */
2206 r = copysign(0., x);
2207 errno = 0;
2208 } else {
2209 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 r = ldexp(x, (int)exp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 if (Py_IS_INFINITY(r))
2212 errno = ERANGE;
2213 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00002214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 if (errno && is_error(r))
2216 return NULL;
2217 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +00002218}
2219
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002220
2221/*[clinic input]
2222math.modf
2223
2224 x: double
2225 /
2226
2227Return the fractional and integer parts of x.
2228
2229Both results carry the sign of x and are floats.
2230[clinic start generated code]*/
Guido van Rossumc6e22901998-12-04 19:26:43 +00002231
Barry Warsaw8b43b191996-12-09 22:32:36 +00002232static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002233math_modf_impl(PyObject *module, double x)
2234/*[clinic end generated code: output=90cee0260014c3c0 input=b4cfb6786afd9035]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00002235{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002236 double y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 /* some platforms don't do the right thing for NaNs and
2238 infinities, so we take care of special cases directly. */
2239 if (!Py_IS_FINITE(x)) {
2240 if (Py_IS_INFINITY(x))
2241 return Py_BuildValue("(dd)", copysign(0., x), x);
2242 else if (Py_IS_NAN(x))
2243 return Py_BuildValue("(dd)", x, x);
2244 }
Christian Heimesa342c012008-04-20 21:01:16 +00002245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 x = modf(x, &y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +00002249}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002250
Guido van Rossumc6e22901998-12-04 19:26:43 +00002251
Serhiy Storchaka95949422013-08-27 19:40:23 +03002252/* A decent logarithm is easy to compute even for huge ints, but libm can't
Tim Peters78526162001-09-05 00:53:45 +00002253 do that by itself -- loghelper can. func is log or log10, and name is
Serhiy Storchaka95949422013-08-27 19:40:23 +03002254 "log" or "log10". Note that overflow of the result isn't possible: an int
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002255 can contain no more than INT_MAX * SHIFT bits, so has value certainly less
2256 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 +00002257 small enough to fit in an IEEE single. log and log10 are even smaller.
Serhiy Storchaka95949422013-08-27 19:40:23 +03002258 However, intermediate overflow is possible for an int if the number of bits
2259 in that int is larger than PY_SSIZE_T_MAX. */
Tim Peters78526162001-09-05 00:53:45 +00002260
2261static PyObject*
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002262loghelper(PyObject* arg, double (*func)(double), const char *funcname)
Tim Peters78526162001-09-05 00:53:45 +00002263{
Serhiy Storchaka95949422013-08-27 19:40:23 +03002264 /* If it is int, do it ourselves. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 if (PyLong_Check(arg)) {
Mark Dickinsonc6037172010-09-29 19:06:36 +00002266 double x, result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 Py_ssize_t e;
Mark Dickinsonc6037172010-09-29 19:06:36 +00002268
2269 /* Negative or zero inputs give a ValueError. */
2270 if (Py_SIZE(arg) <= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 PyErr_SetString(PyExc_ValueError,
2272 "math domain error");
2273 return NULL;
2274 }
Mark Dickinsonfa41e602010-09-28 07:22:27 +00002275
Mark Dickinsonc6037172010-09-29 19:06:36 +00002276 x = PyLong_AsDouble(arg);
2277 if (x == -1.0 && PyErr_Occurred()) {
2278 if (!PyErr_ExceptionMatches(PyExc_OverflowError))
2279 return NULL;
2280 /* Here the conversion to double overflowed, but it's possible
2281 to compute the log anyway. Clear the exception and continue. */
2282 PyErr_Clear();
2283 x = _PyLong_Frexp((PyLongObject *)arg, &e);
2284 if (x == -1.0 && PyErr_Occurred())
2285 return NULL;
2286 /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */
2287 result = func(x) + func(2.0) * e;
2288 }
2289 else
2290 /* Successfully converted x to a double. */
2291 result = func(x);
2292 return PyFloat_FromDouble(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 }
Tim Peters78526162001-09-05 00:53:45 +00002294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 /* Else let libm handle it by itself. */
2296 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +00002297}
2298
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002299
2300/*[clinic input]
2301math.log
2302
2303 x: object
2304 [
2305 base: object(c_default="NULL") = math.e
2306 ]
2307 /
2308
2309Return the logarithm of x to the given base.
2310
2311If the base not specified, returns the natural logarithm (base e) of x.
2312[clinic start generated code]*/
2313
Tim Peters78526162001-09-05 00:53:45 +00002314static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002315math_log_impl(PyObject *module, PyObject *x, int group_right_1,
2316 PyObject *base)
2317/*[clinic end generated code: output=7b5a39e526b73fc9 input=0f62d5726cbfebbd]*/
Tim Peters78526162001-09-05 00:53:45 +00002318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 PyObject *num, *den;
2320 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +00002321
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002322 num = loghelper(x, m_log, "log");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 if (num == NULL || base == NULL)
2324 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +00002325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 den = loghelper(base, m_log, "log");
2327 if (den == NULL) {
2328 Py_DECREF(num);
2329 return NULL;
2330 }
Raymond Hettinger866964c2002-12-14 19:51:34 +00002331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 ans = PyNumber_TrueDivide(num, den);
2333 Py_DECREF(num);
2334 Py_DECREF(den);
2335 return ans;
Tim Peters78526162001-09-05 00:53:45 +00002336}
2337
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002338
2339/*[clinic input]
2340math.log2
2341
2342 x: object
2343 /
2344
2345Return the base 2 logarithm of x.
2346[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002347
2348static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002349math_log2(PyObject *module, PyObject *x)
2350/*[clinic end generated code: output=5425899a4d5d6acb input=08321262bae4f39b]*/
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02002351{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002352 return loghelper(x, m_log2, "log2");
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02002353}
2354
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002355
2356/*[clinic input]
2357math.log10
2358
2359 x: object
2360 /
2361
2362Return the base 10 logarithm of x.
2363[clinic start generated code]*/
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02002364
2365static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002366math_log10(PyObject *module, PyObject *x)
2367/*[clinic end generated code: output=be72a64617df9c6f input=b2469d02c6469e53]*/
Tim Peters78526162001-09-05 00:53:45 +00002368{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002369 return loghelper(x, m_log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +00002370}
2371
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002372
2373/*[clinic input]
2374math.fmod
2375
2376 x: double
2377 y: double
2378 /
2379
2380Return fmod(x, y), according to platform C.
2381
2382x % y may differ.
2383[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002384
Christian Heimes53876d92008-04-19 00:31:39 +00002385static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002386math_fmod_impl(PyObject *module, double x, double y)
2387/*[clinic end generated code: output=7559d794343a27b5 input=4f84caa8cfc26a03]*/
Christian Heimes53876d92008-04-19 00:31:39 +00002388{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002389 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 /* fmod(x, +/-Inf) returns x for finite x. */
2391 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
2392 return PyFloat_FromDouble(x);
2393 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 r = fmod(x, y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 if (Py_IS_NAN(r)) {
2396 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
2397 errno = EDOM;
2398 else
2399 errno = 0;
2400 }
2401 if (errno && is_error(r))
2402 return NULL;
2403 else
2404 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00002405}
2406
Raymond Hettinger13990742018-08-11 11:26:36 -07002407/*
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002408Given a *vec* of values, compute the vector norm:
Raymond Hettinger13990742018-08-11 11:26:36 -07002409
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002410 sqrt(sum(x ** 2 for x in vec))
Raymond Hettingerfff3c282020-08-15 19:38:19 -07002411
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002412The *max* variable should be equal to the largest fabs(x).
2413The *n* variable is the length of *vec*.
2414If n==0, then *max* should be 0.0.
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002415If an infinity is present in the vec, *max* should be INF.
Raymond Hettingerc630e102018-08-11 18:39:05 -07002416The *found_nan* variable indicates whether some member of
2417the *vec* is a NaN.
Raymond Hettinger21786f52018-08-28 22:47:24 -07002418
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002419To avoid overflow/underflow and to achieve high accuracy giving results
2420that are almost always correctly rounded, four techniques are used:
Raymond Hettinger21786f52018-08-28 22:47:24 -07002421
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002422* lossless scaling using a power-of-two scaling factor
Raymond Hettinger67c998d2020-09-06 15:10:07 -07002423* accurate squaring using Veltkamp-Dekker splitting [1]
2424* compensated summation using a variant of the Neumaier algorithm [2]
2425* differential correction of the square root [3]
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002426
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002427The usual presentation of the Neumaier summation algorithm has an
2428expensive branch depending on which operand has the larger
2429magnitude. We avoid this cost by arranging the calculation so that
2430fabs(csum) is always as large as fabs(x).
Raymond Hettinger21786f52018-08-28 22:47:24 -07002431
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002432To establish the invariant, *csum* is initialized to 1.0 which is
Raymond Hettinger457d4e92020-09-13 23:33:41 -07002433always larger than x**2 after scaling or after division by *max*.
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002434After the loop is finished, the initial 1.0 is subtracted out for a
2435net zero effect on the final sum. Since *csum* will be greater than
24361.0, the subtraction of 1.0 will not cause fractional digits to be
2437dropped from *csum*.
2438
2439To get the full benefit from compensated summation, the largest
2440addend should be in the range: 0.5 <= |x| <= 1.0. Accordingly,
2441scaling or division by *max* should not be skipped even if not
2442otherwise needed to prevent overflow or loss of precision.
2443
Raymond Hettinger82e79482020-08-26 13:09:40 -07002444The assertion that hi*hi <= 1.0 is a bit subtle. Each vector element
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002445gets scaled to a magnitude below 1.0. The Veltkamp-Dekker splitting
2446algorithm gives a *hi* value that is correctly rounded to half
2447precision. When a value at or below 1.0 is correctly rounded, it
2448never goes above 1.0. And when values at or below 1.0 are squared,
2449they remain at or below 1.0, thus preserving the summation invariant.
2450
Raymond Hettinger27de2862020-08-29 09:11:04 -07002451Another interesting assertion is that csum+lo*lo == csum. In the loop,
2452each scaled vector element has a magnitude less than 1.0. After the
2453Veltkamp split, *lo* has a maximum value of 2**-27. So the maximum
2454value of *lo* squared is 2**-54. The value of ulp(1.0)/2.0 is 2**-53.
2455Given that csum >= 1.0, we have:
2456 lo**2 <= 2**-54 < 2**-53 == 1/2*ulp(1.0) <= ulp(csum)/2
2457Since lo**2 is less than 1/2 ulp(csum), we have csum+lo*lo == csum.
2458
Raymond Hettinger92c38162020-08-30 10:00:11 -07002459To minimize loss of information during the accumulation of fractional
Raymond Hettinger67c998d2020-09-06 15:10:07 -07002460values, each term has a separate accumulator. This also breaks up
2461sequential dependencies in the inner loop so the CPU can maximize
Raymond Hettinger457d4e92020-09-13 23:33:41 -07002462floating point throughput. [4] On a 2.6 GHz Haswell, adding one
Raymond Hettinger67c998d2020-09-06 15:10:07 -07002463dimension has an incremental cost of only 5ns -- for example when
2464moving from hypot(x,y) to hypot(x,y,z).
Raymond Hettinger92c38162020-08-30 10:00:11 -07002465
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002466The square root differential correction is needed because a
2467correctly rounded square root of a correctly rounded sum of
2468squares can still be off by as much as one ulp.
2469
2470The differential correction starts with a value *x* that is
2471the difference between the square of *h*, the possibly inaccurately
2472rounded square root, and the accurately computed sum of squares.
2473The correction is the first order term of the Maclaurin series
Raymond Hettinger457d4e92020-09-13 23:33:41 -07002474expansion of sqrt(h**2 + x) == h + x/(2*h) + O(x**2). [5]
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002475
2476Essentially, this differential correction is equivalent to one
Raymond Hettinger82e79482020-08-26 13:09:40 -07002477refinement step in Newton's divide-and-average square root
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002478algorithm, effectively doubling the number of accurate bits.
2479This technique is used in Dekker's SQRT2 algorithm and again in
2480Borges' ALGORITHM 4 and 5.
2481
Raymond Hettinger67c998d2020-09-06 15:10:07 -07002482Without proof for all cases, hypot() cannot claim to be always
2483correctly rounded. However for n <= 1000, prior to the final addition
2484that rounds the overall result, the internal accuracy of "h" together
2485with its correction of "x / (2.0 * h)" is at least 100 bits. [6]
2486Also, hypot() was tested against a Decimal implementation with
2487prec=300. After 100 million trials, no incorrectly rounded examples
2488were found. In addition, perfect commutativity (all permutations are
2489exactly equal) was verified for 1 billion random inputs with n=5. [7]
2490
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002491References:
2492
24931. Veltkamp-Dekker splitting: http://csclub.uwaterloo.ca/~pbarfuss/dekker1971.pdf
24942. Compensated summation: http://www.ti3.tu-harburg.de/paper/rump/Ru08b.pdf
Raymond Hettinger92c38162020-08-30 10:00:11 -070024953. Square root differential correction: https://arxiv.org/pdf/1904.09481.pdf
Raymond Hettinger457d4e92020-09-13 23:33:41 -070024964. Data dependency graph: https://bugs.python.org/file49439/hypot.png
24975. https://www.wolframalpha.com/input/?i=Maclaurin+series+sqrt%28h**2+%2B+x%29+at+x%3D0
Raymond Hettinger497126f2020-10-01 19:30:54 -070024986. Analysis of internal accuracy: https://bugs.python.org/file49484/best_frac.py
Raymond Hettinger457d4e92020-09-13 23:33:41 -070024997. Commutativity test: https://bugs.python.org/file49448/test_hypot_commutativity.py
Raymond Hettingerfff3c282020-08-15 19:38:19 -07002500
Raymond Hettinger13990742018-08-11 11:26:36 -07002501*/
2502
2503static inline double
Raymond Hettingerc630e102018-08-11 18:39:05 -07002504vector_norm(Py_ssize_t n, double *vec, double max, int found_nan)
Raymond Hettinger13990742018-08-11 11:26:36 -07002505{
Raymond Hettinger438e9fc2020-09-22 20:01:12 -07002506 const double T27 = 134217729.0; /* ldexp(1.0, 27) + 1.0) */
2507 double x, scale, oldcsum, csum = 1.0, frac1 = 0.0, frac2 = 0.0, frac3 = 0.0;
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002508 double t, hi, lo, h;
Raymond Hettingerfff3c282020-08-15 19:38:19 -07002509 int max_e;
Raymond Hettinger13990742018-08-11 11:26:36 -07002510 Py_ssize_t i;
2511
Raymond Hettingerc630e102018-08-11 18:39:05 -07002512 if (Py_IS_INFINITY(max)) {
2513 return max;
2514 }
2515 if (found_nan) {
2516 return Py_NAN;
2517 }
Raymond Hettingerf3267142018-09-02 13:34:21 -07002518 if (max == 0.0 || n <= 1) {
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002519 return max;
Raymond Hettinger13990742018-08-11 11:26:36 -07002520 }
Raymond Hettingerfff3c282020-08-15 19:38:19 -07002521 frexp(max, &max_e);
2522 if (max_e >= -1023) {
2523 scale = ldexp(1.0, -max_e);
2524 assert(max * scale >= 0.5);
2525 assert(max * scale < 1.0);
2526 for (i=0 ; i < n ; i++) {
2527 x = vec[i];
2528 assert(Py_IS_FINITE(x) && fabs(x) <= max);
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002529
Raymond Hettingerfff3c282020-08-15 19:38:19 -07002530 x *= scale;
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002531 assert(fabs(x) < 1.0);
2532
2533 t = x * T27;
2534 hi = t - (t - x);
2535 lo = x - hi;
2536 assert(hi + lo == x);
2537
2538 x = hi * hi;
Raymond Hettingerfff3c282020-08-15 19:38:19 -07002539 assert(x <= 1.0);
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002540 assert(fabs(csum) >= fabs(x));
2541 oldcsum = csum;
2542 csum += x;
Raymond Hettinger438e9fc2020-09-22 20:01:12 -07002543 frac1 += (oldcsum - csum) + x;
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002544
2545 x = 2.0 * hi * lo;
2546 assert(fabs(csum) >= fabs(x));
2547 oldcsum = csum;
2548 csum += x;
Raymond Hettinger438e9fc2020-09-22 20:01:12 -07002549 frac2 += (oldcsum - csum) + x;
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002550
Raymond Hettinger27de2862020-08-29 09:11:04 -07002551 assert(csum + lo * lo == csum);
Raymond Hettinger438e9fc2020-09-22 20:01:12 -07002552 frac3 += lo * lo;
Raymond Hettingerfff3c282020-08-15 19:38:19 -07002553 }
Raymond Hettinger438e9fc2020-09-22 20:01:12 -07002554 h = sqrt(csum - 1.0 + (frac1 + frac2 + frac3));
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002555
2556 x = h;
2557 t = x * T27;
2558 hi = t - (t - x);
2559 lo = x - hi;
2560 assert (hi + lo == x);
2561
2562 x = -hi * hi;
2563 assert(fabs(csum) >= fabs(x));
2564 oldcsum = csum;
2565 csum += x;
Raymond Hettinger438e9fc2020-09-22 20:01:12 -07002566 frac1 += (oldcsum - csum) + x;
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002567
2568 x = -2.0 * hi * lo;
2569 assert(fabs(csum) >= fabs(x));
2570 oldcsum = csum;
2571 csum += x;
Raymond Hettinger438e9fc2020-09-22 20:01:12 -07002572 frac2 += (oldcsum - csum) + x;
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002573
2574 x = -lo * lo;
2575 assert(fabs(csum) >= fabs(x));
2576 oldcsum = csum;
2577 csum += x;
Raymond Hettinger438e9fc2020-09-22 20:01:12 -07002578 frac3 += (oldcsum - csum) + x;
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002579
Raymond Hettinger438e9fc2020-09-22 20:01:12 -07002580 x = csum - 1.0 + (frac1 + frac2 + frac3);
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002581 return (h + x / (2.0 * h)) / scale;
Raymond Hettingerfff3c282020-08-15 19:38:19 -07002582 }
2583 /* When max_e < -1023, ldexp(1.0, -max_e) overflows.
2584 So instead of multiplying by a scale, we just divide by *max*.
2585 */
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002586 for (i=0 ; i < n ; i++) {
Raymond Hettinger13990742018-08-11 11:26:36 -07002587 x = vec[i];
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002588 assert(Py_IS_FINITE(x) && fabs(x) <= max);
Raymond Hettinger13990742018-08-11 11:26:36 -07002589 x /= max;
Raymond Hettinger21786f52018-08-28 22:47:24 -07002590 x = x*x;
Raymond Hettingerfff3c282020-08-15 19:38:19 -07002591 assert(x <= 1.0);
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002592 assert(fabs(csum) >= fabs(x));
Raymond Hettinger13990742018-08-11 11:26:36 -07002593 oldcsum = csum;
2594 csum += x;
Raymond Hettinger438e9fc2020-09-22 20:01:12 -07002595 frac1 += (oldcsum - csum) + x;
Raymond Hettinger13990742018-08-11 11:26:36 -07002596 }
Raymond Hettinger438e9fc2020-09-22 20:01:12 -07002597 return max * sqrt(csum - 1.0 + frac1);
Raymond Hettinger13990742018-08-11 11:26:36 -07002598}
2599
Raymond Hettingerc630e102018-08-11 18:39:05 -07002600#define NUM_STACK_ELEMS 16
2601
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002602/*[clinic input]
2603math.dist
2604
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002605 p: object
2606 q: object
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002607 /
2608
2609Return the Euclidean distance between two points p and q.
2610
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002611The points should be specified as sequences (or iterables) of
2612coordinates. Both inputs must have the same dimension.
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002613
2614Roughly equivalent to:
2615 sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
2616[clinic start generated code]*/
2617
2618static PyObject *
2619math_dist_impl(PyObject *module, PyObject *p, PyObject *q)
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002620/*[clinic end generated code: output=56bd9538d06bbcfe input=74e85e1b6092e68e]*/
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002621{
2622 PyObject *item;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002623 double max = 0.0;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002624 double x, px, qx, result;
2625 Py_ssize_t i, m, n;
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002626 int found_nan = 0, p_allocated = 0, q_allocated = 0;
Raymond Hettingerc630e102018-08-11 18:39:05 -07002627 double diffs_on_stack[NUM_STACK_ELEMS];
2628 double *diffs = diffs_on_stack;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002629
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002630 if (!PyTuple_Check(p)) {
2631 p = PySequence_Tuple(p);
2632 if (p == NULL) {
2633 return NULL;
2634 }
2635 p_allocated = 1;
2636 }
2637 if (!PyTuple_Check(q)) {
2638 q = PySequence_Tuple(q);
2639 if (q == NULL) {
2640 if (p_allocated) {
2641 Py_DECREF(p);
2642 }
2643 return NULL;
2644 }
2645 q_allocated = 1;
2646 }
2647
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002648 m = PyTuple_GET_SIZE(p);
2649 n = PyTuple_GET_SIZE(q);
2650 if (m != n) {
2651 PyErr_SetString(PyExc_ValueError,
2652 "both points must have the same number of dimensions");
2653 return NULL;
2654
2655 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002656 if (n > NUM_STACK_ELEMS) {
2657 diffs = (double *) PyObject_Malloc(n * sizeof(double));
2658 if (diffs == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07002659 return PyErr_NoMemory();
Raymond Hettingerc630e102018-08-11 18:39:05 -07002660 }
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002661 }
2662 for (i=0 ; i<n ; i++) {
2663 item = PyTuple_GET_ITEM(p, i);
Raymond Hettingercfd735e2019-01-29 20:39:53 -08002664 ASSIGN_DOUBLE(px, item, error_exit);
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002665 item = PyTuple_GET_ITEM(q, i);
Raymond Hettingercfd735e2019-01-29 20:39:53 -08002666 ASSIGN_DOUBLE(qx, item, error_exit);
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002667 x = fabs(px - qx);
2668 diffs[i] = x;
2669 found_nan |= Py_IS_NAN(x);
2670 if (x > max) {
2671 max = x;
2672 }
2673 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002674 result = vector_norm(n, diffs, max, found_nan);
2675 if (diffs != diffs_on_stack) {
2676 PyObject_Free(diffs);
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002677 }
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002678 if (p_allocated) {
2679 Py_DECREF(p);
2680 }
2681 if (q_allocated) {
2682 Py_DECREF(q);
2683 }
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002684 return PyFloat_FromDouble(result);
Raymond Hettingerc630e102018-08-11 18:39:05 -07002685
2686 error_exit:
2687 if (diffs != diffs_on_stack) {
2688 PyObject_Free(diffs);
2689 }
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002690 if (p_allocated) {
2691 Py_DECREF(p);
2692 }
2693 if (q_allocated) {
2694 Py_DECREF(q);
2695 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002696 return NULL;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002697}
2698
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002699/* AC: cannot convert yet, waiting for *args support */
Christian Heimes53876d92008-04-19 00:31:39 +00002700static PyObject *
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002701math_hypot(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Christian Heimes53876d92008-04-19 00:31:39 +00002702{
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002703 Py_ssize_t i;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002704 PyObject *item;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002705 double max = 0.0;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002706 double x, result;
2707 int found_nan = 0;
Raymond Hettingerc630e102018-08-11 18:39:05 -07002708 double coord_on_stack[NUM_STACK_ELEMS];
2709 double *coordinates = coord_on_stack;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002710
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002711 if (nargs > NUM_STACK_ELEMS) {
2712 coordinates = (double *) PyObject_Malloc(nargs * sizeof(double));
Zackery Spytz4c49da02018-12-07 03:11:30 -07002713 if (coordinates == NULL) {
2714 return PyErr_NoMemory();
2715 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002716 }
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002717 for (i = 0; i < nargs; i++) {
2718 item = args[i];
Raymond Hettingercfd735e2019-01-29 20:39:53 -08002719 ASSIGN_DOUBLE(x, item, error_exit);
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002720 x = fabs(x);
2721 coordinates[i] = x;
2722 found_nan |= Py_IS_NAN(x);
2723 if (x > max) {
2724 max = x;
2725 }
2726 }
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002727 result = vector_norm(nargs, coordinates, max, found_nan);
Raymond Hettingerc630e102018-08-11 18:39:05 -07002728 if (coordinates != coord_on_stack) {
2729 PyObject_Free(coordinates);
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002730 }
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002731 return PyFloat_FromDouble(result);
Raymond Hettingerc630e102018-08-11 18:39:05 -07002732
2733 error_exit:
2734 if (coordinates != coord_on_stack) {
2735 PyObject_Free(coordinates);
2736 }
2737 return NULL;
Christian Heimes53876d92008-04-19 00:31:39 +00002738}
2739
Raymond Hettingerc630e102018-08-11 18:39:05 -07002740#undef NUM_STACK_ELEMS
2741
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002742PyDoc_STRVAR(math_hypot_doc,
2743 "hypot(*coordinates) -> value\n\n\
2744Multidimensional Euclidean distance from the origin to a point.\n\
2745\n\
2746Roughly equivalent to:\n\
2747 sqrt(sum(x**2 for x in coordinates))\n\
2748\n\
2749For a two dimensional point (x, y), gives the hypotenuse\n\
2750using the Pythagorean theorem: sqrt(x*x + y*y).\n\
2751\n\
2752For example, the hypotenuse of a 3/4/5 right triangle is:\n\
2753\n\
2754 >>> hypot(3.0, 4.0)\n\
2755 5.0\n\
2756");
Christian Heimes53876d92008-04-19 00:31:39 +00002757
2758/* pow can't use math_2, but needs its own wrapper: the problem is
2759 that an infinite result can arise either as a result of overflow
2760 (in which case OverflowError should be raised) or as a result of
2761 e.g. 0.**-5. (for which ValueError needs to be raised.)
2762*/
2763
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002764/*[clinic input]
2765math.pow
Christian Heimes53876d92008-04-19 00:31:39 +00002766
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002767 x: double
2768 y: double
2769 /
2770
2771Return x**y (x to the power of y).
2772[clinic start generated code]*/
2773
2774static PyObject *
2775math_pow_impl(PyObject *module, double x, double y)
2776/*[clinic end generated code: output=fff93e65abccd6b0 input=c26f1f6075088bfd]*/
2777{
2778 double r;
2779 int odd_y;
Christian Heimesa342c012008-04-20 21:01:16 +00002780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 /* deal directly with IEEE specials, to cope with problems on various
2782 platforms whose semantics don't exactly match C99 */
2783 r = 0.; /* silence compiler warning */
2784 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
2785 errno = 0;
2786 if (Py_IS_NAN(x))
2787 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
2788 else if (Py_IS_NAN(y))
2789 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
2790 else if (Py_IS_INFINITY(x)) {
2791 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
2792 if (y > 0.)
2793 r = odd_y ? x : fabs(x);
2794 else if (y == 0.)
2795 r = 1.;
2796 else /* y < 0. */
2797 r = odd_y ? copysign(0., x) : 0.;
2798 }
2799 else if (Py_IS_INFINITY(y)) {
2800 if (fabs(x) == 1.0)
2801 r = 1.;
2802 else if (y > 0. && fabs(x) > 1.0)
2803 r = y;
2804 else if (y < 0. && fabs(x) < 1.0) {
2805 r = -y; /* result is +inf */
2806 if (x == 0.) /* 0**-inf: divide-by-zero */
2807 errno = EDOM;
2808 }
2809 else
2810 r = 0.;
2811 }
2812 }
2813 else {
2814 /* let libm handle finite**finite */
2815 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002816 r = pow(x, y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002817 /* a NaN result should arise only from (-ve)**(finite
2818 non-integer); in this case we want to raise ValueError. */
2819 if (!Py_IS_FINITE(r)) {
2820 if (Py_IS_NAN(r)) {
2821 errno = EDOM;
2822 }
2823 /*
2824 an infinite result here arises either from:
2825 (A) (+/-0.)**negative (-> divide-by-zero)
2826 (B) overflow of x**y with x and y finite
2827 */
2828 else if (Py_IS_INFINITY(r)) {
2829 if (x == 0.)
2830 errno = EDOM;
2831 else
2832 errno = ERANGE;
2833 }
2834 }
2835 }
Christian Heimes53876d92008-04-19 00:31:39 +00002836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002837 if (errno && is_error(r))
2838 return NULL;
2839 else
2840 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00002841}
2842
Christian Heimes53876d92008-04-19 00:31:39 +00002843
Christian Heimes072c0f12008-01-03 23:01:04 +00002844static const double degToRad = Py_MATH_PI / 180.0;
2845static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002846
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002847/*[clinic input]
2848math.degrees
2849
2850 x: double
2851 /
2852
2853Convert angle x from radians to degrees.
2854[clinic start generated code]*/
2855
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002856static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002857math_degrees_impl(PyObject *module, double x)
2858/*[clinic end generated code: output=7fea78b294acd12f input=81e016555d6e3660]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002859{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002860 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002861}
2862
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002863
2864/*[clinic input]
2865math.radians
2866
2867 x: double
2868 /
2869
2870Convert angle x from degrees to radians.
2871[clinic start generated code]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002872
2873static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002874math_radians_impl(PyObject *module, double x)
2875/*[clinic end generated code: output=34daa47caf9b1590 input=91626fc489fe3d63]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002876{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002877 return PyFloat_FromDouble(x * degToRad);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002878}
2879
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002880
2881/*[clinic input]
2882math.isfinite
2883
2884 x: double
2885 /
2886
2887Return True if x is neither an infinity nor a NaN, and False otherwise.
2888[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002889
Christian Heimes072c0f12008-01-03 23:01:04 +00002890static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002891math_isfinite_impl(PyObject *module, double x)
2892/*[clinic end generated code: output=8ba1f396440c9901 input=46967d254812e54a]*/
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002893{
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002894 return PyBool_FromLong((long)Py_IS_FINITE(x));
2895}
2896
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002897
2898/*[clinic input]
2899math.isnan
2900
2901 x: double
2902 /
2903
2904Return True if x is a NaN (not a number), and False otherwise.
2905[clinic start generated code]*/
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002906
2907static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002908math_isnan_impl(PyObject *module, double x)
2909/*[clinic end generated code: output=f537b4d6df878c3e input=935891e66083f46a]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00002912}
2913
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002914
2915/*[clinic input]
2916math.isinf
2917
2918 x: double
2919 /
2920
2921Return True if x is a positive or negative infinity, and False otherwise.
2922[clinic start generated code]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002923
2924static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002925math_isinf_impl(PyObject *module, double x)
2926/*[clinic end generated code: output=9f00cbec4de7b06b input=32630e4212cf961f]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002927{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002928 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00002929}
2930
Christian Heimes072c0f12008-01-03 23:01:04 +00002931
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002932/*[clinic input]
2933math.isclose -> bool
2934
2935 a: double
2936 b: double
2937 *
2938 rel_tol: double = 1e-09
2939 maximum difference for being considered "close", relative to the
2940 magnitude of the input values
2941 abs_tol: double = 0.0
2942 maximum difference for being considered "close", regardless of the
2943 magnitude of the input values
2944
2945Determine whether two floating point numbers are close in value.
2946
2947Return True if a is close in value to b, and False otherwise.
2948
2949For the values to be considered close, the difference between them
2950must be smaller than at least one of the tolerances.
2951
2952-inf, inf and NaN behave similarly to the IEEE 754 Standard. That
2953is, NaN is not close to anything, even itself. inf and -inf are
2954only close to themselves.
2955[clinic start generated code]*/
2956
2957static int
2958math_isclose_impl(PyObject *module, double a, double b, double rel_tol,
2959 double abs_tol)
2960/*[clinic end generated code: output=b73070207511952d input=f28671871ea5bfba]*/
Tal Einatd5519ed2015-05-31 22:05:00 +03002961{
Tal Einatd5519ed2015-05-31 22:05:00 +03002962 double diff = 0.0;
Tal Einatd5519ed2015-05-31 22:05:00 +03002963
2964 /* sanity check on the inputs */
2965 if (rel_tol < 0.0 || abs_tol < 0.0 ) {
2966 PyErr_SetString(PyExc_ValueError,
2967 "tolerances must be non-negative");
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002968 return -1;
Tal Einatd5519ed2015-05-31 22:05:00 +03002969 }
2970
2971 if ( a == b ) {
2972 /* short circuit exact equality -- needed to catch two infinities of
2973 the same sign. And perhaps speeds things up a bit sometimes.
2974 */
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002975 return 1;
Tal Einatd5519ed2015-05-31 22:05:00 +03002976 }
2977
2978 /* This catches the case of two infinities of opposite sign, or
2979 one infinity and one finite number. Two infinities of opposite
2980 sign would otherwise have an infinite relative tolerance.
2981 Two infinities of the same sign are caught by the equality check
2982 above.
2983 */
2984
2985 if (Py_IS_INFINITY(a) || Py_IS_INFINITY(b)) {
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002986 return 0;
Tal Einatd5519ed2015-05-31 22:05:00 +03002987 }
2988
2989 /* now do the regular computation
2990 this is essentially the "weak" test from the Boost library
2991 */
2992
2993 diff = fabs(b - a);
2994
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002995 return (((diff <= fabs(rel_tol * b)) ||
2996 (diff <= fabs(rel_tol * a))) ||
2997 (diff <= abs_tol));
Tal Einatd5519ed2015-05-31 22:05:00 +03002998}
2999
Pablo Galindo04114112019-03-09 19:18:08 +00003000static inline int
3001_check_long_mult_overflow(long a, long b) {
3002
3003 /* From Python2's int_mul code:
3004
3005 Integer overflow checking for * is painful: Python tried a couple ways, but
3006 they didn't work on all platforms, or failed in endcases (a product of
3007 -sys.maxint-1 has been a particular pain).
3008
3009 Here's another way:
3010
3011 The native long product x*y is either exactly right or *way* off, being
3012 just the last n bits of the true product, where n is the number of bits
3013 in a long (the delivered product is the true product plus i*2**n for
3014 some integer i).
3015
3016 The native double product (double)x * (double)y is subject to three
3017 rounding errors: on a sizeof(long)==8 box, each cast to double can lose
3018 info, and even on a sizeof(long)==4 box, the multiplication can lose info.
3019 But, unlike the native long product, it's not in *range* trouble: even
3020 if sizeof(long)==32 (256-bit longs), the product easily fits in the
3021 dynamic range of a double. So the leading 50 (or so) bits of the double
3022 product are correct.
3023
3024 We check these two ways against each other, and declare victory if they're
3025 approximately the same. Else, because the native long product is the only
3026 one that can lose catastrophic amounts of information, it's the native long
3027 product that must have overflowed.
3028
3029 */
3030
3031 long longprod = (long)((unsigned long)a * b);
3032 double doubleprod = (double)a * (double)b;
3033 double doubled_longprod = (double)longprod;
3034
3035 if (doubled_longprod == doubleprod) {
3036 return 0;
3037 }
3038
3039 const double diff = doubled_longprod - doubleprod;
3040 const double absdiff = diff >= 0.0 ? diff : -diff;
3041 const double absprod = doubleprod >= 0.0 ? doubleprod : -doubleprod;
3042
3043 if (32.0 * absdiff <= absprod) {
3044 return 0;
3045 }
3046
3047 return 1;
3048}
Tal Einatd5519ed2015-05-31 22:05:00 +03003049
Pablo Galindobc098512019-02-07 07:04:02 +00003050/*[clinic input]
3051math.prod
3052
3053 iterable: object
3054 /
3055 *
3056 start: object(c_default="NULL") = 1
3057
3058Calculate the product of all the elements in the input iterable.
3059
3060The default start value for the product is 1.
3061
3062When the iterable is empty, return the start value. This function is
3063intended specifically for use with numeric values and may reject
3064non-numeric types.
3065[clinic start generated code]*/
3066
3067static PyObject *
3068math_prod_impl(PyObject *module, PyObject *iterable, PyObject *start)
3069/*[clinic end generated code: output=36153bedac74a198 input=4c5ab0682782ed54]*/
3070{
3071 PyObject *result = start;
3072 PyObject *temp, *item, *iter;
3073
3074 iter = PyObject_GetIter(iterable);
3075 if (iter == NULL) {
3076 return NULL;
3077 }
3078
3079 if (result == NULL) {
3080 result = PyLong_FromLong(1);
3081 if (result == NULL) {
3082 Py_DECREF(iter);
3083 return NULL;
3084 }
3085 } else {
3086 Py_INCREF(result);
3087 }
3088#ifndef SLOW_PROD
3089 /* Fast paths for integers keeping temporary products in C.
3090 * Assumes all inputs are the same type.
3091 * If the assumption fails, default to use PyObjects instead.
3092 */
3093 if (PyLong_CheckExact(result)) {
3094 int overflow;
3095 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
3096 /* If this already overflowed, don't even enter the loop. */
3097 if (overflow == 0) {
3098 Py_DECREF(result);
3099 result = NULL;
3100 }
3101 /* Loop over all the items in the iterable until we finish, we overflow
3102 * or we found a non integer element */
3103 while(result == NULL) {
3104 item = PyIter_Next(iter);
3105 if (item == NULL) {
3106 Py_DECREF(iter);
3107 if (PyErr_Occurred()) {
3108 return NULL;
3109 }
3110 return PyLong_FromLong(i_result);
3111 }
3112 if (PyLong_CheckExact(item)) {
3113 long b = PyLong_AsLongAndOverflow(item, &overflow);
Pablo Galindo04114112019-03-09 19:18:08 +00003114 if (overflow == 0 && !_check_long_mult_overflow(i_result, b)) {
3115 long x = i_result * b;
Pablo Galindobc098512019-02-07 07:04:02 +00003116 i_result = x;
3117 Py_DECREF(item);
3118 continue;
3119 }
3120 }
3121 /* Either overflowed or is not an int.
3122 * Restore real objects and process normally */
3123 result = PyLong_FromLong(i_result);
3124 if (result == NULL) {
3125 Py_DECREF(item);
3126 Py_DECREF(iter);
3127 return NULL;
3128 }
3129 temp = PyNumber_Multiply(result, item);
3130 Py_DECREF(result);
3131 Py_DECREF(item);
3132 result = temp;
3133 if (result == NULL) {
3134 Py_DECREF(iter);
3135 return NULL;
3136 }
3137 }
3138 }
3139
3140 /* Fast paths for floats keeping temporary products in C.
3141 * Assumes all inputs are the same type.
3142 * If the assumption fails, default to use PyObjects instead.
3143 */
3144 if (PyFloat_CheckExact(result)) {
3145 double f_result = PyFloat_AS_DOUBLE(result);
3146 Py_DECREF(result);
3147 result = NULL;
3148 while(result == NULL) {
3149 item = PyIter_Next(iter);
3150 if (item == NULL) {
3151 Py_DECREF(iter);
3152 if (PyErr_Occurred()) {
3153 return NULL;
3154 }
3155 return PyFloat_FromDouble(f_result);
3156 }
3157 if (PyFloat_CheckExact(item)) {
3158 f_result *= PyFloat_AS_DOUBLE(item);
3159 Py_DECREF(item);
3160 continue;
3161 }
3162 if (PyLong_CheckExact(item)) {
3163 long value;
3164 int overflow;
3165 value = PyLong_AsLongAndOverflow(item, &overflow);
3166 if (!overflow) {
3167 f_result *= (double)value;
3168 Py_DECREF(item);
3169 continue;
3170 }
3171 }
3172 result = PyFloat_FromDouble(f_result);
3173 if (result == NULL) {
3174 Py_DECREF(item);
3175 Py_DECREF(iter);
3176 return NULL;
3177 }
3178 temp = PyNumber_Multiply(result, item);
3179 Py_DECREF(result);
3180 Py_DECREF(item);
3181 result = temp;
3182 if (result == NULL) {
3183 Py_DECREF(iter);
3184 return NULL;
3185 }
3186 }
3187 }
3188#endif
3189 /* Consume rest of the iterable (if any) that could not be handled
3190 * by specialized functions above.*/
3191 for(;;) {
3192 item = PyIter_Next(iter);
3193 if (item == NULL) {
3194 /* error, or end-of-sequence */
3195 if (PyErr_Occurred()) {
3196 Py_DECREF(result);
3197 result = NULL;
3198 }
3199 break;
3200 }
3201 temp = PyNumber_Multiply(result, item);
3202 Py_DECREF(result);
3203 Py_DECREF(item);
3204 result = temp;
3205 if (result == NULL)
3206 break;
3207 }
3208 Py_DECREF(iter);
3209 return result;
3210}
3211
3212
Yash Aggarwal4a686502019-06-01 12:51:27 +05303213/*[clinic input]
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003214math.perm
3215
3216 n: object
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003217 k: object = None
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003218 /
3219
3220Number of ways to choose k items from n items without repetition and with order.
3221
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003222Evaluates to n! / (n - k)! when k <= n and evaluates
3223to zero when k > n.
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003224
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003225If k is not specified or is None, then k defaults to n
3226and the function returns n!.
3227
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003228Raises TypeError if either of the arguments are not integers.
3229Raises ValueError if either of the arguments are negative.
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003230[clinic start generated code]*/
3231
3232static PyObject *
3233math_perm_impl(PyObject *module, PyObject *n, PyObject *k)
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003234/*[clinic end generated code: output=e021a25469653e23 input=5311c5a00f359b53]*/
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003235{
3236 PyObject *result = NULL, *factor = NULL;
3237 int overflow, cmp;
3238 long long i, factors;
3239
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003240 if (k == Py_None) {
3241 return math_factorial(module, n);
3242 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003243 n = PyNumber_Index(n);
3244 if (n == NULL) {
3245 return NULL;
3246 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003247 k = PyNumber_Index(k);
3248 if (k == NULL) {
3249 Py_DECREF(n);
3250 return NULL;
3251 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003252
3253 if (Py_SIZE(n) < 0) {
3254 PyErr_SetString(PyExc_ValueError,
3255 "n must be a non-negative integer");
3256 goto error;
3257 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003258 if (Py_SIZE(k) < 0) {
3259 PyErr_SetString(PyExc_ValueError,
3260 "k must be a non-negative integer");
3261 goto error;
3262 }
3263
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003264 cmp = PyObject_RichCompareBool(n, k, Py_LT);
3265 if (cmp != 0) {
3266 if (cmp > 0) {
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003267 result = PyLong_FromLong(0);
3268 goto done;
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003269 }
3270 goto error;
3271 }
3272
3273 factors = PyLong_AsLongLongAndOverflow(k, &overflow);
3274 if (overflow > 0) {
3275 PyErr_Format(PyExc_OverflowError,
3276 "k must not exceed %lld",
3277 LLONG_MAX);
3278 goto error;
3279 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003280 else if (factors == -1) {
3281 /* k is nonnegative, so a return value of -1 can only indicate error */
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003282 goto error;
3283 }
3284
3285 if (factors == 0) {
3286 result = PyLong_FromLong(1);
3287 goto done;
3288 }
3289
3290 result = n;
3291 Py_INCREF(result);
3292 if (factors == 1) {
3293 goto done;
3294 }
3295
3296 factor = n;
3297 Py_INCREF(factor);
3298 for (i = 1; i < factors; ++i) {
Victor Stinner37834132020-10-27 17:12:53 +01003299 Py_SETREF(factor, PyNumber_Subtract(factor, _PyLong_GetOne()));
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003300 if (factor == NULL) {
3301 goto error;
3302 }
3303 Py_SETREF(result, PyNumber_Multiply(result, factor));
3304 if (result == NULL) {
3305 goto error;
3306 }
3307 }
3308 Py_DECREF(factor);
3309
3310done:
3311 Py_DECREF(n);
3312 Py_DECREF(k);
3313 return result;
3314
3315error:
3316 Py_XDECREF(factor);
3317 Py_XDECREF(result);
3318 Py_DECREF(n);
3319 Py_DECREF(k);
3320 return NULL;
3321}
3322
3323
3324/*[clinic input]
Yash Aggarwal4a686502019-06-01 12:51:27 +05303325math.comb
3326
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003327 n: object
3328 k: object
3329 /
Yash Aggarwal4a686502019-06-01 12:51:27 +05303330
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003331Number of ways to choose k items from n items without repetition and without order.
Yash Aggarwal4a686502019-06-01 12:51:27 +05303332
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003333Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates
3334to zero when k > n.
Yash Aggarwal4a686502019-06-01 12:51:27 +05303335
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003336Also called the binomial coefficient because it is equivalent
3337to the coefficient of k-th term in polynomial expansion of the
3338expression (1 + x)**n.
3339
3340Raises TypeError if either of the arguments are not integers.
3341Raises ValueError if either of the arguments are negative.
Yash Aggarwal4a686502019-06-01 12:51:27 +05303342
3343[clinic start generated code]*/
3344
3345static PyObject *
3346math_comb_impl(PyObject *module, PyObject *n, PyObject *k)
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003347/*[clinic end generated code: output=bd2cec8d854f3493 input=9a05315af2518709]*/
Yash Aggarwal4a686502019-06-01 12:51:27 +05303348{
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003349 PyObject *result = NULL, *factor = NULL, *temp;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303350 int overflow, cmp;
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003351 long long i, factors;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303352
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003353 n = PyNumber_Index(n);
3354 if (n == NULL) {
3355 return NULL;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303356 }
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003357 k = PyNumber_Index(k);
3358 if (k == NULL) {
3359 Py_DECREF(n);
3360 return NULL;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303361 }
3362
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003363 if (Py_SIZE(n) < 0) {
3364 PyErr_SetString(PyExc_ValueError,
3365 "n must be a non-negative integer");
3366 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303367 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003368 if (Py_SIZE(k) < 0) {
3369 PyErr_SetString(PyExc_ValueError,
3370 "k must be a non-negative integer");
3371 goto error;
3372 }
3373
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003374 /* k = min(k, n - k) */
3375 temp = PyNumber_Subtract(n, k);
3376 if (temp == NULL) {
3377 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303378 }
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003379 if (Py_SIZE(temp) < 0) {
3380 Py_DECREF(temp);
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003381 result = PyLong_FromLong(0);
3382 goto done;
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003383 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003384 cmp = PyObject_RichCompareBool(temp, k, Py_LT);
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003385 if (cmp > 0) {
3386 Py_SETREF(k, temp);
Yash Aggarwal4a686502019-06-01 12:51:27 +05303387 }
3388 else {
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003389 Py_DECREF(temp);
3390 if (cmp < 0) {
3391 goto error;
3392 }
Yash Aggarwal4a686502019-06-01 12:51:27 +05303393 }
3394
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003395 factors = PyLong_AsLongLongAndOverflow(k, &overflow);
3396 if (overflow > 0) {
Yash Aggarwal4a686502019-06-01 12:51:27 +05303397 PyErr_Format(PyExc_OverflowError,
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003398 "min(n - k, k) must not exceed %lld",
Yash Aggarwal4a686502019-06-01 12:51:27 +05303399 LLONG_MAX);
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003400 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303401 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003402 if (factors == -1) {
3403 /* k is nonnegative, so a return value of -1 can only indicate error */
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003404 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303405 }
3406
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003407 if (factors == 0) {
3408 result = PyLong_FromLong(1);
3409 goto done;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303410 }
3411
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003412 result = n;
3413 Py_INCREF(result);
3414 if (factors == 1) {
3415 goto done;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303416 }
3417
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003418 factor = n;
3419 Py_INCREF(factor);
3420 for (i = 1; i < factors; ++i) {
Victor Stinner37834132020-10-27 17:12:53 +01003421 Py_SETREF(factor, PyNumber_Subtract(factor, _PyLong_GetOne()));
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003422 if (factor == NULL) {
3423 goto error;
3424 }
3425 Py_SETREF(result, PyNumber_Multiply(result, factor));
3426 if (result == NULL) {
3427 goto error;
3428 }
Yash Aggarwal4a686502019-06-01 12:51:27 +05303429
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003430 temp = PyLong_FromUnsignedLongLong((unsigned long long)i + 1);
3431 if (temp == NULL) {
3432 goto error;
3433 }
3434 Py_SETREF(result, PyNumber_FloorDivide(result, temp));
3435 Py_DECREF(temp);
3436 if (result == NULL) {
3437 goto error;
3438 }
3439 }
3440 Py_DECREF(factor);
Yash Aggarwal4a686502019-06-01 12:51:27 +05303441
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003442done:
3443 Py_DECREF(n);
3444 Py_DECREF(k);
3445 return result;
3446
3447error:
3448 Py_XDECREF(factor);
3449 Py_XDECREF(result);
3450 Py_DECREF(n);
3451 Py_DECREF(k);
Yash Aggarwal4a686502019-06-01 12:51:27 +05303452 return NULL;
3453}
3454
3455
Victor Stinner100fafc2020-01-12 02:15:42 +01003456/*[clinic input]
3457math.nextafter
3458
3459 x: double
3460 y: double
3461 /
3462
3463Return the next floating-point value after x towards y.
3464[clinic start generated code]*/
3465
3466static PyObject *
3467math_nextafter_impl(PyObject *module, double x, double y)
3468/*[clinic end generated code: output=750c8266c1c540ce input=02b2d50cd1d9f9b6]*/
3469{
Victor Stinner85ead4f2020-01-21 11:14:10 +01003470#if defined(_AIX)
3471 if (x == y) {
3472 /* On AIX 7.1, libm nextafter(-0.0, +0.0) returns -0.0.
3473 Bug fixed in bos.adt.libm 7.2.2.0 by APAR IV95512. */
3474 return PyFloat_FromDouble(y);
3475 }
3476#endif
3477 return PyFloat_FromDouble(nextafter(x, y));
Victor Stinner100fafc2020-01-12 02:15:42 +01003478}
3479
3480
Victor Stinner0b2ab212020-01-13 12:44:35 +01003481/*[clinic input]
3482math.ulp -> double
3483
3484 x: double
3485 /
3486
3487Return the value of the least significant bit of the float x.
3488[clinic start generated code]*/
3489
3490static double
3491math_ulp_impl(PyObject *module, double x)
3492/*[clinic end generated code: output=f5207867a9384dd4 input=31f9bfbbe373fcaa]*/
3493{
3494 if (Py_IS_NAN(x)) {
3495 return x;
3496 }
3497 x = fabs(x);
3498 if (Py_IS_INFINITY(x)) {
3499 return x;
3500 }
3501 double inf = m_inf();
3502 double x2 = nextafter(x, inf);
3503 if (Py_IS_INFINITY(x2)) {
3504 /* special case: x is the largest positive representable float */
3505 x2 = nextafter(x, -inf);
3506 return x - x2;
3507 }
3508 return x2 - x;
3509}
3510
Dong-hee Na5be82412020-03-31 23:33:22 +09003511static int
3512math_exec(PyObject *module)
3513{
3514 if (PyModule_AddObject(module, "pi", PyFloat_FromDouble(Py_MATH_PI)) < 0) {
3515 return -1;
3516 }
3517 if (PyModule_AddObject(module, "e", PyFloat_FromDouble(Py_MATH_E)) < 0) {
3518 return -1;
3519 }
3520 // 2pi
3521 if (PyModule_AddObject(module, "tau", PyFloat_FromDouble(Py_MATH_TAU)) < 0) {
3522 return -1;
3523 }
3524 if (PyModule_AddObject(module, "inf", PyFloat_FromDouble(m_inf())) < 0) {
3525 return -1;
3526 }
3527#if !defined(PY_NO_SHORT_FLOAT_REPR) || defined(Py_NAN)
3528 if (PyModule_AddObject(module, "nan", PyFloat_FromDouble(m_nan())) < 0) {
3529 return -1;
3530 }
3531#endif
3532 return 0;
3533}
Victor Stinner0b2ab212020-01-13 12:44:35 +01003534
Barry Warsaw8b43b191996-12-09 22:32:36 +00003535static PyMethodDef math_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003536 {"acos", math_acos, METH_O, math_acos_doc},
3537 {"acosh", math_acosh, METH_O, math_acosh_doc},
3538 {"asin", math_asin, METH_O, math_asin_doc},
3539 {"asinh", math_asinh, METH_O, math_asinh_doc},
3540 {"atan", math_atan, METH_O, math_atan_doc},
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003541 {"atan2", (PyCFunction)(void(*)(void))math_atan2, METH_FASTCALL, math_atan2_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003542 {"atanh", math_atanh, METH_O, math_atanh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003543 MATH_CEIL_METHODDEF
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003544 {"copysign", (PyCFunction)(void(*)(void))math_copysign, METH_FASTCALL, math_copysign_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003545 {"cos", math_cos, METH_O, math_cos_doc},
3546 {"cosh", math_cosh, METH_O, math_cosh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003547 MATH_DEGREES_METHODDEF
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07003548 MATH_DIST_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003549 {"erf", math_erf, METH_O, math_erf_doc},
3550 {"erfc", math_erfc, METH_O, math_erfc_doc},
3551 {"exp", math_exp, METH_O, math_exp_doc},
3552 {"expm1", math_expm1, METH_O, math_expm1_doc},
3553 {"fabs", math_fabs, METH_O, math_fabs_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003554 MATH_FACTORIAL_METHODDEF
3555 MATH_FLOOR_METHODDEF
3556 MATH_FMOD_METHODDEF
3557 MATH_FREXP_METHODDEF
3558 MATH_FSUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003559 {"gamma", math_gamma, METH_O, math_gamma_doc},
Serhiy Storchaka559e7f12020-02-23 13:21:29 +02003560 {"gcd", (PyCFunction)(void(*)(void))math_gcd, METH_FASTCALL, math_gcd_doc},
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003561 {"hypot", (PyCFunction)(void(*)(void))math_hypot, METH_FASTCALL, math_hypot_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003562 MATH_ISCLOSE_METHODDEF
3563 MATH_ISFINITE_METHODDEF
3564 MATH_ISINF_METHODDEF
3565 MATH_ISNAN_METHODDEF
Mark Dickinson73934b92019-05-18 12:29:50 +01003566 MATH_ISQRT_METHODDEF
Serhiy Storchaka559e7f12020-02-23 13:21:29 +02003567 {"lcm", (PyCFunction)(void(*)(void))math_lcm, METH_FASTCALL, math_lcm_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003568 MATH_LDEXP_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003569 {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003570 MATH_LOG_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003571 {"log1p", math_log1p, METH_O, math_log1p_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003572 MATH_LOG10_METHODDEF
3573 MATH_LOG2_METHODDEF
3574 MATH_MODF_METHODDEF
3575 MATH_POW_METHODDEF
3576 MATH_RADIANS_METHODDEF
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003577 {"remainder", (PyCFunction)(void(*)(void))math_remainder, METH_FASTCALL, math_remainder_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003578 {"sin", math_sin, METH_O, math_sin_doc},
3579 {"sinh", math_sinh, METH_O, math_sinh_doc},
3580 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
3581 {"tan", math_tan, METH_O, math_tan_doc},
3582 {"tanh", math_tanh, METH_O, math_tanh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003583 MATH_TRUNC_METHODDEF
Pablo Galindobc098512019-02-07 07:04:02 +00003584 MATH_PROD_METHODDEF
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003585 MATH_PERM_METHODDEF
Yash Aggarwal4a686502019-06-01 12:51:27 +05303586 MATH_COMB_METHODDEF
Victor Stinner100fafc2020-01-12 02:15:42 +01003587 MATH_NEXTAFTER_METHODDEF
Victor Stinner0b2ab212020-01-13 12:44:35 +01003588 MATH_ULP_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003589 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003590};
3591
Dong-hee Na5be82412020-03-31 23:33:22 +09003592static PyModuleDef_Slot math_slots[] = {
3593 {Py_mod_exec, math_exec},
3594 {0, NULL}
3595};
Guido van Rossumc6e22901998-12-04 19:26:43 +00003596
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003597PyDoc_STRVAR(module_doc,
Ned Batchelder6faad352019-05-17 05:59:14 -04003598"This module provides access to the mathematical functions\n"
3599"defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00003600
Martin v. Löwis1a214512008-06-11 05:26:20 +00003601static struct PyModuleDef mathmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003602 PyModuleDef_HEAD_INIT,
Dong-hee Na5be82412020-03-31 23:33:22 +09003603 .m_name = "math",
3604 .m_doc = module_doc,
3605 .m_size = 0,
3606 .m_methods = math_methods,
3607 .m_slots = math_slots,
Martin v. Löwis1a214512008-06-11 05:26:20 +00003608};
3609
Mark Hammondfe51c6d2002-08-02 02:27:13 +00003610PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003611PyInit_math(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003612{
Dong-hee Na5be82412020-03-31 23:33:22 +09003613 return PyModuleDef_Init(&mathmodule);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003614}