blob: f012b51d86698d6767a30f27919b202d6ccd06d8 [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"
Mark Dickinson664b5112009-12-16 20:23:42 +000056#include "_math.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000057
Serhiy Storchakac9ea9332017-01-19 18:13:09 +020058#include "clinic/mathmodule.c.h"
59
60/*[clinic input]
61module math
62[clinic start generated code]*/
63/*[clinic end generated code: output=da39a3ee5e6b4b0d input=76bc7002685dd942]*/
64
65
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000066/*
67 sin(pi*x), giving accurate results for all finite x (especially x
68 integral or close to an integer). This is here for use in the
69 reflection formula for the gamma function. It conforms to IEEE
70 754-2008 for finite arguments, but not for infinities or nans.
71*/
Tim Petersa40c7932001-09-05 22:36:56 +000072
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000073static const double pi = 3.141592653589793238462643383279502884197;
Mark Dickinson9c91eb82010-07-07 16:17:31 +000074static const double logpi = 1.144729885849400174143427351353058711647;
Louie Lu7a264642017-03-31 01:05:10 +080075#if !defined(HAVE_ERF) || !defined(HAVE_ERFC)
76static const double sqrtpi = 1.772453850905516027298167483341145182798;
77#endif /* !defined(HAVE_ERF) || !defined(HAVE_ERFC) */
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000078
Raymond Hettingercfd735e2019-01-29 20:39:53 -080079
80/* Version of PyFloat_AsDouble() with in-line fast paths
81 for exact floats and integers. Gives a substantial
82 speed improvement for extracting float arguments.
83*/
84
85#define ASSIGN_DOUBLE(target_var, obj, error_label) \
86 if (PyFloat_CheckExact(obj)) { \
87 target_var = PyFloat_AS_DOUBLE(obj); \
88 } \
89 else if (PyLong_CheckExact(obj)) { \
90 target_var = PyLong_AsDouble(obj); \
91 if (target_var == -1.0 && PyErr_Occurred()) { \
92 goto error_label; \
93 } \
94 } \
95 else { \
96 target_var = PyFloat_AsDouble(obj); \
97 if (target_var == -1.0 && PyErr_Occurred()) { \
98 goto error_label; \
99 } \
100 }
101
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000102static double
Dima Pasechnikf57cd822019-02-26 06:36:11 +0000103m_sinpi(double x)
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000104{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 double y, r;
106 int n;
107 /* this function should only ever be called for finite arguments */
108 assert(Py_IS_FINITE(x));
109 y = fmod(fabs(x), 2.0);
110 n = (int)round(2.0*y);
111 assert(0 <= n && n <= 4);
112 switch (n) {
113 case 0:
114 r = sin(pi*y);
115 break;
116 case 1:
117 r = cos(pi*(y-0.5));
118 break;
119 case 2:
120 /* N.B. -sin(pi*(y-1.0)) is *not* equivalent: it would give
121 -0.0 instead of 0.0 when y == 1.0. */
122 r = sin(pi*(1.0-y));
123 break;
124 case 3:
125 r = -cos(pi*(y-1.5));
126 break;
127 case 4:
128 r = sin(pi*(y-2.0));
129 break;
130 default:
Barry Warsawb2e57942017-09-14 18:13:16 -0700131 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 }
133 return copysign(1.0, x)*r;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000134}
135
136/* Implementation of the real gamma function. In extensive but non-exhaustive
137 random tests, this function proved accurate to within <= 10 ulps across the
138 entire float domain. Note that accuracy may depend on the quality of the
139 system math functions, the pow function in particular. Special cases
140 follow C99 annex F. The parameters and method are tailored to platforms
141 whose double format is the IEEE 754 binary64 format.
142
143 Method: for x > 0.0 we use the Lanczos approximation with parameters N=13
144 and g=6.024680040776729583740234375; these parameters are amongst those
145 used by the Boost library. Following Boost (again), we re-express the
146 Lanczos sum as a rational function, and compute it that way. The
147 coefficients below were computed independently using MPFR, and have been
148 double-checked against the coefficients in the Boost source code.
149
150 For x < 0.0 we use the reflection formula.
151
152 There's one minor tweak that deserves explanation: Lanczos' formula for
153 Gamma(x) involves computing pow(x+g-0.5, x-0.5) / exp(x+g-0.5). For many x
154 values, x+g-0.5 can be represented exactly. However, in cases where it
155 can't be represented exactly the small error in x+g-0.5 can be magnified
156 significantly by the pow and exp calls, especially for large x. A cheap
157 correction is to multiply by (1 + e*g/(x+g-0.5)), where e is the error
158 involved in the computation of x+g-0.5 (that is, e = computed value of
159 x+g-0.5 - exact value of x+g-0.5). Here's the proof:
160
161 Correction factor
162 -----------------
163 Write x+g-0.5 = y-e, where y is exactly representable as an IEEE 754
164 double, and e is tiny. Then:
165
166 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) = pow(y-e, x-0.5)/exp(y-e)
167 = pow(y, x-0.5)/exp(y) * C,
168
169 where the correction_factor C is given by
170
171 C = pow(1-e/y, x-0.5) * exp(e)
172
173 Since e is tiny, pow(1-e/y, x-0.5) ~ 1-(x-0.5)*e/y, and exp(x) ~ 1+e, so:
174
175 C ~ (1-(x-0.5)*e/y) * (1+e) ~ 1 + e*(y-(x-0.5))/y
176
177 But y-(x-0.5) = g+e, and g+e ~ g. So we get C ~ 1 + e*g/y, and
178
179 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) ~ pow(y, x-0.5)/exp(y) * (1 + e*g/y),
180
181 Note that for accuracy, when computing r*C it's better to do
182
183 r + e*g/y*r;
184
185 than
186
187 r * (1 + e*g/y);
188
189 since the addition in the latter throws away most of the bits of
190 information in e*g/y.
191*/
192
193#define LANCZOS_N 13
194static const double lanczos_g = 6.024680040776729583740234375;
195static const double lanczos_g_minus_half = 5.524680040776729583740234375;
196static const double lanczos_num_coeffs[LANCZOS_N] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 23531376880.410759688572007674451636754734846804940,
198 42919803642.649098768957899047001988850926355848959,
199 35711959237.355668049440185451547166705960488635843,
200 17921034426.037209699919755754458931112671403265390,
201 6039542586.3520280050642916443072979210699388420708,
202 1439720407.3117216736632230727949123939715485786772,
203 248874557.86205415651146038641322942321632125127801,
204 31426415.585400194380614231628318205362874684987640,
205 2876370.6289353724412254090516208496135991145378768,
206 186056.26539522349504029498971604569928220784236328,
207 8071.6720023658162106380029022722506138218516325024,
208 210.82427775157934587250973392071336271166969580291,
209 2.5066282746310002701649081771338373386264310793408
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000210};
211
212/* denominator is x*(x+1)*...*(x+LANCZOS_N-2) */
213static const double lanczos_den_coeffs[LANCZOS_N] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 0.0, 39916800.0, 120543840.0, 150917976.0, 105258076.0, 45995730.0,
215 13339535.0, 2637558.0, 357423.0, 32670.0, 1925.0, 66.0, 1.0};
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000216
217/* gamma values for small positive integers, 1 though NGAMMA_INTEGRAL */
218#define NGAMMA_INTEGRAL 23
219static const double gamma_integral[NGAMMA_INTEGRAL] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0,
221 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0,
222 1307674368000.0, 20922789888000.0, 355687428096000.0,
223 6402373705728000.0, 121645100408832000.0, 2432902008176640000.0,
224 51090942171709440000.0, 1124000727777607680000.0,
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000225};
226
227/* Lanczos' sum L_g(x), for positive x */
228
229static double
230lanczos_sum(double x)
231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 double num = 0.0, den = 0.0;
233 int i;
234 assert(x > 0.0);
235 /* evaluate the rational function lanczos_sum(x). For large
236 x, the obvious algorithm risks overflow, so we instead
237 rescale the denominator and numerator of the rational
238 function by x**(1-LANCZOS_N) and treat this as a
239 rational function in 1/x. This also reduces the error for
240 larger x values. The choice of cutoff point (5.0 below) is
241 somewhat arbitrary; in tests, smaller cutoff values than
242 this resulted in lower accuracy. */
243 if (x < 5.0) {
244 for (i = LANCZOS_N; --i >= 0; ) {
245 num = num * x + lanczos_num_coeffs[i];
246 den = den * x + lanczos_den_coeffs[i];
247 }
248 }
249 else {
250 for (i = 0; i < LANCZOS_N; i++) {
251 num = num / x + lanczos_num_coeffs[i];
252 den = den / x + lanczos_den_coeffs[i];
253 }
254 }
255 return num/den;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000256}
257
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +0000258/* Constant for +infinity, generated in the same way as float('inf'). */
259
260static double
261m_inf(void)
262{
263#ifndef PY_NO_SHORT_FLOAT_REPR
264 return _Py_dg_infinity(0);
265#else
266 return Py_HUGE_VAL;
267#endif
268}
269
270/* Constant nan value, generated in the same way as float('nan'). */
271/* We don't currently assume that Py_NAN is defined everywhere. */
272
273#if !defined(PY_NO_SHORT_FLOAT_REPR) || defined(Py_NAN)
274
275static double
276m_nan(void)
277{
278#ifndef PY_NO_SHORT_FLOAT_REPR
279 return _Py_dg_stdnan(0);
280#else
281 return Py_NAN;
282#endif
283}
284
285#endif
286
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000287static double
288m_tgamma(double x)
289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 double absx, r, y, z, sqrtpow;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 /* special cases */
293 if (!Py_IS_FINITE(x)) {
294 if (Py_IS_NAN(x) || x > 0.0)
295 return x; /* tgamma(nan) = nan, tgamma(inf) = inf */
296 else {
297 errno = EDOM;
298 return Py_NAN; /* tgamma(-inf) = nan, invalid */
299 }
300 }
301 if (x == 0.0) {
302 errno = EDOM;
Mark Dickinson50203a62011-09-25 15:26:43 +0100303 /* tgamma(+-0.0) = +-inf, divide-by-zero */
304 return copysign(Py_HUGE_VAL, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 /* integer arguments */
308 if (x == floor(x)) {
309 if (x < 0.0) {
310 errno = EDOM; /* tgamma(n) = nan, invalid for */
311 return Py_NAN; /* negative integers n */
312 }
313 if (x <= NGAMMA_INTEGRAL)
314 return gamma_integral[(int)x - 1];
315 }
316 absx = fabs(x);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 /* tiny arguments: tgamma(x) ~ 1/x for x near 0 */
319 if (absx < 1e-20) {
320 r = 1.0/x;
321 if (Py_IS_INFINITY(r))
322 errno = ERANGE;
323 return r;
324 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 /* large arguments: assuming IEEE 754 doubles, tgamma(x) overflows for
327 x > 200, and underflows to +-0.0 for x < -200, not a negative
328 integer. */
329 if (absx > 200.0) {
330 if (x < 0.0) {
Dima Pasechnikf57cd822019-02-26 06:36:11 +0000331 return 0.0/m_sinpi(x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 }
333 else {
334 errno = ERANGE;
335 return Py_HUGE_VAL;
336 }
337 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 y = absx + lanczos_g_minus_half;
340 /* compute error in sum */
341 if (absx > lanczos_g_minus_half) {
342 /* note: the correction can be foiled by an optimizing
343 compiler that (incorrectly) thinks that an expression like
344 a + b - a - b can be optimized to 0.0. This shouldn't
345 happen in a standards-conforming compiler. */
346 double q = y - absx;
347 z = q - lanczos_g_minus_half;
348 }
349 else {
350 double q = y - lanczos_g_minus_half;
351 z = q - absx;
352 }
353 z = z * lanczos_g / y;
354 if (x < 0.0) {
Dima Pasechnikf57cd822019-02-26 06:36:11 +0000355 r = -pi / m_sinpi(absx) / absx * exp(y) / lanczos_sum(absx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 r -= z * r;
357 if (absx < 140.0) {
358 r /= pow(y, absx - 0.5);
359 }
360 else {
361 sqrtpow = pow(y, absx / 2.0 - 0.25);
362 r /= sqrtpow;
363 r /= sqrtpow;
364 }
365 }
366 else {
367 r = lanczos_sum(absx) / exp(y);
368 r += z * r;
369 if (absx < 140.0) {
370 r *= pow(y, absx - 0.5);
371 }
372 else {
373 sqrtpow = pow(y, absx / 2.0 - 0.25);
374 r *= sqrtpow;
375 r *= sqrtpow;
376 }
377 }
378 if (Py_IS_INFINITY(r))
379 errno = ERANGE;
380 return r;
Guido van Rossum8832b621991-12-16 15:44:24 +0000381}
382
Christian Heimes53876d92008-04-19 00:31:39 +0000383/*
Mark Dickinson05d2e082009-12-11 20:17:17 +0000384 lgamma: natural log of the absolute value of the Gamma function.
385 For large arguments, Lanczos' formula works extremely well here.
386*/
387
388static double
389m_lgamma(double x)
390{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200391 double r;
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200392 double absx;
Mark Dickinson05d2e082009-12-11 20:17:17 +0000393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 /* special cases */
395 if (!Py_IS_FINITE(x)) {
396 if (Py_IS_NAN(x))
397 return x; /* lgamma(nan) = nan */
398 else
399 return Py_HUGE_VAL; /* lgamma(+-inf) = +inf */
400 }
Mark Dickinson05d2e082009-12-11 20:17:17 +0000401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 /* integer arguments */
403 if (x == floor(x) && x <= 2.0) {
404 if (x <= 0.0) {
405 errno = EDOM; /* lgamma(n) = inf, divide-by-zero for */
406 return Py_HUGE_VAL; /* integers n <= 0 */
407 }
408 else {
409 return 0.0; /* lgamma(1) = lgamma(2) = 0.0 */
410 }
411 }
Mark Dickinson05d2e082009-12-11 20:17:17 +0000412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 absx = fabs(x);
414 /* tiny arguments: lgamma(x) ~ -log(fabs(x)) for small x */
415 if (absx < 1e-20)
416 return -log(absx);
Mark Dickinson05d2e082009-12-11 20:17:17 +0000417
Mark Dickinson9c91eb82010-07-07 16:17:31 +0000418 /* Lanczos' formula. We could save a fraction of a ulp in accuracy by
419 having a second set of numerator coefficients for lanczos_sum that
420 absorbed the exp(-lanczos_g) term, and throwing out the lanczos_g
421 subtraction below; it's probably not worth it. */
422 r = log(lanczos_sum(absx)) - lanczos_g;
423 r += (absx - 0.5) * (log(absx + lanczos_g - 0.5) - 1);
424 if (x < 0.0)
425 /* Use reflection formula to get value for negative x. */
Dima Pasechnikf57cd822019-02-26 06:36:11 +0000426 r = logpi - log(fabs(m_sinpi(absx))) - log(absx) - r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 if (Py_IS_INFINITY(r))
428 errno = ERANGE;
429 return r;
Mark Dickinson05d2e082009-12-11 20:17:17 +0000430}
431
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200432#if !defined(HAVE_ERF) || !defined(HAVE_ERFC)
433
Mark Dickinson45f992a2009-12-19 11:20:49 +0000434/*
435 Implementations of the error function erf(x) and the complementary error
436 function erfc(x).
437
Brett Cannon45adb312016-01-15 09:38:24 -0800438 Method: we use a series approximation for erf for small x, and a continued
439 fraction approximation for erfc(x) for larger x;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000440 combined with the relations erf(-x) = -erf(x) and erfc(x) = 1.0 - erf(x),
441 this gives us erf(x) and erfc(x) for all x.
442
443 The series expansion used is:
444
445 erf(x) = x*exp(-x*x)/sqrt(pi) * [
446 2/1 + 4/3 x**2 + 8/15 x**4 + 16/105 x**6 + ...]
447
448 The coefficient of x**(2k-2) here is 4**k*factorial(k)/factorial(2*k).
449 This series converges well for smallish x, but slowly for larger x.
450
451 The continued fraction expansion used is:
452
453 erfc(x) = x*exp(-x*x)/sqrt(pi) * [1/(0.5 + x**2 -) 0.5/(2.5 + x**2 - )
454 3.0/(4.5 + x**2 - ) 7.5/(6.5 + x**2 - ) ...]
455
456 after the first term, the general term has the form:
457
458 k*(k-0.5)/(2*k+0.5 + x**2 - ...).
459
460 This expansion converges fast for larger x, but convergence becomes
461 infinitely slow as x approaches 0.0. The (somewhat naive) continued
462 fraction evaluation algorithm used below also risks overflow for large x;
463 but for large x, erfc(x) == 0.0 to within machine precision. (For
464 example, erfc(30.0) is approximately 2.56e-393).
465
466 Parameters: use series expansion for abs(x) < ERF_SERIES_CUTOFF and
467 continued fraction expansion for ERF_SERIES_CUTOFF <= abs(x) <
468 ERFC_CONTFRAC_CUTOFF. ERFC_SERIES_TERMS and ERFC_CONTFRAC_TERMS are the
469 numbers of terms to use for the relevant expansions. */
470
471#define ERF_SERIES_CUTOFF 1.5
472#define ERF_SERIES_TERMS 25
473#define ERFC_CONTFRAC_CUTOFF 30.0
474#define ERFC_CONTFRAC_TERMS 50
475
476/*
477 Error function, via power series.
478
479 Given a finite float x, return an approximation to erf(x).
480 Converges reasonably fast for small x.
481*/
482
483static double
484m_erf_series(double x)
485{
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000486 double x2, acc, fk, result;
487 int i, saved_errno;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 x2 = x * x;
490 acc = 0.0;
491 fk = (double)ERF_SERIES_TERMS + 0.5;
492 for (i = 0; i < ERF_SERIES_TERMS; i++) {
493 acc = 2.0 + x2 * acc / fk;
494 fk -= 1.0;
495 }
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000496 /* Make sure the exp call doesn't affect errno;
497 see m_erfc_contfrac for more. */
498 saved_errno = errno;
499 result = acc * x * exp(-x2) / sqrtpi;
500 errno = saved_errno;
501 return result;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000502}
503
504/*
505 Complementary error function, via continued fraction expansion.
506
507 Given a positive float x, return an approximation to erfc(x). Converges
508 reasonably fast for x large (say, x > 2.0), and should be safe from
509 overflow if x and nterms are not too large. On an IEEE 754 machine, with x
510 <= 30.0, we're safe up to nterms = 100. For x >= 30.0, erfc(x) is smaller
511 than the smallest representable nonzero float. */
512
513static double
514m_erfc_contfrac(double x)
515{
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000516 double x2, a, da, p, p_last, q, q_last, b, result;
517 int i, saved_errno;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 if (x >= ERFC_CONTFRAC_CUTOFF)
520 return 0.0;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 x2 = x*x;
523 a = 0.0;
524 da = 0.5;
525 p = 1.0; p_last = 0.0;
526 q = da + x2; q_last = 1.0;
527 for (i = 0; i < ERFC_CONTFRAC_TERMS; i++) {
528 double temp;
529 a += da;
530 da += 2.0;
531 b = da + x2;
532 temp = p; p = b*p - a*p_last; p_last = temp;
533 temp = q; q = b*q - a*q_last; q_last = temp;
534 }
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000535 /* Issue #8986: On some platforms, exp sets errno on underflow to zero;
536 save the current errno value so that we can restore it later. */
537 saved_errno = errno;
538 result = p / q * x * exp(-x2) / sqrtpi;
539 errno = saved_errno;
540 return result;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000541}
542
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200543#endif /* !defined(HAVE_ERF) || !defined(HAVE_ERFC) */
544
Mark Dickinson45f992a2009-12-19 11:20:49 +0000545/* Error function erf(x), for general x */
546
547static double
548m_erf(double x)
549{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200550#ifdef HAVE_ERF
551 return erf(x);
552#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 double absx, cf;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 if (Py_IS_NAN(x))
556 return x;
557 absx = fabs(x);
558 if (absx < ERF_SERIES_CUTOFF)
559 return m_erf_series(x);
560 else {
561 cf = m_erfc_contfrac(absx);
562 return x > 0.0 ? 1.0 - cf : cf - 1.0;
563 }
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200564#endif
Mark Dickinson45f992a2009-12-19 11:20:49 +0000565}
566
567/* Complementary error function erfc(x), for general x. */
568
569static double
570m_erfc(double x)
571{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200572#ifdef HAVE_ERFC
573 return erfc(x);
574#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 double absx, cf;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 if (Py_IS_NAN(x))
578 return x;
579 absx = fabs(x);
580 if (absx < ERF_SERIES_CUTOFF)
581 return 1.0 - m_erf_series(x);
582 else {
583 cf = m_erfc_contfrac(absx);
584 return x > 0.0 ? cf : 2.0 - cf;
585 }
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200586#endif
Mark Dickinson45f992a2009-12-19 11:20:49 +0000587}
Mark Dickinson05d2e082009-12-11 20:17:17 +0000588
589/*
Christian Heimese57950f2008-04-21 13:08:03 +0000590 wrapper for atan2 that deals directly with special cases before
591 delegating to the platform libm for the remaining cases. This
592 is necessary to get consistent behaviour across platforms.
593 Windows, FreeBSD and alpha Tru64 are amongst platforms that don't
594 always follow C99.
595*/
596
597static double
598m_atan2(double y, double x)
599{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 if (Py_IS_NAN(x) || Py_IS_NAN(y))
601 return Py_NAN;
602 if (Py_IS_INFINITY(y)) {
603 if (Py_IS_INFINITY(x)) {
604 if (copysign(1., x) == 1.)
605 /* atan2(+-inf, +inf) == +-pi/4 */
606 return copysign(0.25*Py_MATH_PI, y);
607 else
608 /* atan2(+-inf, -inf) == +-pi*3/4 */
609 return copysign(0.75*Py_MATH_PI, y);
610 }
611 /* atan2(+-inf, x) == +-pi/2 for finite x */
612 return copysign(0.5*Py_MATH_PI, y);
613 }
614 if (Py_IS_INFINITY(x) || y == 0.) {
615 if (copysign(1., x) == 1.)
616 /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */
617 return copysign(0., y);
618 else
619 /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */
620 return copysign(Py_MATH_PI, y);
621 }
622 return atan2(y, x);
Christian Heimese57950f2008-04-21 13:08:03 +0000623}
624
Mark Dickinsona0ce3752017-04-05 18:34:27 +0100625
626/* IEEE 754-style remainder operation: x - n*y where n*y is the nearest
627 multiple of y to x, taking n even in the case of a tie. Assuming an IEEE 754
628 binary floating-point format, the result is always exact. */
629
630static double
631m_remainder(double x, double y)
632{
633 /* Deal with most common case first. */
634 if (Py_IS_FINITE(x) && Py_IS_FINITE(y)) {
635 double absx, absy, c, m, r;
636
637 if (y == 0.0) {
638 return Py_NAN;
639 }
640
641 absx = fabs(x);
642 absy = fabs(y);
643 m = fmod(absx, absy);
644
645 /*
646 Warning: some subtlety here. What we *want* to know at this point is
647 whether the remainder m is less than, equal to, or greater than half
648 of absy. However, we can't do that comparison directly because we
Mark Dickinson01484702019-07-13 16:50:03 +0100649 can't be sure that 0.5*absy is representable (the multiplication
Mark Dickinsona0ce3752017-04-05 18:34:27 +0100650 might incur precision loss due to underflow). So instead we compare
651 m with the complement c = absy - m: m < 0.5*absy if and only if m <
652 c, and so on. The catch is that absy - m might also not be
653 representable, but it turns out that it doesn't matter:
654
655 - if m > 0.5*absy then absy - m is exactly representable, by
656 Sterbenz's lemma, so m > c
657 - if m == 0.5*absy then again absy - m is exactly representable
658 and m == c
659 - if m < 0.5*absy then either (i) 0.5*absy is exactly representable,
660 in which case 0.5*absy < absy - m, so 0.5*absy <= c and hence m <
661 c, or (ii) absy is tiny, either subnormal or in the lowest normal
662 binade. Then absy - m is exactly representable and again m < c.
663 */
664
665 c = absy - m;
666 if (m < c) {
667 r = m;
668 }
669 else if (m > c) {
670 r = -c;
671 }
672 else {
673 /*
674 Here absx is exactly halfway between two multiples of absy,
675 and we need to choose the even multiple. x now has the form
676
677 absx = n * absy + m
678
679 for some integer n (recalling that m = 0.5*absy at this point).
680 If n is even we want to return m; if n is odd, we need to
681 return -m.
682
683 So
684
685 0.5 * (absx - m) = (n/2) * absy
686
687 and now reducing modulo absy gives us:
688
689 | m, if n is odd
690 fmod(0.5 * (absx - m), absy) = |
691 | 0, if n is even
692
693 Now m - 2.0 * fmod(...) gives the desired result: m
694 if n is even, -m if m is odd.
695
696 Note that all steps in fmod(0.5 * (absx - m), absy)
697 will be computed exactly, with no rounding error
698 introduced.
699 */
700 assert(m == c);
701 r = m - 2.0 * fmod(0.5 * (absx - m), absy);
702 }
703 return copysign(1.0, x) * r;
704 }
705
706 /* Special values. */
707 if (Py_IS_NAN(x)) {
708 return x;
709 }
710 if (Py_IS_NAN(y)) {
711 return y;
712 }
713 if (Py_IS_INFINITY(x)) {
714 return Py_NAN;
715 }
716 assert(Py_IS_INFINITY(y));
717 return x;
718}
719
720
Christian Heimese57950f2008-04-21 13:08:03 +0000721/*
Mark Dickinsone675f082008-12-11 21:56:00 +0000722 Various platforms (Solaris, OpenBSD) do nonstandard things for log(0),
723 log(-ve), log(NaN). Here are wrappers for log and log10 that deal with
724 special values directly, passing positive non-special values through to
725 the system log/log10.
726 */
727
728static double
729m_log(double x)
730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 if (Py_IS_FINITE(x)) {
732 if (x > 0.0)
733 return log(x);
734 errno = EDOM;
735 if (x == 0.0)
736 return -Py_HUGE_VAL; /* log(0) = -inf */
737 else
738 return Py_NAN; /* log(-ve) = nan */
739 }
740 else if (Py_IS_NAN(x))
741 return x; /* log(nan) = nan */
742 else if (x > 0.0)
743 return x; /* log(inf) = inf */
744 else {
745 errno = EDOM;
746 return Py_NAN; /* log(-inf) = nan */
747 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000748}
749
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200750/*
751 log2: log to base 2.
752
753 Uses an algorithm that should:
Mark Dickinson83b8c0b2011-05-09 08:40:20 +0100754
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200755 (a) produce exact results for powers of 2, and
Mark Dickinson83b8c0b2011-05-09 08:40:20 +0100756 (b) give a monotonic log2 (for positive finite floats),
757 assuming that the system log is monotonic.
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200758*/
759
760static double
761m_log2(double x)
762{
763 if (!Py_IS_FINITE(x)) {
764 if (Py_IS_NAN(x))
765 return x; /* log2(nan) = nan */
766 else if (x > 0.0)
767 return x; /* log2(+inf) = +inf */
768 else {
769 errno = EDOM;
770 return Py_NAN; /* log2(-inf) = nan, invalid-operation */
771 }
772 }
773
774 if (x > 0.0) {
Victor Stinner8f9f8d62011-05-09 12:45:41 +0200775#ifdef HAVE_LOG2
776 return log2(x);
777#else
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200778 double m;
779 int e;
780 m = frexp(x, &e);
781 /* We want log2(m * 2**e) == log(m) / log(2) + e. Care is needed when
782 * x is just greater than 1.0: in that case e is 1, log(m) is negative,
783 * and we get significant cancellation error from the addition of
784 * log(m) / log(2) to e. The slight rewrite of the expression below
785 * avoids this problem.
786 */
787 if (x >= 1.0) {
788 return log(2.0 * m) / log(2.0) + (e - 1);
789 }
790 else {
791 return log(m) / log(2.0) + e;
792 }
Victor Stinner8f9f8d62011-05-09 12:45:41 +0200793#endif
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200794 }
795 else if (x == 0.0) {
796 errno = EDOM;
797 return -Py_HUGE_VAL; /* log2(0) = -inf, divide-by-zero */
798 }
799 else {
800 errno = EDOM;
Mark Dickinson23442582011-05-09 08:05:00 +0100801 return Py_NAN; /* log2(-inf) = nan, invalid-operation */
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200802 }
803}
804
Mark Dickinsone675f082008-12-11 21:56:00 +0000805static double
806m_log10(double x)
807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 if (Py_IS_FINITE(x)) {
809 if (x > 0.0)
810 return log10(x);
811 errno = EDOM;
812 if (x == 0.0)
813 return -Py_HUGE_VAL; /* log10(0) = -inf */
814 else
815 return Py_NAN; /* log10(-ve) = nan */
816 }
817 else if (Py_IS_NAN(x))
818 return x; /* log10(nan) = nan */
819 else if (x > 0.0)
820 return x; /* log10(inf) = inf */
821 else {
822 errno = EDOM;
823 return Py_NAN; /* log10(-inf) = nan */
824 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000825}
826
827
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200828/*[clinic input]
829math.gcd
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300830
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200831 x as a: object
832 y as b: object
833 /
834
835greatest common divisor of x and y
836[clinic start generated code]*/
837
838static PyObject *
839math_gcd_impl(PyObject *module, PyObject *a, PyObject *b)
840/*[clinic end generated code: output=7b2e0c151bd7a5d8 input=c2691e57fb2a98fa]*/
841{
842 PyObject *g;
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300843
844 a = PyNumber_Index(a);
845 if (a == NULL)
846 return NULL;
847 b = PyNumber_Index(b);
848 if (b == NULL) {
849 Py_DECREF(a);
850 return NULL;
851 }
852 g = _PyLong_GCD(a, b);
853 Py_DECREF(a);
854 Py_DECREF(b);
855 return g;
856}
857
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300858
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000859/* Call is_error when errno != 0, and where x is the result libm
860 * returned. is_error will usually set up an exception and return
861 * true (1), but may return false (0) without setting up an exception.
862 */
863static int
864is_error(double x)
865{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 int result = 1; /* presumption of guilt */
867 assert(errno); /* non-zero errno is a precondition for calling */
868 if (errno == EDOM)
869 PyErr_SetString(PyExc_ValueError, "math domain error");
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 else if (errno == ERANGE) {
872 /* ANSI C generally requires libm functions to set ERANGE
873 * on overflow, but also generally *allows* them to set
874 * ERANGE on underflow too. There's no consistency about
875 * the latter across platforms.
876 * Alas, C99 never requires that errno be set.
877 * Here we suppress the underflow errors (libm functions
878 * should return a zero on underflow, and +- HUGE_VAL on
879 * overflow, so testing the result for zero suffices to
880 * distinguish the cases).
881 *
882 * On some platforms (Ubuntu/ia64) it seems that errno can be
883 * set to ERANGE for subnormal results that do *not* underflow
884 * to zero. So to be safe, we'll ignore ERANGE whenever the
885 * function result is less than one in absolute value.
886 */
887 if (fabs(x) < 1.0)
888 result = 0;
889 else
890 PyErr_SetString(PyExc_OverflowError,
891 "math range error");
892 }
893 else
894 /* Unexpected math error */
895 PyErr_SetFromErrno(PyExc_ValueError);
896 return result;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000897}
898
Mark Dickinsone675f082008-12-11 21:56:00 +0000899/*
Christian Heimes53876d92008-04-19 00:31:39 +0000900 math_1 is used to wrap a libm function f that takes a double
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200901 argument and returns a double.
Christian Heimes53876d92008-04-19 00:31:39 +0000902
903 The error reporting follows these rules, which are designed to do
904 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
905 platforms.
906
907 - a NaN result from non-NaN inputs causes ValueError to be raised
908 - an infinite result from finite inputs causes OverflowError to be
909 raised if can_overflow is 1, or raises ValueError if can_overflow
910 is 0.
911 - if the result is finite and errno == EDOM then ValueError is
912 raised
913 - if the result is finite and nonzero and errno == ERANGE then
914 OverflowError is raised
915
916 The last rule is used to catch overflow on platforms which follow
917 C89 but for which HUGE_VAL is not an infinity.
918
919 For the majority of one-argument functions these rules are enough
920 to ensure that Python's functions behave as specified in 'Annex F'
921 of the C99 standard, with the 'invalid' and 'divide-by-zero'
922 floating-point exceptions mapping to Python's ValueError and the
923 'overflow' floating-point exception mapping to OverflowError.
924 math_1 only works for functions that don't have singularities *and*
925 the possibility of overflow; fortunately, that covers everything we
926 care about right now.
927*/
928
Barry Warsaw8b43b191996-12-09 22:32:36 +0000929static PyObject *
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000930math_1_to_whatever(PyObject *arg, double (*func) (double),
Christian Heimes53876d92008-04-19 00:31:39 +0000931 PyObject *(*from_double_func) (double),
932 int can_overflow)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 double x, r;
935 x = PyFloat_AsDouble(arg);
936 if (x == -1.0 && PyErr_Occurred())
937 return NULL;
938 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 r = (*func)(x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 if (Py_IS_NAN(r) && !Py_IS_NAN(x)) {
941 PyErr_SetString(PyExc_ValueError,
942 "math domain error"); /* invalid arg */
943 return NULL;
944 }
945 if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) {
Benjamin Peterson2354a752012-03-13 16:13:09 -0500946 if (can_overflow)
947 PyErr_SetString(PyExc_OverflowError,
948 "math range error"); /* overflow */
949 else
950 PyErr_SetString(PyExc_ValueError,
951 "math domain error"); /* singularity */
952 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 }
954 if (Py_IS_FINITE(r) && errno && is_error(r))
955 /* this branch unnecessary on most platforms */
956 return NULL;
Mark Dickinsonde429622008-05-01 00:19:23 +0000957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 return (*from_double_func)(r);
Christian Heimes53876d92008-04-19 00:31:39 +0000959}
960
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000961/* variant of math_1, to be used when the function being wrapped is known to
962 set errno properly (that is, errno = EDOM for invalid or divide-by-zero,
963 errno = ERANGE for overflow). */
964
965static PyObject *
966math_1a(PyObject *arg, double (*func) (double))
967{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 double x, r;
969 x = PyFloat_AsDouble(arg);
970 if (x == -1.0 && PyErr_Occurred())
971 return NULL;
972 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 r = (*func)(x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 if (errno && is_error(r))
975 return NULL;
976 return PyFloat_FromDouble(r);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000977}
978
Christian Heimes53876d92008-04-19 00:31:39 +0000979/*
980 math_2 is used to wrap a libm function f that takes two double
981 arguments and returns a double.
982
983 The error reporting follows these rules, which are designed to do
984 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
985 platforms.
986
987 - a NaN result from non-NaN inputs causes ValueError to be raised
988 - an infinite result from finite inputs causes OverflowError to be
989 raised.
990 - if the result is finite and errno == EDOM then ValueError is
991 raised
992 - if the result is finite and nonzero and errno == ERANGE then
993 OverflowError is raised
994
995 The last rule is used to catch overflow on platforms which follow
996 C89 but for which HUGE_VAL is not an infinity.
997
998 For most two-argument functions (copysign, fmod, hypot, atan2)
999 these rules are enough to ensure that Python's functions behave as
1000 specified in 'Annex F' of the C99 standard, with the 'invalid' and
1001 'divide-by-zero' floating-point exceptions mapping to Python's
1002 ValueError and the 'overflow' floating-point exception mapping to
1003 OverflowError.
1004*/
1005
1006static PyObject *
1007math_1(PyObject *arg, double (*func) (double), int can_overflow)
1008{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow);
Jeffrey Yasskinc2155832008-01-05 20:03:11 +00001010}
1011
1012static PyObject *
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02001013math_2(PyObject *const *args, Py_ssize_t nargs,
1014 double (*func) (double, double), const char *funcname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001015{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 double x, y, r;
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02001017 if (!_PyArg_CheckPositional(funcname, nargs, 2, 2))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 return NULL;
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02001019 x = PyFloat_AsDouble(args[0]);
1020 y = PyFloat_AsDouble(args[1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1022 return NULL;
1023 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 r = (*func)(x, y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 if (Py_IS_NAN(r)) {
1026 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1027 errno = EDOM;
1028 else
1029 errno = 0;
1030 }
1031 else if (Py_IS_INFINITY(r)) {
1032 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
1033 errno = ERANGE;
1034 else
1035 errno = 0;
1036 }
1037 if (errno && is_error(r))
1038 return NULL;
1039 else
1040 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001041}
1042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043#define FUNC1(funcname, func, can_overflow, docstring) \
1044 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
1045 return math_1(args, func, can_overflow); \
1046 }\
1047 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049#define FUNC1A(funcname, func, docstring) \
1050 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
1051 return math_1a(args, func); \
1052 }\
1053 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001054
Fred Drake40c48682000-07-03 18:11:56 +00001055#define FUNC2(funcname, func, docstring) \
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02001056 static PyObject * math_##funcname(PyObject *self, PyObject *const *args, Py_ssize_t nargs) { \
1057 return math_2(args, nargs, func, #funcname); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 }\
1059 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001060
Christian Heimes53876d92008-04-19 00:31:39 +00001061FUNC1(acos, acos, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001062 "acos($module, x, /)\n--\n\n"
Giovanni Cappellottodc3f99f2019-07-13 09:59:55 -04001063 "Return the arc cosine (measured in radians) of x.\n\n"
1064 "The result is between 0 and pi.")
Mark Dickinsonf3718592009-12-21 15:27:41 +00001065FUNC1(acosh, m_acosh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001066 "acosh($module, x, /)\n--\n\n"
1067 "Return the inverse hyperbolic cosine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001068FUNC1(asin, asin, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001069 "asin($module, x, /)\n--\n\n"
Giovanni Cappellottodc3f99f2019-07-13 09:59:55 -04001070 "Return the arc sine (measured in radians) of x.\n\n"
1071 "The result is between -pi/2 and pi/2.")
Mark Dickinsonf3718592009-12-21 15:27:41 +00001072FUNC1(asinh, m_asinh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001073 "asinh($module, x, /)\n--\n\n"
1074 "Return the inverse hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001075FUNC1(atan, atan, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001076 "atan($module, x, /)\n--\n\n"
Giovanni Cappellottodc3f99f2019-07-13 09:59:55 -04001077 "Return the arc tangent (measured in radians) of x.\n\n"
1078 "The result is between -pi/2 and pi/2.")
Christian Heimese57950f2008-04-21 13:08:03 +00001079FUNC2(atan2, m_atan2,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001080 "atan2($module, y, x, /)\n--\n\n"
1081 "Return the arc tangent (measured in radians) of y/x.\n\n"
Tim Petersfe71f812001-08-07 22:10:00 +00001082 "Unlike atan(y/x), the signs of both x and y are considered.")
Mark Dickinsonf3718592009-12-21 15:27:41 +00001083FUNC1(atanh, m_atanh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001084 "atanh($module, x, /)\n--\n\n"
1085 "Return the inverse hyperbolic tangent of x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +00001086
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001087/*[clinic input]
1088math.ceil
1089
1090 x as number: object
1091 /
1092
1093Return the ceiling of x as an Integral.
1094
1095This is the smallest integer >= x.
1096[clinic start generated code]*/
1097
1098static PyObject *
1099math_ceil(PyObject *module, PyObject *number)
1100/*[clinic end generated code: output=6c3b8a78bc201c67 input=2725352806399cab]*/
1101{
Benjamin Petersonce798522012-01-22 11:24:29 -05001102 _Py_IDENTIFIER(__ceil__);
Guido van Rossum13e05de2007-08-23 22:56:55 +00001103
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001104 if (!PyFloat_CheckExact(number)) {
1105 PyObject *method = _PyObject_LookupSpecial(number, &PyId___ceil__);
1106 if (method != NULL) {
1107 PyObject *result = _PyObject_CallNoArg(method);
1108 Py_DECREF(method);
1109 return result;
1110 }
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001111 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 return NULL;
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001113 }
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001114 double x = PyFloat_AsDouble(number);
1115 if (x == -1.0 && PyErr_Occurred())
1116 return NULL;
1117
1118 return PyLong_FromDouble(ceil(x));
Guido van Rossum13e05de2007-08-23 22:56:55 +00001119}
1120
Christian Heimes072c0f12008-01-03 23:01:04 +00001121FUNC2(copysign, copysign,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001122 "copysign($module, x, y, /)\n--\n\n"
1123 "Return a float with the magnitude (absolute value) of x but the sign of y.\n\n"
1124 "On platforms that support signed zeros, copysign(1.0, -0.0)\n"
1125 "returns -1.0.\n")
Christian Heimes53876d92008-04-19 00:31:39 +00001126FUNC1(cos, cos, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001127 "cos($module, x, /)\n--\n\n"
1128 "Return the cosine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001129FUNC1(cosh, cosh, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001130 "cosh($module, x, /)\n--\n\n"
1131 "Return the hyperbolic cosine of x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +00001132FUNC1A(erf, m_erf,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001133 "erf($module, x, /)\n--\n\n"
1134 "Error function at x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +00001135FUNC1A(erfc, m_erfc,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001136 "erfc($module, x, /)\n--\n\n"
1137 "Complementary error function at x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001138FUNC1(exp, exp, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001139 "exp($module, x, /)\n--\n\n"
1140 "Return e raised to the power of x.")
Mark Dickinson664b5112009-12-16 20:23:42 +00001141FUNC1(expm1, m_expm1, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001142 "expm1($module, x, /)\n--\n\n"
1143 "Return exp(x)-1.\n\n"
Mark Dickinson664b5112009-12-16 20:23:42 +00001144 "This function avoids the loss of precision involved in the direct "
1145 "evaluation of exp(x)-1 for small x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001146FUNC1(fabs, fabs, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001147 "fabs($module, x, /)\n--\n\n"
1148 "Return the absolute value of the float x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +00001149
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001150/*[clinic input]
1151math.floor
1152
1153 x as number: object
1154 /
1155
1156Return the floor of x as an Integral.
1157
1158This is the largest integer <= x.
1159[clinic start generated code]*/
1160
1161static PyObject *
1162math_floor(PyObject *module, PyObject *number)
1163/*[clinic end generated code: output=c6a65c4884884b8a input=63af6b5d7ebcc3d6]*/
1164{
Benjamin Petersonce798522012-01-22 11:24:29 -05001165 _Py_IDENTIFIER(__floor__);
Guido van Rossum13e05de2007-08-23 22:56:55 +00001166
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001167 if (!PyFloat_CheckExact(number)) {
1168 PyObject *method = _PyObject_LookupSpecial(number, &PyId___floor__);
1169 if (method != NULL) {
1170 PyObject *result = _PyObject_CallNoArg(method);
1171 Py_DECREF(method);
1172 return result;
1173 }
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001174 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 return NULL;
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001176 }
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001177 double x = PyFloat_AsDouble(number);
1178 if (x == -1.0 && PyErr_Occurred())
1179 return NULL;
1180
1181 return PyLong_FromDouble(floor(x));
Guido van Rossum13e05de2007-08-23 22:56:55 +00001182}
1183
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001184FUNC1A(gamma, m_tgamma,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001185 "gamma($module, x, /)\n--\n\n"
1186 "Gamma function at x.")
Mark Dickinson05d2e082009-12-11 20:17:17 +00001187FUNC1A(lgamma, m_lgamma,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001188 "lgamma($module, x, /)\n--\n\n"
1189 "Natural logarithm of absolute value of Gamma function at x.")
Mark Dickinsonbe64d952010-07-07 16:21:29 +00001190FUNC1(log1p, m_log1p, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001191 "log1p($module, x, /)\n--\n\n"
1192 "Return the natural logarithm of 1+x (base e).\n\n"
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001193 "The result is computed in a way which is accurate for x near zero.")
Mark Dickinsona0ce3752017-04-05 18:34:27 +01001194FUNC2(remainder, m_remainder,
1195 "remainder($module, x, y, /)\n--\n\n"
1196 "Difference between x and the closest integer multiple of y.\n\n"
1197 "Return x - n*y where n*y is the closest integer multiple of y.\n"
1198 "In the case where x is exactly halfway between two multiples of\n"
1199 "y, the nearest even value of n is used. The result is always exact.")
Christian Heimes53876d92008-04-19 00:31:39 +00001200FUNC1(sin, sin, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001201 "sin($module, x, /)\n--\n\n"
1202 "Return the sine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001203FUNC1(sinh, sinh, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001204 "sinh($module, x, /)\n--\n\n"
1205 "Return the hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001206FUNC1(sqrt, sqrt, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001207 "sqrt($module, x, /)\n--\n\n"
1208 "Return the square root of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001209FUNC1(tan, tan, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001210 "tan($module, x, /)\n--\n\n"
1211 "Return the tangent of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001212FUNC1(tanh, tanh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001213 "tanh($module, x, /)\n--\n\n"
1214 "Return the hyperbolic tangent of x.")
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001215
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001216/* Precision summation function as msum() by Raymond Hettinger in
1217 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
1218 enhanced with the exact partials sum and roundoff from Mark
1219 Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
1220 See those links for more details, proofs and other references.
1221
1222 Note 1: IEEE 754R floating point semantics are assumed,
1223 but the current implementation does not re-establish special
1224 value semantics across iterations (i.e. handling -Inf + Inf).
1225
1226 Note 2: No provision is made for intermediate overflow handling;
Georg Brandlf78e02b2008-06-10 17:40:04 +00001227 therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001228 sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
1229 overflow of the first partial sum.
1230
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001231 Note 3: The intermediate values lo, yr, and hi are declared volatile so
1232 aggressive compilers won't algebraically reduce lo to always be exactly 0.0.
Georg Brandlf78e02b2008-06-10 17:40:04 +00001233 Also, the volatile declaration forces the values to be stored in memory as
1234 regular doubles instead of extended long precision (80-bit) values. This
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001235 prevents double rounding because any addition or subtraction of two doubles
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 can be resolved exactly into double-sized hi and lo values. As long as the
Georg Brandlf78e02b2008-06-10 17:40:04 +00001237 hi value gets forced into a double before yr and lo are computed, the extra
1238 bits in downstream extended precision operations (x87 for example) will be
1239 exactly zero and therefore can be losslessly stored back into a double,
1240 thereby preventing double rounding.
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001241
1242 Note 4: A similar implementation is in Modules/cmathmodule.c.
1243 Be sure to update both when making changes.
1244
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001245 Note 5: The signature of math.fsum() differs from builtins.sum()
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001246 because the start argument doesn't make sense in the context of
1247 accurate summation. Since the partials table is collapsed before
1248 returning a result, sum(seq2, start=sum(seq1)) may not equal the
1249 accurate result returned by sum(itertools.chain(seq1, seq2)).
1250*/
1251
1252#define NUM_PARTIALS 32 /* initial partials array size, on stack */
1253
1254/* Extend the partials array p[] by doubling its size. */
1255static int /* non-zero on error */
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001256_fsum_realloc(double **p_ptr, Py_ssize_t n,
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001257 double *ps, Py_ssize_t *m_ptr)
1258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 void *v = NULL;
1260 Py_ssize_t m = *m_ptr;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 m += m; /* double */
Victor Stinner049e5092014-08-17 22:20:00 +02001263 if (n < m && (size_t)m < ((size_t)PY_SSIZE_T_MAX / sizeof(double))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 double *p = *p_ptr;
1265 if (p == ps) {
1266 v = PyMem_Malloc(sizeof(double) * m);
1267 if (v != NULL)
1268 memcpy(v, ps, sizeof(double) * n);
1269 }
1270 else
1271 v = PyMem_Realloc(p, sizeof(double) * m);
1272 }
1273 if (v == NULL) { /* size overflow or no memory */
1274 PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
1275 return 1;
1276 }
1277 *p_ptr = (double*) v;
1278 *m_ptr = m;
1279 return 0;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001280}
1281
1282/* Full precision summation of a sequence of floats.
1283
1284 def msum(iterable):
1285 partials = [] # sorted, non-overlapping partial sums
1286 for x in iterable:
Mark Dickinsonfdb0acc2010-06-25 20:22:24 +00001287 i = 0
1288 for y in partials:
1289 if abs(x) < abs(y):
1290 x, y = y, x
1291 hi = x + y
1292 lo = y - (hi - x)
1293 if lo:
1294 partials[i] = lo
1295 i += 1
1296 x = hi
1297 partials[i:] = [x]
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001298 return sum_exact(partials)
1299
1300 Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
1301 are exactly equal to x+y. The inner loop applies hi/lo summation to each
1302 partial so that the list of partial sums remains exact.
1303
1304 Sum_exact() adds the partial sums exactly and correctly rounds the final
1305 result (using the round-half-to-even rule). The items in partials remain
1306 non-zero, non-special, non-overlapping and strictly increasing in
1307 magnitude, but possibly not all having the same sign.
1308
1309 Depends on IEEE 754 arithmetic guarantees and half-even rounding.
1310*/
1311
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001312/*[clinic input]
1313math.fsum
1314
1315 seq: object
1316 /
1317
1318Return an accurate floating point sum of values in the iterable seq.
1319
1320Assumes IEEE-754 floating point arithmetic.
1321[clinic start generated code]*/
1322
1323static PyObject *
1324math_fsum(PyObject *module, PyObject *seq)
1325/*[clinic end generated code: output=ba5c672b87fe34fc input=c51b7d8caf6f6e82]*/
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001326{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 PyObject *item, *iter, *sum = NULL;
1328 Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
1329 double x, y, t, ps[NUM_PARTIALS], *p = ps;
1330 double xsave, special_sum = 0.0, inf_sum = 0.0;
1331 volatile double hi, yr, lo;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 iter = PyObject_GetIter(seq);
1334 if (iter == NULL)
1335 return NULL;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 for(;;) { /* for x in iterable */
1338 assert(0 <= n && n <= m);
1339 assert((m == NUM_PARTIALS && p == ps) ||
1340 (m > NUM_PARTIALS && p != NULL));
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 item = PyIter_Next(iter);
1343 if (item == NULL) {
1344 if (PyErr_Occurred())
1345 goto _fsum_error;
1346 break;
1347 }
Raymond Hettingercfd735e2019-01-29 20:39:53 -08001348 ASSIGN_DOUBLE(x, item, error_with_item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 Py_DECREF(item);
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 xsave = x;
1352 for (i = j = 0; j < n; j++) { /* for y in partials */
1353 y = p[j];
1354 if (fabs(x) < fabs(y)) {
1355 t = x; x = y; y = t;
1356 }
1357 hi = x + y;
1358 yr = hi - x;
1359 lo = y - yr;
1360 if (lo != 0.0)
1361 p[i++] = lo;
1362 x = hi;
1363 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 n = i; /* ps[i:] = [x] */
1366 if (x != 0.0) {
1367 if (! Py_IS_FINITE(x)) {
1368 /* a nonfinite x could arise either as
1369 a result of intermediate overflow, or
1370 as a result of a nan or inf in the
1371 summands */
1372 if (Py_IS_FINITE(xsave)) {
1373 PyErr_SetString(PyExc_OverflowError,
1374 "intermediate overflow in fsum");
1375 goto _fsum_error;
1376 }
1377 if (Py_IS_INFINITY(xsave))
1378 inf_sum += xsave;
1379 special_sum += xsave;
1380 /* reset partials */
1381 n = 0;
1382 }
1383 else if (n >= m && _fsum_realloc(&p, n, ps, &m))
1384 goto _fsum_error;
1385 else
1386 p[n++] = x;
1387 }
1388 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 if (special_sum != 0.0) {
1391 if (Py_IS_NAN(inf_sum))
1392 PyErr_SetString(PyExc_ValueError,
1393 "-inf + inf in fsum");
1394 else
1395 sum = PyFloat_FromDouble(special_sum);
1396 goto _fsum_error;
1397 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 hi = 0.0;
1400 if (n > 0) {
1401 hi = p[--n];
1402 /* sum_exact(ps, hi) from the top, stop when the sum becomes
1403 inexact. */
1404 while (n > 0) {
1405 x = hi;
1406 y = p[--n];
1407 assert(fabs(y) < fabs(x));
1408 hi = x + y;
1409 yr = hi - x;
1410 lo = y - yr;
1411 if (lo != 0.0)
1412 break;
1413 }
1414 /* Make half-even rounding work across multiple partials.
1415 Needed so that sum([1e-16, 1, 1e16]) will round-up the last
1416 digit to two instead of down to zero (the 1e-16 makes the 1
1417 slightly closer to two). With a potential 1 ULP rounding
1418 error fixed-up, math.fsum() can guarantee commutativity. */
1419 if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
1420 (lo > 0.0 && p[n-1] > 0.0))) {
1421 y = lo * 2.0;
1422 x = hi + y;
1423 yr = x - hi;
1424 if (y == yr)
1425 hi = x;
1426 }
1427 }
1428 sum = PyFloat_FromDouble(hi);
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001429
Raymond Hettingercfd735e2019-01-29 20:39:53 -08001430 _fsum_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 Py_DECREF(iter);
1432 if (p != ps)
1433 PyMem_Free(p);
1434 return sum;
Raymond Hettingercfd735e2019-01-29 20:39:53 -08001435
1436 error_with_item:
1437 Py_DECREF(item);
1438 goto _fsum_error;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001439}
1440
1441#undef NUM_PARTIALS
1442
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001443
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001444static unsigned long
1445count_set_bits(unsigned long n)
1446{
1447 unsigned long count = 0;
1448 while (n != 0) {
1449 ++count;
1450 n &= n - 1; /* clear least significant bit */
1451 }
1452 return count;
1453}
1454
Mark Dickinson73934b92019-05-18 12:29:50 +01001455/* Integer square root
1456
1457Given a nonnegative integer `n`, we want to compute the largest integer
1458`a` for which `a * a <= n`, or equivalently the integer part of the exact
1459square root of `n`.
1460
1461We use an adaptive-precision pure-integer version of Newton's iteration. Given
1462a positive integer `n`, the algorithm produces at each iteration an integer
1463approximation `a` to the square root of `n >> s` for some even integer `s`,
1464with `s` decreasing as the iterations progress. On the final iteration, `s` is
1465zero and we have an approximation to the square root of `n` itself.
1466
1467At every step, the approximation `a` is strictly within 1.0 of the true square
1468root, so we have
1469
1470 (a - 1)**2 < (n >> s) < (a + 1)**2
1471
1472After the final iteration, a check-and-correct step is needed to determine
1473whether `a` or `a - 1` gives the desired integer square root of `n`.
1474
1475The algorithm is remarkable in its simplicity. There's no need for a
1476per-iteration check-and-correct step, and termination is straightforward: the
1477number of iterations is known in advance (it's exactly `floor(log2(log2(n)))`
1478for `n > 1`). The only tricky part of the correctness proof is in establishing
1479that the bound `(a - 1)**2 < (n >> s) < (a + 1)**2` is maintained from one
1480iteration to the next. A sketch of the proof of this is given below.
1481
1482In addition to the proof sketch, a formal, computer-verified proof
1483of correctness (using Lean) of an equivalent recursive algorithm can be found
1484here:
1485
1486 https://github.com/mdickinson/snippets/blob/master/proofs/isqrt/src/isqrt.lean
1487
1488
1489Here's Python code equivalent to the C implementation below:
1490
1491 def isqrt(n):
1492 """
1493 Return the integer part of the square root of the input.
1494 """
1495 n = operator.index(n)
1496
1497 if n < 0:
1498 raise ValueError("isqrt() argument must be nonnegative")
1499 if n == 0:
1500 return 0
1501
1502 c = (n.bit_length() - 1) // 2
1503 a = 1
1504 d = 0
1505 for s in reversed(range(c.bit_length())):
Mark Dickinson2dfeaa92019-06-16 17:53:21 +01001506 # Loop invariant: (a-1)**2 < (n >> 2*(c - d)) < (a+1)**2
Mark Dickinson73934b92019-05-18 12:29:50 +01001507 e = d
1508 d = c >> s
1509 a = (a << d - e - 1) + (n >> 2*c - e - d + 1) // a
Mark Dickinson73934b92019-05-18 12:29:50 +01001510
1511 return a - (a*a > n)
1512
1513
1514Sketch of proof of correctness
1515------------------------------
1516
1517The delicate part of the correctness proof is showing that the loop invariant
1518is preserved from one iteration to the next. That is, just before the line
1519
1520 a = (a << d - e - 1) + (n >> 2*c - e - d + 1) // a
1521
1522is executed in the above code, we know that
1523
1524 (1) (a - 1)**2 < (n >> 2*(c - e)) < (a + 1)**2.
1525
1526(since `e` is always the value of `d` from the previous iteration). We must
1527prove that after that line is executed, we have
1528
1529 (a - 1)**2 < (n >> 2*(c - d)) < (a + 1)**2
1530
Min ho Kimf7d72e42019-07-06 07:39:32 +10001531To facilitate the proof, we make some changes of notation. Write `m` for
Mark Dickinson73934b92019-05-18 12:29:50 +01001532`n >> 2*(c-d)`, and write `b` for the new value of `a`, so
1533
1534 b = (a << d - e - 1) + (n >> 2*c - e - d + 1) // a
1535
1536or equivalently:
1537
1538 (2) b = (a << d - e - 1) + (m >> d - e + 1) // a
1539
1540Then we can rewrite (1) as:
1541
1542 (3) (a - 1)**2 < (m >> 2*(d - e)) < (a + 1)**2
1543
1544and we must show that (b - 1)**2 < m < (b + 1)**2.
1545
1546From this point on, we switch to mathematical notation, so `/` means exact
1547division rather than integer division and `^` is used for exponentiation. We
1548use the `√` symbol for the exact square root. In (3), we can remove the
1549implicit floor operation to give:
1550
1551 (4) (a - 1)^2 < m / 4^(d - e) < (a + 1)^2
1552
1553Taking square roots throughout (4), scaling by `2^(d-e)`, and rearranging gives
1554
1555 (5) 0 <= | 2^(d-e)a - √m | < 2^(d-e)
1556
1557Squaring and dividing through by `2^(d-e+1) a` gives
1558
1559 (6) 0 <= 2^(d-e-1) a + m / (2^(d-e+1) a) - √m < 2^(d-e-1) / a
1560
1561We'll show below that `2^(d-e-1) <= a`. Given that, we can replace the
1562right-hand side of (6) with `1`, and now replacing the central
1563term `m / (2^(d-e+1) a)` with its floor in (6) gives
1564
1565 (7) -1 < 2^(d-e-1) a + m // 2^(d-e+1) a - √m < 1
1566
1567Or equivalently, from (2):
1568
1569 (7) -1 < b - √m < 1
1570
1571and rearranging gives that `(b-1)^2 < m < (b+1)^2`, which is what we needed
1572to prove.
1573
1574We're not quite done: we still have to prove the inequality `2^(d - e - 1) <=
1575a` that was used to get line (7) above. From the definition of `c`, we have
1576`4^c <= n`, which implies
1577
1578 (8) 4^d <= m
1579
1580also, since `e == d >> 1`, `d` is at most `2e + 1`, from which it follows
1581that `2d - 2e - 1 <= d` and hence that
1582
1583 (9) 4^(2d - 2e - 1) <= m
1584
1585Dividing both sides by `4^(d - e)` gives
1586
1587 (10) 4^(d - e - 1) <= m / 4^(d - e)
1588
1589But we know from (4) that `m / 4^(d-e) < (a + 1)^2`, hence
1590
1591 (11) 4^(d - e - 1) < (a + 1)^2
1592
1593Now taking square roots of both sides and observing that both `2^(d-e-1)` and
1594`a` are integers gives `2^(d - e - 1) <= a`, which is what we needed. This
1595completes the proof sketch.
1596
1597*/
1598
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001599
1600/* Approximate square root of a large 64-bit integer.
1601
1602 Given `n` satisfying `2**62 <= n < 2**64`, return `a`
1603 satisfying `(a - 1)**2 < n < (a + 1)**2`. */
1604
1605static uint64_t
1606_approximate_isqrt(uint64_t n)
1607{
1608 uint32_t u = 1U + (n >> 62);
1609 u = (u << 1) + (n >> 59) / u;
1610 u = (u << 3) + (n >> 53) / u;
1611 u = (u << 7) + (n >> 41) / u;
1612 return (u << 15) + (n >> 17) / u;
1613}
1614
Mark Dickinson73934b92019-05-18 12:29:50 +01001615/*[clinic input]
1616math.isqrt
1617
1618 n: object
1619 /
1620
1621Return the integer part of the square root of the input.
1622[clinic start generated code]*/
1623
1624static PyObject *
1625math_isqrt(PyObject *module, PyObject *n)
1626/*[clinic end generated code: output=35a6f7f980beab26 input=5b6e7ae4fa6c43d6]*/
1627{
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001628 int a_too_large, c_bit_length;
Mark Dickinson73934b92019-05-18 12:29:50 +01001629 size_t c, d;
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001630 uint64_t m, u;
Mark Dickinson73934b92019-05-18 12:29:50 +01001631 PyObject *a = NULL, *b;
1632
1633 n = PyNumber_Index(n);
1634 if (n == NULL) {
1635 return NULL;
1636 }
1637
1638 if (_PyLong_Sign(n) < 0) {
1639 PyErr_SetString(
1640 PyExc_ValueError,
1641 "isqrt() argument must be nonnegative");
1642 goto error;
1643 }
1644 if (_PyLong_Sign(n) == 0) {
1645 Py_DECREF(n);
1646 return PyLong_FromLong(0);
1647 }
1648
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001649 /* c = (n.bit_length() - 1) // 2 */
Mark Dickinson73934b92019-05-18 12:29:50 +01001650 c = _PyLong_NumBits(n);
1651 if (c == (size_t)(-1)) {
1652 goto error;
1653 }
1654 c = (c - 1U) / 2U;
1655
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001656 /* Fast path: if c <= 31 then n < 2**64 and we can compute directly with a
1657 fast, almost branch-free algorithm. In the final correction, we use `u*u
1658 - 1 >= m` instead of the simpler `u*u > m` in order to get the correct
1659 result in the corner case where `u=2**32`. */
1660 if (c <= 31U) {
1661 m = (uint64_t)PyLong_AsUnsignedLongLong(n);
1662 Py_DECREF(n);
1663 if (m == (uint64_t)(-1) && PyErr_Occurred()) {
1664 return NULL;
1665 }
1666 u = _approximate_isqrt(m << (62U - 2U*c)) >> (31U - c);
1667 u -= u * u - 1U >= m;
1668 return PyLong_FromUnsignedLongLong((unsigned long long)u);
Mark Dickinson73934b92019-05-18 12:29:50 +01001669 }
1670
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001671 /* Slow path: n >= 2**64. We perform the first five iterations in C integer
1672 arithmetic, then switch to using Python long integers. */
1673
1674 /* From n >= 2**64 it follows that c.bit_length() >= 6. */
1675 c_bit_length = 6;
1676 while ((c >> c_bit_length) > 0U) {
1677 ++c_bit_length;
1678 }
1679
1680 /* Initialise d and a. */
1681 d = c >> (c_bit_length - 5);
1682 b = _PyLong_Rshift(n, 2U*c - 62U);
1683 if (b == NULL) {
1684 goto error;
1685 }
1686 m = (uint64_t)PyLong_AsUnsignedLongLong(b);
1687 Py_DECREF(b);
1688 if (m == (uint64_t)(-1) && PyErr_Occurred()) {
1689 goto error;
1690 }
1691 u = _approximate_isqrt(m) >> (31U - d);
1692 a = PyLong_FromUnsignedLongLong((unsigned long long)u);
Mark Dickinson73934b92019-05-18 12:29:50 +01001693 if (a == NULL) {
1694 goto error;
1695 }
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001696
1697 for (int s = c_bit_length - 6; s >= 0; --s) {
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03001698 PyObject *q;
Mark Dickinson73934b92019-05-18 12:29:50 +01001699 size_t e = d;
1700
1701 d = c >> s;
1702
1703 /* q = (n >> 2*c - e - d + 1) // a */
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03001704 q = _PyLong_Rshift(n, 2U*c - d - e + 1U);
Mark Dickinson73934b92019-05-18 12:29:50 +01001705 if (q == NULL) {
1706 goto error;
1707 }
1708 Py_SETREF(q, PyNumber_FloorDivide(q, a));
1709 if (q == NULL) {
1710 goto error;
1711 }
1712
1713 /* a = (a << d - 1 - e) + q */
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03001714 Py_SETREF(a, _PyLong_Lshift(a, d - 1U - e));
Mark Dickinson73934b92019-05-18 12:29:50 +01001715 if (a == NULL) {
1716 Py_DECREF(q);
1717 goto error;
1718 }
1719 Py_SETREF(a, PyNumber_Add(a, q));
1720 Py_DECREF(q);
1721 if (a == NULL) {
1722 goto error;
1723 }
1724 }
1725
1726 /* The correct result is either a or a - 1. Figure out which, and
1727 decrement a if necessary. */
1728
1729 /* a_too_large = n < a * a */
1730 b = PyNumber_Multiply(a, a);
1731 if (b == NULL) {
1732 goto error;
1733 }
1734 a_too_large = PyObject_RichCompareBool(n, b, Py_LT);
1735 Py_DECREF(b);
1736 if (a_too_large == -1) {
1737 goto error;
1738 }
1739
1740 if (a_too_large) {
1741 Py_SETREF(a, PyNumber_Subtract(a, _PyLong_One));
1742 }
1743 Py_DECREF(n);
1744 return a;
1745
1746 error:
1747 Py_XDECREF(a);
1748 Py_DECREF(n);
1749 return NULL;
1750}
1751
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001752/* Divide-and-conquer factorial algorithm
1753 *
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07001754 * Based on the formula and pseudo-code provided at:
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001755 * http://www.luschny.de/math/factorial/binarysplitfact.html
1756 *
1757 * Faster algorithms exist, but they're more complicated and depend on
Ezio Melotti9527afd2010-07-08 15:03:02 +00001758 * a fast prime factorization algorithm.
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001759 *
1760 * Notes on the algorithm
1761 * ----------------------
1762 *
1763 * factorial(n) is written in the form 2**k * m, with m odd. k and m are
1764 * computed separately, and then combined using a left shift.
1765 *
1766 * The function factorial_odd_part computes the odd part m (i.e., the greatest
1767 * odd divisor) of factorial(n), using the formula:
1768 *
1769 * factorial_odd_part(n) =
1770 *
1771 * product_{i >= 0} product_{0 < j <= n / 2**i, j odd} j
1772 *
1773 * Example: factorial_odd_part(20) =
1774 *
1775 * (1) *
1776 * (1) *
1777 * (1 * 3 * 5) *
1778 * (1 * 3 * 5 * 7 * 9)
1779 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1780 *
1781 * Here i goes from large to small: the first term corresponds to i=4 (any
1782 * larger i gives an empty product), and the last term corresponds to i=0.
1783 * Each term can be computed from the last by multiplying by the extra odd
1784 * numbers required: e.g., to get from the penultimate term to the last one,
1785 * we multiply by (11 * 13 * 15 * 17 * 19).
1786 *
1787 * To see a hint of why this formula works, here are the same numbers as above
1788 * but with the even parts (i.e., the appropriate powers of 2) included. For
1789 * each subterm in the product for i, we multiply that subterm by 2**i:
1790 *
1791 * factorial(20) =
1792 *
1793 * (16) *
1794 * (8) *
1795 * (4 * 12 * 20) *
1796 * (2 * 6 * 10 * 14 * 18) *
1797 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1798 *
1799 * The factorial_partial_product function computes the product of all odd j in
1800 * range(start, stop) for given start and stop. It's used to compute the
1801 * partial products like (11 * 13 * 15 * 17 * 19) in the example above. It
1802 * operates recursively, repeatedly splitting the range into two roughly equal
1803 * pieces until the subranges are small enough to be computed using only C
1804 * integer arithmetic.
1805 *
1806 * The two-valuation k (i.e., the exponent of the largest power of 2 dividing
1807 * the factorial) is computed independently in the main math_factorial
1808 * function. By standard results, its value is:
1809 *
1810 * two_valuation = n//2 + n//4 + n//8 + ....
1811 *
1812 * It can be shown (e.g., by complete induction on n) that two_valuation is
1813 * equal to n - count_set_bits(n), where count_set_bits(n) gives the number of
1814 * '1'-bits in the binary expansion of n.
1815 */
1816
1817/* factorial_partial_product: Compute product(range(start, stop, 2)) using
1818 * divide and conquer. Assumes start and stop are odd and stop > start.
1819 * max_bits must be >= bit_length(stop - 2). */
1820
1821static PyObject *
1822factorial_partial_product(unsigned long start, unsigned long stop,
1823 unsigned long max_bits)
1824{
1825 unsigned long midpoint, num_operands;
1826 PyObject *left = NULL, *right = NULL, *result = NULL;
1827
1828 /* If the return value will fit an unsigned long, then we can
1829 * multiply in a tight, fast loop where each multiply is O(1).
1830 * Compute an upper bound on the number of bits required to store
1831 * the answer.
1832 *
1833 * Storing some integer z requires floor(lg(z))+1 bits, which is
1834 * conveniently the value returned by bit_length(z). The
1835 * product x*y will require at most
1836 * bit_length(x) + bit_length(y) bits to store, based
1837 * on the idea that lg product = lg x + lg y.
1838 *
1839 * We know that stop - 2 is the largest number to be multiplied. From
1840 * there, we have: bit_length(answer) <= num_operands *
1841 * bit_length(stop - 2)
1842 */
1843
1844 num_operands = (stop - start) / 2;
1845 /* The "num_operands <= 8 * SIZEOF_LONG" check guards against the
1846 * unlikely case of an overflow in num_operands * max_bits. */
1847 if (num_operands <= 8 * SIZEOF_LONG &&
1848 num_operands * max_bits <= 8 * SIZEOF_LONG) {
1849 unsigned long j, total;
1850 for (total = start, j = start + 2; j < stop; j += 2)
1851 total *= j;
1852 return PyLong_FromUnsignedLong(total);
1853 }
1854
1855 /* find midpoint of range(start, stop), rounded up to next odd number. */
1856 midpoint = (start + num_operands) | 1;
1857 left = factorial_partial_product(start, midpoint,
Niklas Fiekasc5b79002020-01-16 15:09:19 +01001858 _Py_bit_length(midpoint - 2));
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001859 if (left == NULL)
1860 goto error;
1861 right = factorial_partial_product(midpoint, stop, max_bits);
1862 if (right == NULL)
1863 goto error;
1864 result = PyNumber_Multiply(left, right);
1865
1866 error:
1867 Py_XDECREF(left);
1868 Py_XDECREF(right);
1869 return result;
1870}
1871
1872/* factorial_odd_part: compute the odd part of factorial(n). */
1873
1874static PyObject *
1875factorial_odd_part(unsigned long n)
1876{
1877 long i;
1878 unsigned long v, lower, upper;
1879 PyObject *partial, *tmp, *inner, *outer;
1880
1881 inner = PyLong_FromLong(1);
1882 if (inner == NULL)
1883 return NULL;
1884 outer = inner;
1885 Py_INCREF(outer);
1886
1887 upper = 3;
Niklas Fiekasc5b79002020-01-16 15:09:19 +01001888 for (i = _Py_bit_length(n) - 2; i >= 0; i--) {
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001889 v = n >> i;
1890 if (v <= 2)
1891 continue;
1892 lower = upper;
1893 /* (v + 1) | 1 = least odd integer strictly larger than n / 2**i */
1894 upper = (v + 1) | 1;
1895 /* Here inner is the product of all odd integers j in the range (0,
1896 n/2**(i+1)]. The factorial_partial_product call below gives the
1897 product of all odd integers j in the range (n/2**(i+1), n/2**i]. */
Niklas Fiekasc5b79002020-01-16 15:09:19 +01001898 partial = factorial_partial_product(lower, upper, _Py_bit_length(upper-2));
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001899 /* inner *= partial */
1900 if (partial == NULL)
1901 goto error;
1902 tmp = PyNumber_Multiply(inner, partial);
1903 Py_DECREF(partial);
1904 if (tmp == NULL)
1905 goto error;
1906 Py_DECREF(inner);
1907 inner = tmp;
1908 /* Now inner is the product of all odd integers j in the range (0,
1909 n/2**i], giving the inner product in the formula above. */
1910
1911 /* outer *= inner; */
1912 tmp = PyNumber_Multiply(outer, inner);
1913 if (tmp == NULL)
1914 goto error;
1915 Py_DECREF(outer);
1916 outer = tmp;
1917 }
Mark Dickinson76464492012-10-25 10:46:28 +01001918 Py_DECREF(inner);
1919 return outer;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001920
1921 error:
1922 Py_DECREF(outer);
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001923 Py_DECREF(inner);
Mark Dickinson76464492012-10-25 10:46:28 +01001924 return NULL;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001925}
1926
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001927
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001928/* Lookup table for small factorial values */
1929
1930static const unsigned long SmallFactorials[] = {
1931 1, 1, 2, 6, 24, 120, 720, 5040, 40320,
1932 362880, 3628800, 39916800, 479001600,
1933#if SIZEOF_LONG >= 8
1934 6227020800, 87178291200, 1307674368000,
1935 20922789888000, 355687428096000, 6402373705728000,
1936 121645100408832000, 2432902008176640000
1937#endif
1938};
1939
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001940/*[clinic input]
1941math.factorial
1942
1943 x as arg: object
1944 /
1945
1946Find x!.
1947
1948Raise a ValueError if x is negative or non-integral.
1949[clinic start generated code]*/
1950
Barry Warsaw8b43b191996-12-09 22:32:36 +00001951static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001952math_factorial(PyObject *module, PyObject *arg)
1953/*[clinic end generated code: output=6686f26fae00e9ca input=6d1c8105c0d91fb4]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001954{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03001955 long x, two_valuation;
Mark Dickinson5990d282014-04-10 09:29:39 -04001956 int overflow;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03001957 PyObject *result, *odd_part, *pyint_form;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 if (PyFloat_Check(arg)) {
Serhiy Storchaka231aad32019-06-17 16:57:27 +03001960 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1961 "Using factorial() with floats is deprecated",
1962 1) < 0)
1963 {
1964 return NULL;
1965 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 PyObject *lx;
1967 double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
1968 if (!(Py_IS_FINITE(dx) && dx == floor(dx))) {
1969 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001970 "factorial() only accepts integral values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 return NULL;
1972 }
1973 lx = PyLong_FromDouble(dx);
1974 if (lx == NULL)
1975 return NULL;
Mark Dickinson5990d282014-04-10 09:29:39 -04001976 x = PyLong_AsLongAndOverflow(lx, &overflow);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 Py_DECREF(lx);
1978 }
Pablo Galindoe9ba3702018-09-03 22:20:06 +01001979 else {
1980 pyint_form = PyNumber_Index(arg);
1981 if (pyint_form == NULL) {
1982 return NULL;
1983 }
1984 x = PyLong_AsLongAndOverflow(pyint_form, &overflow);
1985 Py_DECREF(pyint_form);
1986 }
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001987
Mark Dickinson5990d282014-04-10 09:29:39 -04001988 if (x == -1 && PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 return NULL;
Mark Dickinson5990d282014-04-10 09:29:39 -04001990 }
1991 else if (overflow == 1) {
1992 PyErr_Format(PyExc_OverflowError,
1993 "factorial() argument should not exceed %ld",
1994 LONG_MAX);
1995 return NULL;
1996 }
1997 else if (overflow == -1 || x < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001999 "factorial() not defined for negative values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 return NULL;
2001 }
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002002
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002003 /* use lookup table if x is small */
Victor Stinner63941882011-09-29 00:42:28 +02002004 if (x < (long)Py_ARRAY_LENGTH(SmallFactorials))
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002005 return PyLong_FromUnsignedLong(SmallFactorials[x]);
2006
2007 /* else express in the form odd_part * 2**two_valuation, and compute as
2008 odd_part << two_valuation. */
2009 odd_part = factorial_odd_part(x);
2010 if (odd_part == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03002012 two_valuation = x - count_set_bits(x);
2013 result = _PyLong_Lshift(odd_part, two_valuation);
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002014 Py_DECREF(odd_part);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 return result;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002016}
2017
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002018
2019/*[clinic input]
2020math.trunc
2021
2022 x: object
2023 /
2024
2025Truncates the Real x to the nearest Integral toward 0.
2026
2027Uses the __trunc__ magic method.
2028[clinic start generated code]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002029
2030static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002031math_trunc(PyObject *module, PyObject *x)
2032/*[clinic end generated code: output=34b9697b707e1031 input=2168b34e0a09134d]*/
Christian Heimes400adb02008-02-01 08:12:03 +00002033{
Benjamin Petersonce798522012-01-22 11:24:29 -05002034 _Py_IDENTIFIER(__trunc__);
Benjamin Petersonb0125892010-07-02 13:35:17 +00002035 PyObject *trunc, *result;
Christian Heimes400adb02008-02-01 08:12:03 +00002036
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02002037 if (PyFloat_CheckExact(x)) {
2038 return PyFloat_Type.tp_as_number->nb_int(x);
2039 }
2040
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002041 if (Py_TYPE(x)->tp_dict == NULL) {
2042 if (PyType_Ready(Py_TYPE(x)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 return NULL;
2044 }
Christian Heimes400adb02008-02-01 08:12:03 +00002045
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002046 trunc = _PyObject_LookupSpecial(x, &PyId___trunc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 if (trunc == NULL) {
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00002048 if (!PyErr_Occurred())
2049 PyErr_Format(PyExc_TypeError,
2050 "type %.100s doesn't define __trunc__ method",
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002051 Py_TYPE(x)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 return NULL;
2053 }
Victor Stinnerf17c3de2016-12-06 18:46:19 +01002054 result = _PyObject_CallNoArg(trunc);
Benjamin Petersonb0125892010-07-02 13:35:17 +00002055 Py_DECREF(trunc);
2056 return result;
Christian Heimes400adb02008-02-01 08:12:03 +00002057}
2058
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002059
2060/*[clinic input]
2061math.frexp
2062
2063 x: double
2064 /
2065
2066Return the mantissa and exponent of x, as pair (m, e).
2067
2068m is a float and e is an int, such that x = m * 2.**e.
2069If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.
2070[clinic start generated code]*/
Christian Heimes400adb02008-02-01 08:12:03 +00002071
2072static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002073math_frexp_impl(PyObject *module, double x)
2074/*[clinic end generated code: output=03e30d252a15ad4a input=96251c9e208bc6e9]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00002075{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 /* deal with special cases directly, to sidestep platform
2078 differences */
2079 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
2080 i = 0;
2081 }
2082 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 x = frexp(x, &i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 }
2085 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +00002086}
2087
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002088
2089/*[clinic input]
2090math.ldexp
2091
2092 x: double
2093 i: object
2094 /
2095
2096Return x * (2**i).
2097
2098This is essentially the inverse of frexp().
2099[clinic start generated code]*/
Guido van Rossumc6e22901998-12-04 19:26:43 +00002100
Barry Warsaw8b43b191996-12-09 22:32:36 +00002101static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002102math_ldexp_impl(PyObject *module, double x, PyObject *i)
2103/*[clinic end generated code: output=b6892f3c2df9cc6a input=17d5970c1a40a8c1]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00002104{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002105 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 long exp;
2107 int overflow;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00002108
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002109 if (PyLong_Check(i)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 /* on overflow, replace exponent with either LONG_MAX
2111 or LONG_MIN, depending on the sign. */
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002112 exp = PyLong_AsLongAndOverflow(i, &overflow);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 if (exp == -1 && PyErr_Occurred())
2114 return NULL;
2115 if (overflow)
2116 exp = overflow < 0 ? LONG_MIN : LONG_MAX;
2117 }
2118 else {
2119 PyErr_SetString(PyExc_TypeError,
Serhiy Storchaka95949422013-08-27 19:40:23 +03002120 "Expected an int as second argument to ldexp.");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 return NULL;
2122 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00002123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 if (x == 0. || !Py_IS_FINITE(x)) {
2125 /* NaNs, zeros and infinities are returned unchanged */
2126 r = x;
2127 errno = 0;
2128 } else if (exp > INT_MAX) {
2129 /* overflow */
2130 r = copysign(Py_HUGE_VAL, x);
2131 errno = ERANGE;
2132 } else if (exp < INT_MIN) {
2133 /* underflow to +-0 */
2134 r = copysign(0., x);
2135 errno = 0;
2136 } else {
2137 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 r = ldexp(x, (int)exp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 if (Py_IS_INFINITY(r))
2140 errno = ERANGE;
2141 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00002142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 if (errno && is_error(r))
2144 return NULL;
2145 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +00002146}
2147
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002148
2149/*[clinic input]
2150math.modf
2151
2152 x: double
2153 /
2154
2155Return the fractional and integer parts of x.
2156
2157Both results carry the sign of x and are floats.
2158[clinic start generated code]*/
Guido van Rossumc6e22901998-12-04 19:26:43 +00002159
Barry Warsaw8b43b191996-12-09 22:32:36 +00002160static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002161math_modf_impl(PyObject *module, double x)
2162/*[clinic end generated code: output=90cee0260014c3c0 input=b4cfb6786afd9035]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00002163{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002164 double y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 /* some platforms don't do the right thing for NaNs and
2166 infinities, so we take care of special cases directly. */
2167 if (!Py_IS_FINITE(x)) {
2168 if (Py_IS_INFINITY(x))
2169 return Py_BuildValue("(dd)", copysign(0., x), x);
2170 else if (Py_IS_NAN(x))
2171 return Py_BuildValue("(dd)", x, x);
2172 }
Christian Heimesa342c012008-04-20 21:01:16 +00002173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 x = modf(x, &y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +00002177}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002178
Guido van Rossumc6e22901998-12-04 19:26:43 +00002179
Serhiy Storchaka95949422013-08-27 19:40:23 +03002180/* A decent logarithm is easy to compute even for huge ints, but libm can't
Tim Peters78526162001-09-05 00:53:45 +00002181 do that by itself -- loghelper can. func is log or log10, and name is
Serhiy Storchaka95949422013-08-27 19:40:23 +03002182 "log" or "log10". Note that overflow of the result isn't possible: an int
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002183 can contain no more than INT_MAX * SHIFT bits, so has value certainly less
2184 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 +00002185 small enough to fit in an IEEE single. log and log10 are even smaller.
Serhiy Storchaka95949422013-08-27 19:40:23 +03002186 However, intermediate overflow is possible for an int if the number of bits
2187 in that int is larger than PY_SSIZE_T_MAX. */
Tim Peters78526162001-09-05 00:53:45 +00002188
2189static PyObject*
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002190loghelper(PyObject* arg, double (*func)(double), const char *funcname)
Tim Peters78526162001-09-05 00:53:45 +00002191{
Serhiy Storchaka95949422013-08-27 19:40:23 +03002192 /* If it is int, do it ourselves. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 if (PyLong_Check(arg)) {
Mark Dickinsonc6037172010-09-29 19:06:36 +00002194 double x, result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 Py_ssize_t e;
Mark Dickinsonc6037172010-09-29 19:06:36 +00002196
2197 /* Negative or zero inputs give a ValueError. */
2198 if (Py_SIZE(arg) <= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 PyErr_SetString(PyExc_ValueError,
2200 "math domain error");
2201 return NULL;
2202 }
Mark Dickinsonfa41e602010-09-28 07:22:27 +00002203
Mark Dickinsonc6037172010-09-29 19:06:36 +00002204 x = PyLong_AsDouble(arg);
2205 if (x == -1.0 && PyErr_Occurred()) {
2206 if (!PyErr_ExceptionMatches(PyExc_OverflowError))
2207 return NULL;
2208 /* Here the conversion to double overflowed, but it's possible
2209 to compute the log anyway. Clear the exception and continue. */
2210 PyErr_Clear();
2211 x = _PyLong_Frexp((PyLongObject *)arg, &e);
2212 if (x == -1.0 && PyErr_Occurred())
2213 return NULL;
2214 /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */
2215 result = func(x) + func(2.0) * e;
2216 }
2217 else
2218 /* Successfully converted x to a double. */
2219 result = func(x);
2220 return PyFloat_FromDouble(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 }
Tim Peters78526162001-09-05 00:53:45 +00002222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 /* Else let libm handle it by itself. */
2224 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +00002225}
2226
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002227
2228/*[clinic input]
2229math.log
2230
2231 x: object
2232 [
2233 base: object(c_default="NULL") = math.e
2234 ]
2235 /
2236
2237Return the logarithm of x to the given base.
2238
2239If the base not specified, returns the natural logarithm (base e) of x.
2240[clinic start generated code]*/
2241
Tim Peters78526162001-09-05 00:53:45 +00002242static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002243math_log_impl(PyObject *module, PyObject *x, int group_right_1,
2244 PyObject *base)
2245/*[clinic end generated code: output=7b5a39e526b73fc9 input=0f62d5726cbfebbd]*/
Tim Peters78526162001-09-05 00:53:45 +00002246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 PyObject *num, *den;
2248 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +00002249
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002250 num = loghelper(x, m_log, "log");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 if (num == NULL || base == NULL)
2252 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +00002253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 den = loghelper(base, m_log, "log");
2255 if (den == NULL) {
2256 Py_DECREF(num);
2257 return NULL;
2258 }
Raymond Hettinger866964c2002-12-14 19:51:34 +00002259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 ans = PyNumber_TrueDivide(num, den);
2261 Py_DECREF(num);
2262 Py_DECREF(den);
2263 return ans;
Tim Peters78526162001-09-05 00:53:45 +00002264}
2265
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002266
2267/*[clinic input]
2268math.log2
2269
2270 x: object
2271 /
2272
2273Return the base 2 logarithm of x.
2274[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002275
2276static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002277math_log2(PyObject *module, PyObject *x)
2278/*[clinic end generated code: output=5425899a4d5d6acb input=08321262bae4f39b]*/
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02002279{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002280 return loghelper(x, m_log2, "log2");
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02002281}
2282
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002283
2284/*[clinic input]
2285math.log10
2286
2287 x: object
2288 /
2289
2290Return the base 10 logarithm of x.
2291[clinic start generated code]*/
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02002292
2293static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002294math_log10(PyObject *module, PyObject *x)
2295/*[clinic end generated code: output=be72a64617df9c6f input=b2469d02c6469e53]*/
Tim Peters78526162001-09-05 00:53:45 +00002296{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002297 return loghelper(x, m_log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +00002298}
2299
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002300
2301/*[clinic input]
2302math.fmod
2303
2304 x: double
2305 y: double
2306 /
2307
2308Return fmod(x, y), according to platform C.
2309
2310x % y may differ.
2311[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002312
Christian Heimes53876d92008-04-19 00:31:39 +00002313static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002314math_fmod_impl(PyObject *module, double x, double y)
2315/*[clinic end generated code: output=7559d794343a27b5 input=4f84caa8cfc26a03]*/
Christian Heimes53876d92008-04-19 00:31:39 +00002316{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002317 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 /* fmod(x, +/-Inf) returns x for finite x. */
2319 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
2320 return PyFloat_FromDouble(x);
2321 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 r = fmod(x, y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 if (Py_IS_NAN(r)) {
2324 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
2325 errno = EDOM;
2326 else
2327 errno = 0;
2328 }
2329 if (errno && is_error(r))
2330 return NULL;
2331 else
2332 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00002333}
2334
Raymond Hettinger13990742018-08-11 11:26:36 -07002335/*
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002336Given an *n* length *vec* of values and a value *max*, compute:
Raymond Hettinger13990742018-08-11 11:26:36 -07002337
Raymond Hettingerc630e102018-08-11 18:39:05 -07002338 max * sqrt(sum((x / max) ** 2 for x in vec))
Raymond Hettinger13990742018-08-11 11:26:36 -07002339
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002340The value of the *max* variable must be non-negative and
Raymond Hettinger216aaaa2018-11-09 01:06:02 -08002341equal to the absolute value of the largest magnitude
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002342entry in the vector. If n==0, then *max* should be 0.0.
2343If an infinity is present in the vec, *max* should be INF.
Raymond Hettingerc630e102018-08-11 18:39:05 -07002344
2345The *found_nan* variable indicates whether some member of
2346the *vec* is a NaN.
Raymond Hettinger21786f52018-08-28 22:47:24 -07002347
2348To improve accuracy and to increase the number of cases where
2349vector_norm() is commutative, we use a variant of Neumaier
2350summation specialized to exploit that we always know that
2351|csum| >= |x|.
2352
2353The *csum* variable tracks the cumulative sum and *frac* tracks
2354the cumulative fractional errors at each step. Since this
2355variant assumes that |csum| >= |x| at each step, we establish
2356the precondition by starting the accumulation from 1.0 which
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002357represents the largest possible value of (x/max)**2.
2358
2359After the loop is finished, the initial 1.0 is subtracted out
2360for a net zero effect on the final sum. Since *csum* will be
2361greater than 1.0, the subtraction of 1.0 will not cause
2362fractional digits to be dropped from *csum*.
Raymond Hettinger21786f52018-08-28 22:47:24 -07002363
Raymond Hettinger13990742018-08-11 11:26:36 -07002364*/
2365
2366static inline double
Raymond Hettingerc630e102018-08-11 18:39:05 -07002367vector_norm(Py_ssize_t n, double *vec, double max, int found_nan)
Raymond Hettinger13990742018-08-11 11:26:36 -07002368{
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002369 double x, csum = 1.0, oldcsum, frac = 0.0;
Raymond Hettinger13990742018-08-11 11:26:36 -07002370 Py_ssize_t i;
2371
Raymond Hettingerc630e102018-08-11 18:39:05 -07002372 if (Py_IS_INFINITY(max)) {
2373 return max;
2374 }
2375 if (found_nan) {
2376 return Py_NAN;
2377 }
Raymond Hettingerf3267142018-09-02 13:34:21 -07002378 if (max == 0.0 || n <= 1) {
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002379 return max;
Raymond Hettinger13990742018-08-11 11:26:36 -07002380 }
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002381 for (i=0 ; i < n ; i++) {
Raymond Hettinger13990742018-08-11 11:26:36 -07002382 x = vec[i];
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002383 assert(Py_IS_FINITE(x) && fabs(x) <= max);
Raymond Hettinger13990742018-08-11 11:26:36 -07002384 x /= max;
Raymond Hettinger21786f52018-08-28 22:47:24 -07002385 x = x*x;
Raymond Hettinger13990742018-08-11 11:26:36 -07002386 oldcsum = csum;
2387 csum += x;
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002388 assert(csum >= x);
Raymond Hettinger21786f52018-08-28 22:47:24 -07002389 frac += (oldcsum - csum) + x;
Raymond Hettinger13990742018-08-11 11:26:36 -07002390 }
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002391 return max * sqrt(csum - 1.0 + frac);
Raymond Hettinger13990742018-08-11 11:26:36 -07002392}
2393
Raymond Hettingerc630e102018-08-11 18:39:05 -07002394#define NUM_STACK_ELEMS 16
2395
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002396/*[clinic input]
2397math.dist
2398
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002399 p: object
2400 q: object
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002401 /
2402
2403Return the Euclidean distance between two points p and q.
2404
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002405The points should be specified as sequences (or iterables) of
2406coordinates. Both inputs must have the same dimension.
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002407
2408Roughly equivalent to:
2409 sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
2410[clinic start generated code]*/
2411
2412static PyObject *
2413math_dist_impl(PyObject *module, PyObject *p, PyObject *q)
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002414/*[clinic end generated code: output=56bd9538d06bbcfe input=74e85e1b6092e68e]*/
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002415{
2416 PyObject *item;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002417 double max = 0.0;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002418 double x, px, qx, result;
2419 Py_ssize_t i, m, n;
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002420 int found_nan = 0, p_allocated = 0, q_allocated = 0;
Raymond Hettingerc630e102018-08-11 18:39:05 -07002421 double diffs_on_stack[NUM_STACK_ELEMS];
2422 double *diffs = diffs_on_stack;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002423
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002424 if (!PyTuple_Check(p)) {
2425 p = PySequence_Tuple(p);
2426 if (p == NULL) {
2427 return NULL;
2428 }
2429 p_allocated = 1;
2430 }
2431 if (!PyTuple_Check(q)) {
2432 q = PySequence_Tuple(q);
2433 if (q == NULL) {
2434 if (p_allocated) {
2435 Py_DECREF(p);
2436 }
2437 return NULL;
2438 }
2439 q_allocated = 1;
2440 }
2441
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002442 m = PyTuple_GET_SIZE(p);
2443 n = PyTuple_GET_SIZE(q);
2444 if (m != n) {
2445 PyErr_SetString(PyExc_ValueError,
2446 "both points must have the same number of dimensions");
2447 return NULL;
2448
2449 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002450 if (n > NUM_STACK_ELEMS) {
2451 diffs = (double *) PyObject_Malloc(n * sizeof(double));
2452 if (diffs == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07002453 return PyErr_NoMemory();
Raymond Hettingerc630e102018-08-11 18:39:05 -07002454 }
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002455 }
2456 for (i=0 ; i<n ; i++) {
2457 item = PyTuple_GET_ITEM(p, i);
Raymond Hettingercfd735e2019-01-29 20:39:53 -08002458 ASSIGN_DOUBLE(px, item, error_exit);
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002459 item = PyTuple_GET_ITEM(q, i);
Raymond Hettingercfd735e2019-01-29 20:39:53 -08002460 ASSIGN_DOUBLE(qx, item, error_exit);
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002461 x = fabs(px - qx);
2462 diffs[i] = x;
2463 found_nan |= Py_IS_NAN(x);
2464 if (x > max) {
2465 max = x;
2466 }
2467 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002468 result = vector_norm(n, diffs, max, found_nan);
2469 if (diffs != diffs_on_stack) {
2470 PyObject_Free(diffs);
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002471 }
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002472 if (p_allocated) {
2473 Py_DECREF(p);
2474 }
2475 if (q_allocated) {
2476 Py_DECREF(q);
2477 }
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002478 return PyFloat_FromDouble(result);
Raymond Hettingerc630e102018-08-11 18:39:05 -07002479
2480 error_exit:
2481 if (diffs != diffs_on_stack) {
2482 PyObject_Free(diffs);
2483 }
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002484 if (p_allocated) {
2485 Py_DECREF(p);
2486 }
2487 if (q_allocated) {
2488 Py_DECREF(q);
2489 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002490 return NULL;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002491}
2492
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002493/* AC: cannot convert yet, waiting for *args support */
Christian Heimes53876d92008-04-19 00:31:39 +00002494static PyObject *
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002495math_hypot(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Christian Heimes53876d92008-04-19 00:31:39 +00002496{
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002497 Py_ssize_t i;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002498 PyObject *item;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002499 double max = 0.0;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002500 double x, result;
2501 int found_nan = 0;
Raymond Hettingerc630e102018-08-11 18:39:05 -07002502 double coord_on_stack[NUM_STACK_ELEMS];
2503 double *coordinates = coord_on_stack;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002504
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002505 if (nargs > NUM_STACK_ELEMS) {
2506 coordinates = (double *) PyObject_Malloc(nargs * sizeof(double));
Zackery Spytz4c49da02018-12-07 03:11:30 -07002507 if (coordinates == NULL) {
2508 return PyErr_NoMemory();
2509 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002510 }
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002511 for (i = 0; i < nargs; i++) {
2512 item = args[i];
Raymond Hettingercfd735e2019-01-29 20:39:53 -08002513 ASSIGN_DOUBLE(x, item, error_exit);
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002514 x = fabs(x);
2515 coordinates[i] = x;
2516 found_nan |= Py_IS_NAN(x);
2517 if (x > max) {
2518 max = x;
2519 }
2520 }
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002521 result = vector_norm(nargs, coordinates, max, found_nan);
Raymond Hettingerc630e102018-08-11 18:39:05 -07002522 if (coordinates != coord_on_stack) {
2523 PyObject_Free(coordinates);
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002524 }
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002525 return PyFloat_FromDouble(result);
Raymond Hettingerc630e102018-08-11 18:39:05 -07002526
2527 error_exit:
2528 if (coordinates != coord_on_stack) {
2529 PyObject_Free(coordinates);
2530 }
2531 return NULL;
Christian Heimes53876d92008-04-19 00:31:39 +00002532}
2533
Raymond Hettingerc630e102018-08-11 18:39:05 -07002534#undef NUM_STACK_ELEMS
2535
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002536PyDoc_STRVAR(math_hypot_doc,
2537 "hypot(*coordinates) -> value\n\n\
2538Multidimensional Euclidean distance from the origin to a point.\n\
2539\n\
2540Roughly equivalent to:\n\
2541 sqrt(sum(x**2 for x in coordinates))\n\
2542\n\
2543For a two dimensional point (x, y), gives the hypotenuse\n\
2544using the Pythagorean theorem: sqrt(x*x + y*y).\n\
2545\n\
2546For example, the hypotenuse of a 3/4/5 right triangle is:\n\
2547\n\
2548 >>> hypot(3.0, 4.0)\n\
2549 5.0\n\
2550");
Christian Heimes53876d92008-04-19 00:31:39 +00002551
2552/* pow can't use math_2, but needs its own wrapper: the problem is
2553 that an infinite result can arise either as a result of overflow
2554 (in which case OverflowError should be raised) or as a result of
2555 e.g. 0.**-5. (for which ValueError needs to be raised.)
2556*/
2557
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002558/*[clinic input]
2559math.pow
Christian Heimes53876d92008-04-19 00:31:39 +00002560
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002561 x: double
2562 y: double
2563 /
2564
2565Return x**y (x to the power of y).
2566[clinic start generated code]*/
2567
2568static PyObject *
2569math_pow_impl(PyObject *module, double x, double y)
2570/*[clinic end generated code: output=fff93e65abccd6b0 input=c26f1f6075088bfd]*/
2571{
2572 double r;
2573 int odd_y;
Christian Heimesa342c012008-04-20 21:01:16 +00002574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 /* deal directly with IEEE specials, to cope with problems on various
2576 platforms whose semantics don't exactly match C99 */
2577 r = 0.; /* silence compiler warning */
2578 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
2579 errno = 0;
2580 if (Py_IS_NAN(x))
2581 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
2582 else if (Py_IS_NAN(y))
2583 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
2584 else if (Py_IS_INFINITY(x)) {
2585 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
2586 if (y > 0.)
2587 r = odd_y ? x : fabs(x);
2588 else if (y == 0.)
2589 r = 1.;
2590 else /* y < 0. */
2591 r = odd_y ? copysign(0., x) : 0.;
2592 }
2593 else if (Py_IS_INFINITY(y)) {
2594 if (fabs(x) == 1.0)
2595 r = 1.;
2596 else if (y > 0. && fabs(x) > 1.0)
2597 r = y;
2598 else if (y < 0. && fabs(x) < 1.0) {
2599 r = -y; /* result is +inf */
2600 if (x == 0.) /* 0**-inf: divide-by-zero */
2601 errno = EDOM;
2602 }
2603 else
2604 r = 0.;
2605 }
2606 }
2607 else {
2608 /* let libm handle finite**finite */
2609 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 r = pow(x, y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002611 /* a NaN result should arise only from (-ve)**(finite
2612 non-integer); in this case we want to raise ValueError. */
2613 if (!Py_IS_FINITE(r)) {
2614 if (Py_IS_NAN(r)) {
2615 errno = EDOM;
2616 }
2617 /*
2618 an infinite result here arises either from:
2619 (A) (+/-0.)**negative (-> divide-by-zero)
2620 (B) overflow of x**y with x and y finite
2621 */
2622 else if (Py_IS_INFINITY(r)) {
2623 if (x == 0.)
2624 errno = EDOM;
2625 else
2626 errno = ERANGE;
2627 }
2628 }
2629 }
Christian Heimes53876d92008-04-19 00:31:39 +00002630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 if (errno && is_error(r))
2632 return NULL;
2633 else
2634 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00002635}
2636
Christian Heimes53876d92008-04-19 00:31:39 +00002637
Christian Heimes072c0f12008-01-03 23:01:04 +00002638static const double degToRad = Py_MATH_PI / 180.0;
2639static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002640
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002641/*[clinic input]
2642math.degrees
2643
2644 x: double
2645 /
2646
2647Convert angle x from radians to degrees.
2648[clinic start generated code]*/
2649
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002650static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002651math_degrees_impl(PyObject *module, double x)
2652/*[clinic end generated code: output=7fea78b294acd12f input=81e016555d6e3660]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002655}
2656
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002657
2658/*[clinic input]
2659math.radians
2660
2661 x: double
2662 /
2663
2664Convert angle x from degrees to radians.
2665[clinic start generated code]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002666
2667static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002668math_radians_impl(PyObject *module, double x)
2669/*[clinic end generated code: output=34daa47caf9b1590 input=91626fc489fe3d63]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 return PyFloat_FromDouble(x * degToRad);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002672}
2673
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002674
2675/*[clinic input]
2676math.isfinite
2677
2678 x: double
2679 /
2680
2681Return True if x is neither an infinity nor a NaN, and False otherwise.
2682[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002683
Christian Heimes072c0f12008-01-03 23:01:04 +00002684static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002685math_isfinite_impl(PyObject *module, double x)
2686/*[clinic end generated code: output=8ba1f396440c9901 input=46967d254812e54a]*/
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002687{
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002688 return PyBool_FromLong((long)Py_IS_FINITE(x));
2689}
2690
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002691
2692/*[clinic input]
2693math.isnan
2694
2695 x: double
2696 /
2697
2698Return True if x is a NaN (not a number), and False otherwise.
2699[clinic start generated code]*/
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002700
2701static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002702math_isnan_impl(PyObject *module, double x)
2703/*[clinic end generated code: output=f537b4d6df878c3e input=935891e66083f46a]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002705 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00002706}
2707
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002708
2709/*[clinic input]
2710math.isinf
2711
2712 x: double
2713 /
2714
2715Return True if x is a positive or negative infinity, and False otherwise.
2716[clinic start generated code]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002717
2718static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002719math_isinf_impl(PyObject *module, double x)
2720/*[clinic end generated code: output=9f00cbec4de7b06b input=32630e4212cf961f]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002721{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002722 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00002723}
2724
Christian Heimes072c0f12008-01-03 23:01:04 +00002725
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002726/*[clinic input]
2727math.isclose -> bool
2728
2729 a: double
2730 b: double
2731 *
2732 rel_tol: double = 1e-09
2733 maximum difference for being considered "close", relative to the
2734 magnitude of the input values
2735 abs_tol: double = 0.0
2736 maximum difference for being considered "close", regardless of the
2737 magnitude of the input values
2738
2739Determine whether two floating point numbers are close in value.
2740
2741Return True if a is close in value to b, and False otherwise.
2742
2743For the values to be considered close, the difference between them
2744must be smaller than at least one of the tolerances.
2745
2746-inf, inf and NaN behave similarly to the IEEE 754 Standard. That
2747is, NaN is not close to anything, even itself. inf and -inf are
2748only close to themselves.
2749[clinic start generated code]*/
2750
2751static int
2752math_isclose_impl(PyObject *module, double a, double b, double rel_tol,
2753 double abs_tol)
2754/*[clinic end generated code: output=b73070207511952d input=f28671871ea5bfba]*/
Tal Einatd5519ed2015-05-31 22:05:00 +03002755{
Tal Einatd5519ed2015-05-31 22:05:00 +03002756 double diff = 0.0;
Tal Einatd5519ed2015-05-31 22:05:00 +03002757
2758 /* sanity check on the inputs */
2759 if (rel_tol < 0.0 || abs_tol < 0.0 ) {
2760 PyErr_SetString(PyExc_ValueError,
2761 "tolerances must be non-negative");
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002762 return -1;
Tal Einatd5519ed2015-05-31 22:05:00 +03002763 }
2764
2765 if ( a == b ) {
2766 /* short circuit exact equality -- needed to catch two infinities of
2767 the same sign. And perhaps speeds things up a bit sometimes.
2768 */
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002769 return 1;
Tal Einatd5519ed2015-05-31 22:05:00 +03002770 }
2771
2772 /* This catches the case of two infinities of opposite sign, or
2773 one infinity and one finite number. Two infinities of opposite
2774 sign would otherwise have an infinite relative tolerance.
2775 Two infinities of the same sign are caught by the equality check
2776 above.
2777 */
2778
2779 if (Py_IS_INFINITY(a) || Py_IS_INFINITY(b)) {
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002780 return 0;
Tal Einatd5519ed2015-05-31 22:05:00 +03002781 }
2782
2783 /* now do the regular computation
2784 this is essentially the "weak" test from the Boost library
2785 */
2786
2787 diff = fabs(b - a);
2788
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002789 return (((diff <= fabs(rel_tol * b)) ||
2790 (diff <= fabs(rel_tol * a))) ||
2791 (diff <= abs_tol));
Tal Einatd5519ed2015-05-31 22:05:00 +03002792}
2793
Pablo Galindo04114112019-03-09 19:18:08 +00002794static inline int
2795_check_long_mult_overflow(long a, long b) {
2796
2797 /* From Python2's int_mul code:
2798
2799 Integer overflow checking for * is painful: Python tried a couple ways, but
2800 they didn't work on all platforms, or failed in endcases (a product of
2801 -sys.maxint-1 has been a particular pain).
2802
2803 Here's another way:
2804
2805 The native long product x*y is either exactly right or *way* off, being
2806 just the last n bits of the true product, where n is the number of bits
2807 in a long (the delivered product is the true product plus i*2**n for
2808 some integer i).
2809
2810 The native double product (double)x * (double)y is subject to three
2811 rounding errors: on a sizeof(long)==8 box, each cast to double can lose
2812 info, and even on a sizeof(long)==4 box, the multiplication can lose info.
2813 But, unlike the native long product, it's not in *range* trouble: even
2814 if sizeof(long)==32 (256-bit longs), the product easily fits in the
2815 dynamic range of a double. So the leading 50 (or so) bits of the double
2816 product are correct.
2817
2818 We check these two ways against each other, and declare victory if they're
2819 approximately the same. Else, because the native long product is the only
2820 one that can lose catastrophic amounts of information, it's the native long
2821 product that must have overflowed.
2822
2823 */
2824
2825 long longprod = (long)((unsigned long)a * b);
2826 double doubleprod = (double)a * (double)b;
2827 double doubled_longprod = (double)longprod;
2828
2829 if (doubled_longprod == doubleprod) {
2830 return 0;
2831 }
2832
2833 const double diff = doubled_longprod - doubleprod;
2834 const double absdiff = diff >= 0.0 ? diff : -diff;
2835 const double absprod = doubleprod >= 0.0 ? doubleprod : -doubleprod;
2836
2837 if (32.0 * absdiff <= absprod) {
2838 return 0;
2839 }
2840
2841 return 1;
2842}
Tal Einatd5519ed2015-05-31 22:05:00 +03002843
Pablo Galindobc098512019-02-07 07:04:02 +00002844/*[clinic input]
2845math.prod
2846
2847 iterable: object
2848 /
2849 *
2850 start: object(c_default="NULL") = 1
2851
2852Calculate the product of all the elements in the input iterable.
2853
2854The default start value for the product is 1.
2855
2856When the iterable is empty, return the start value. This function is
2857intended specifically for use with numeric values and may reject
2858non-numeric types.
2859[clinic start generated code]*/
2860
2861static PyObject *
2862math_prod_impl(PyObject *module, PyObject *iterable, PyObject *start)
2863/*[clinic end generated code: output=36153bedac74a198 input=4c5ab0682782ed54]*/
2864{
2865 PyObject *result = start;
2866 PyObject *temp, *item, *iter;
2867
2868 iter = PyObject_GetIter(iterable);
2869 if (iter == NULL) {
2870 return NULL;
2871 }
2872
2873 if (result == NULL) {
2874 result = PyLong_FromLong(1);
2875 if (result == NULL) {
2876 Py_DECREF(iter);
2877 return NULL;
2878 }
2879 } else {
2880 Py_INCREF(result);
2881 }
2882#ifndef SLOW_PROD
2883 /* Fast paths for integers keeping temporary products in C.
2884 * Assumes all inputs are the same type.
2885 * If the assumption fails, default to use PyObjects instead.
2886 */
2887 if (PyLong_CheckExact(result)) {
2888 int overflow;
2889 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2890 /* If this already overflowed, don't even enter the loop. */
2891 if (overflow == 0) {
2892 Py_DECREF(result);
2893 result = NULL;
2894 }
2895 /* Loop over all the items in the iterable until we finish, we overflow
2896 * or we found a non integer element */
2897 while(result == NULL) {
2898 item = PyIter_Next(iter);
2899 if (item == NULL) {
2900 Py_DECREF(iter);
2901 if (PyErr_Occurred()) {
2902 return NULL;
2903 }
2904 return PyLong_FromLong(i_result);
2905 }
2906 if (PyLong_CheckExact(item)) {
2907 long b = PyLong_AsLongAndOverflow(item, &overflow);
Pablo Galindo04114112019-03-09 19:18:08 +00002908 if (overflow == 0 && !_check_long_mult_overflow(i_result, b)) {
2909 long x = i_result * b;
Pablo Galindobc098512019-02-07 07:04:02 +00002910 i_result = x;
2911 Py_DECREF(item);
2912 continue;
2913 }
2914 }
2915 /* Either overflowed or is not an int.
2916 * Restore real objects and process normally */
2917 result = PyLong_FromLong(i_result);
2918 if (result == NULL) {
2919 Py_DECREF(item);
2920 Py_DECREF(iter);
2921 return NULL;
2922 }
2923 temp = PyNumber_Multiply(result, item);
2924 Py_DECREF(result);
2925 Py_DECREF(item);
2926 result = temp;
2927 if (result == NULL) {
2928 Py_DECREF(iter);
2929 return NULL;
2930 }
2931 }
2932 }
2933
2934 /* Fast paths for floats keeping temporary products in C.
2935 * Assumes all inputs are the same type.
2936 * If the assumption fails, default to use PyObjects instead.
2937 */
2938 if (PyFloat_CheckExact(result)) {
2939 double f_result = PyFloat_AS_DOUBLE(result);
2940 Py_DECREF(result);
2941 result = NULL;
2942 while(result == NULL) {
2943 item = PyIter_Next(iter);
2944 if (item == NULL) {
2945 Py_DECREF(iter);
2946 if (PyErr_Occurred()) {
2947 return NULL;
2948 }
2949 return PyFloat_FromDouble(f_result);
2950 }
2951 if (PyFloat_CheckExact(item)) {
2952 f_result *= PyFloat_AS_DOUBLE(item);
2953 Py_DECREF(item);
2954 continue;
2955 }
2956 if (PyLong_CheckExact(item)) {
2957 long value;
2958 int overflow;
2959 value = PyLong_AsLongAndOverflow(item, &overflow);
2960 if (!overflow) {
2961 f_result *= (double)value;
2962 Py_DECREF(item);
2963 continue;
2964 }
2965 }
2966 result = PyFloat_FromDouble(f_result);
2967 if (result == NULL) {
2968 Py_DECREF(item);
2969 Py_DECREF(iter);
2970 return NULL;
2971 }
2972 temp = PyNumber_Multiply(result, item);
2973 Py_DECREF(result);
2974 Py_DECREF(item);
2975 result = temp;
2976 if (result == NULL) {
2977 Py_DECREF(iter);
2978 return NULL;
2979 }
2980 }
2981 }
2982#endif
2983 /* Consume rest of the iterable (if any) that could not be handled
2984 * by specialized functions above.*/
2985 for(;;) {
2986 item = PyIter_Next(iter);
2987 if (item == NULL) {
2988 /* error, or end-of-sequence */
2989 if (PyErr_Occurred()) {
2990 Py_DECREF(result);
2991 result = NULL;
2992 }
2993 break;
2994 }
2995 temp = PyNumber_Multiply(result, item);
2996 Py_DECREF(result);
2997 Py_DECREF(item);
2998 result = temp;
2999 if (result == NULL)
3000 break;
3001 }
3002 Py_DECREF(iter);
3003 return result;
3004}
3005
3006
Yash Aggarwal4a686502019-06-01 12:51:27 +05303007/*[clinic input]
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003008math.perm
3009
3010 n: object
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003011 k: object = None
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003012 /
3013
3014Number of ways to choose k items from n items without repetition and with order.
3015
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003016Evaluates to n! / (n - k)! when k <= n and evaluates
3017to zero when k > n.
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003018
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003019If k is not specified or is None, then k defaults to n
3020and the function returns n!.
3021
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003022Raises TypeError if either of the arguments are not integers.
3023Raises ValueError if either of the arguments are negative.
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003024[clinic start generated code]*/
3025
3026static PyObject *
3027math_perm_impl(PyObject *module, PyObject *n, PyObject *k)
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003028/*[clinic end generated code: output=e021a25469653e23 input=5311c5a00f359b53]*/
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003029{
3030 PyObject *result = NULL, *factor = NULL;
3031 int overflow, cmp;
3032 long long i, factors;
3033
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003034 if (k == Py_None) {
3035 return math_factorial(module, n);
3036 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003037 n = PyNumber_Index(n);
3038 if (n == NULL) {
3039 return NULL;
3040 }
3041 if (!PyLong_CheckExact(n)) {
3042 Py_SETREF(n, _PyLong_Copy((PyLongObject *)n));
3043 if (n == NULL) {
3044 return NULL;
3045 }
3046 }
3047 k = PyNumber_Index(k);
3048 if (k == NULL) {
3049 Py_DECREF(n);
3050 return NULL;
3051 }
3052 if (!PyLong_CheckExact(k)) {
3053 Py_SETREF(k, _PyLong_Copy((PyLongObject *)k));
3054 if (k == NULL) {
3055 Py_DECREF(n);
3056 return NULL;
3057 }
3058 }
3059
3060 if (Py_SIZE(n) < 0) {
3061 PyErr_SetString(PyExc_ValueError,
3062 "n must be a non-negative integer");
3063 goto error;
3064 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003065 if (Py_SIZE(k) < 0) {
3066 PyErr_SetString(PyExc_ValueError,
3067 "k must be a non-negative integer");
3068 goto error;
3069 }
3070
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003071 cmp = PyObject_RichCompareBool(n, k, Py_LT);
3072 if (cmp != 0) {
3073 if (cmp > 0) {
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003074 result = PyLong_FromLong(0);
3075 goto done;
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003076 }
3077 goto error;
3078 }
3079
3080 factors = PyLong_AsLongLongAndOverflow(k, &overflow);
3081 if (overflow > 0) {
3082 PyErr_Format(PyExc_OverflowError,
3083 "k must not exceed %lld",
3084 LLONG_MAX);
3085 goto error;
3086 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003087 else if (factors == -1) {
3088 /* k is nonnegative, so a return value of -1 can only indicate error */
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003089 goto error;
3090 }
3091
3092 if (factors == 0) {
3093 result = PyLong_FromLong(1);
3094 goto done;
3095 }
3096
3097 result = n;
3098 Py_INCREF(result);
3099 if (factors == 1) {
3100 goto done;
3101 }
3102
3103 factor = n;
3104 Py_INCREF(factor);
3105 for (i = 1; i < factors; ++i) {
3106 Py_SETREF(factor, PyNumber_Subtract(factor, _PyLong_One));
3107 if (factor == NULL) {
3108 goto error;
3109 }
3110 Py_SETREF(result, PyNumber_Multiply(result, factor));
3111 if (result == NULL) {
3112 goto error;
3113 }
3114 }
3115 Py_DECREF(factor);
3116
3117done:
3118 Py_DECREF(n);
3119 Py_DECREF(k);
3120 return result;
3121
3122error:
3123 Py_XDECREF(factor);
3124 Py_XDECREF(result);
3125 Py_DECREF(n);
3126 Py_DECREF(k);
3127 return NULL;
3128}
3129
3130
3131/*[clinic input]
Yash Aggarwal4a686502019-06-01 12:51:27 +05303132math.comb
3133
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003134 n: object
3135 k: object
3136 /
Yash Aggarwal4a686502019-06-01 12:51:27 +05303137
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003138Number of ways to choose k items from n items without repetition and without order.
Yash Aggarwal4a686502019-06-01 12:51:27 +05303139
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003140Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates
3141to zero when k > n.
Yash Aggarwal4a686502019-06-01 12:51:27 +05303142
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003143Also called the binomial coefficient because it is equivalent
3144to the coefficient of k-th term in polynomial expansion of the
3145expression (1 + x)**n.
3146
3147Raises TypeError if either of the arguments are not integers.
3148Raises ValueError if either of the arguments are negative.
Yash Aggarwal4a686502019-06-01 12:51:27 +05303149
3150[clinic start generated code]*/
3151
3152static PyObject *
3153math_comb_impl(PyObject *module, PyObject *n, PyObject *k)
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003154/*[clinic end generated code: output=bd2cec8d854f3493 input=9a05315af2518709]*/
Yash Aggarwal4a686502019-06-01 12:51:27 +05303155{
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003156 PyObject *result = NULL, *factor = NULL, *temp;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303157 int overflow, cmp;
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003158 long long i, factors;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303159
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003160 n = PyNumber_Index(n);
3161 if (n == NULL) {
3162 return NULL;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303163 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003164 if (!PyLong_CheckExact(n)) {
3165 Py_SETREF(n, _PyLong_Copy((PyLongObject *)n));
3166 if (n == NULL) {
3167 return NULL;
3168 }
3169 }
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003170 k = PyNumber_Index(k);
3171 if (k == NULL) {
3172 Py_DECREF(n);
3173 return NULL;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303174 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003175 if (!PyLong_CheckExact(k)) {
3176 Py_SETREF(k, _PyLong_Copy((PyLongObject *)k));
3177 if (k == NULL) {
3178 Py_DECREF(n);
3179 return NULL;
3180 }
3181 }
Yash Aggarwal4a686502019-06-01 12:51:27 +05303182
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003183 if (Py_SIZE(n) < 0) {
3184 PyErr_SetString(PyExc_ValueError,
3185 "n must be a non-negative integer");
3186 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303187 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003188 if (Py_SIZE(k) < 0) {
3189 PyErr_SetString(PyExc_ValueError,
3190 "k must be a non-negative integer");
3191 goto error;
3192 }
3193
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003194 /* k = min(k, n - k) */
3195 temp = PyNumber_Subtract(n, k);
3196 if (temp == NULL) {
3197 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303198 }
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003199 if (Py_SIZE(temp) < 0) {
3200 Py_DECREF(temp);
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003201 result = PyLong_FromLong(0);
3202 goto done;
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003203 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003204 cmp = PyObject_RichCompareBool(temp, k, Py_LT);
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003205 if (cmp > 0) {
3206 Py_SETREF(k, temp);
Yash Aggarwal4a686502019-06-01 12:51:27 +05303207 }
3208 else {
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003209 Py_DECREF(temp);
3210 if (cmp < 0) {
3211 goto error;
3212 }
Yash Aggarwal4a686502019-06-01 12:51:27 +05303213 }
3214
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003215 factors = PyLong_AsLongLongAndOverflow(k, &overflow);
3216 if (overflow > 0) {
Yash Aggarwal4a686502019-06-01 12:51:27 +05303217 PyErr_Format(PyExc_OverflowError,
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003218 "min(n - k, k) must not exceed %lld",
Yash Aggarwal4a686502019-06-01 12:51:27 +05303219 LLONG_MAX);
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003220 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303221 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003222 if (factors == -1) {
3223 /* k is nonnegative, so a return value of -1 can only indicate error */
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003224 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303225 }
3226
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003227 if (factors == 0) {
3228 result = PyLong_FromLong(1);
3229 goto done;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303230 }
3231
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003232 result = n;
3233 Py_INCREF(result);
3234 if (factors == 1) {
3235 goto done;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303236 }
3237
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003238 factor = n;
3239 Py_INCREF(factor);
3240 for (i = 1; i < factors; ++i) {
3241 Py_SETREF(factor, PyNumber_Subtract(factor, _PyLong_One));
3242 if (factor == NULL) {
3243 goto error;
3244 }
3245 Py_SETREF(result, PyNumber_Multiply(result, factor));
3246 if (result == NULL) {
3247 goto error;
3248 }
Yash Aggarwal4a686502019-06-01 12:51:27 +05303249
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003250 temp = PyLong_FromUnsignedLongLong((unsigned long long)i + 1);
3251 if (temp == NULL) {
3252 goto error;
3253 }
3254 Py_SETREF(result, PyNumber_FloorDivide(result, temp));
3255 Py_DECREF(temp);
3256 if (result == NULL) {
3257 goto error;
3258 }
3259 }
3260 Py_DECREF(factor);
Yash Aggarwal4a686502019-06-01 12:51:27 +05303261
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003262done:
3263 Py_DECREF(n);
3264 Py_DECREF(k);
3265 return result;
3266
3267error:
3268 Py_XDECREF(factor);
3269 Py_XDECREF(result);
3270 Py_DECREF(n);
3271 Py_DECREF(k);
Yash Aggarwal4a686502019-06-01 12:51:27 +05303272 return NULL;
3273}
3274
3275
Victor Stinner100fafc2020-01-12 02:15:42 +01003276/*[clinic input]
3277math.nextafter
3278
3279 x: double
3280 y: double
3281 /
3282
3283Return the next floating-point value after x towards y.
3284[clinic start generated code]*/
3285
3286static PyObject *
3287math_nextafter_impl(PyObject *module, double x, double y)
3288/*[clinic end generated code: output=750c8266c1c540ce input=02b2d50cd1d9f9b6]*/
3289{
Victor Stinner85ead4f2020-01-21 11:14:10 +01003290#if defined(_AIX)
3291 if (x == y) {
3292 /* On AIX 7.1, libm nextafter(-0.0, +0.0) returns -0.0.
3293 Bug fixed in bos.adt.libm 7.2.2.0 by APAR IV95512. */
3294 return PyFloat_FromDouble(y);
3295 }
3296#endif
3297 return PyFloat_FromDouble(nextafter(x, y));
Victor Stinner100fafc2020-01-12 02:15:42 +01003298}
3299
3300
Victor Stinner0b2ab212020-01-13 12:44:35 +01003301/*[clinic input]
3302math.ulp -> double
3303
3304 x: double
3305 /
3306
3307Return the value of the least significant bit of the float x.
3308[clinic start generated code]*/
3309
3310static double
3311math_ulp_impl(PyObject *module, double x)
3312/*[clinic end generated code: output=f5207867a9384dd4 input=31f9bfbbe373fcaa]*/
3313{
3314 if (Py_IS_NAN(x)) {
3315 return x;
3316 }
3317 x = fabs(x);
3318 if (Py_IS_INFINITY(x)) {
3319 return x;
3320 }
3321 double inf = m_inf();
3322 double x2 = nextafter(x, inf);
3323 if (Py_IS_INFINITY(x2)) {
3324 /* special case: x is the largest positive representable float */
3325 x2 = nextafter(x, -inf);
3326 return x - x2;
3327 }
3328 return x2 - x;
3329}
3330
3331
Barry Warsaw8b43b191996-12-09 22:32:36 +00003332static PyMethodDef math_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003333 {"acos", math_acos, METH_O, math_acos_doc},
3334 {"acosh", math_acosh, METH_O, math_acosh_doc},
3335 {"asin", math_asin, METH_O, math_asin_doc},
3336 {"asinh", math_asinh, METH_O, math_asinh_doc},
3337 {"atan", math_atan, METH_O, math_atan_doc},
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003338 {"atan2", (PyCFunction)(void(*)(void))math_atan2, METH_FASTCALL, math_atan2_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003339 {"atanh", math_atanh, METH_O, math_atanh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003340 MATH_CEIL_METHODDEF
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003341 {"copysign", (PyCFunction)(void(*)(void))math_copysign, METH_FASTCALL, math_copysign_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003342 {"cos", math_cos, METH_O, math_cos_doc},
3343 {"cosh", math_cosh, METH_O, math_cosh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003344 MATH_DEGREES_METHODDEF
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07003345 MATH_DIST_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003346 {"erf", math_erf, METH_O, math_erf_doc},
3347 {"erfc", math_erfc, METH_O, math_erfc_doc},
3348 {"exp", math_exp, METH_O, math_exp_doc},
3349 {"expm1", math_expm1, METH_O, math_expm1_doc},
3350 {"fabs", math_fabs, METH_O, math_fabs_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003351 MATH_FACTORIAL_METHODDEF
3352 MATH_FLOOR_METHODDEF
3353 MATH_FMOD_METHODDEF
3354 MATH_FREXP_METHODDEF
3355 MATH_FSUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003356 {"gamma", math_gamma, METH_O, math_gamma_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003357 MATH_GCD_METHODDEF
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003358 {"hypot", (PyCFunction)(void(*)(void))math_hypot, METH_FASTCALL, math_hypot_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003359 MATH_ISCLOSE_METHODDEF
3360 MATH_ISFINITE_METHODDEF
3361 MATH_ISINF_METHODDEF
3362 MATH_ISNAN_METHODDEF
Mark Dickinson73934b92019-05-18 12:29:50 +01003363 MATH_ISQRT_METHODDEF
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003364 MATH_LDEXP_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003365 {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003366 MATH_LOG_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003367 {"log1p", math_log1p, METH_O, math_log1p_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003368 MATH_LOG10_METHODDEF
3369 MATH_LOG2_METHODDEF
3370 MATH_MODF_METHODDEF
3371 MATH_POW_METHODDEF
3372 MATH_RADIANS_METHODDEF
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003373 {"remainder", (PyCFunction)(void(*)(void))math_remainder, METH_FASTCALL, math_remainder_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003374 {"sin", math_sin, METH_O, math_sin_doc},
3375 {"sinh", math_sinh, METH_O, math_sinh_doc},
3376 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
3377 {"tan", math_tan, METH_O, math_tan_doc},
3378 {"tanh", math_tanh, METH_O, math_tanh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003379 MATH_TRUNC_METHODDEF
Pablo Galindobc098512019-02-07 07:04:02 +00003380 MATH_PROD_METHODDEF
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003381 MATH_PERM_METHODDEF
Yash Aggarwal4a686502019-06-01 12:51:27 +05303382 MATH_COMB_METHODDEF
Victor Stinner100fafc2020-01-12 02:15:42 +01003383 MATH_NEXTAFTER_METHODDEF
Victor Stinner0b2ab212020-01-13 12:44:35 +01003384 MATH_ULP_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003385 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003386};
3387
Guido van Rossumc6e22901998-12-04 19:26:43 +00003388
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003389PyDoc_STRVAR(module_doc,
Ned Batchelder6faad352019-05-17 05:59:14 -04003390"This module provides access to the mathematical functions\n"
3391"defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00003392
Martin v. Löwis1a214512008-06-11 05:26:20 +00003393
3394static struct PyModuleDef mathmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003395 PyModuleDef_HEAD_INIT,
3396 "math",
3397 module_doc,
3398 -1,
3399 math_methods,
3400 NULL,
3401 NULL,
3402 NULL,
3403 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003404};
3405
Mark Hammondfe51c6d2002-08-02 02:27:13 +00003406PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003407PyInit_math(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003409 PyObject *m;
Tim Petersfe71f812001-08-07 22:10:00 +00003410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003411 m = PyModule_Create(&mathmodule);
3412 if (m == NULL)
3413 goto finally;
Barry Warsawfc93f751996-12-17 00:47:03 +00003414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003415 PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
3416 PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
Guido van Rossum0a891d72016-08-15 09:12:52 -07003417 PyModule_AddObject(m, "tau", PyFloat_FromDouble(Py_MATH_TAU)); /* 2pi */
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +00003418 PyModule_AddObject(m, "inf", PyFloat_FromDouble(m_inf()));
3419#if !defined(PY_NO_SHORT_FLOAT_REPR) || defined(Py_NAN)
3420 PyModule_AddObject(m, "nan", PyFloat_FromDouble(m_nan()));
3421#endif
Barry Warsawfc93f751996-12-17 00:47:03 +00003422
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +00003423 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003424 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003425}