blob: 309f229159540125166be069ecefc3fa5a088eec [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Math module -- standard C math library functions, pi and e */
2
Christian Heimes53876d92008-04-19 00:31:39 +00003/* Here are some comments from Tim Peters, extracted from the
4 discussion attached to http://bugs.python.org/issue1640. They
5 describe the general aims of the math module with respect to
6 special values, IEEE-754 floating-point exceptions, and Python
7 exceptions.
8
9These are the "spirit of 754" rules:
10
111. If the mathematical result is a real number, but of magnitude too
12large to approximate by a machine float, overflow is signaled and the
13result is an infinity (with the appropriate sign).
14
152. If the mathematical result is a real number, but of magnitude too
16small to approximate by a machine float, underflow is signaled and the
17result is a zero (with the appropriate sign).
18
193. At a singularity (a value x such that the limit of f(y) as y
20approaches x exists and is an infinity), "divide by zero" is signaled
21and the result is an infinity (with the appropriate sign). This is
22complicated a little by that the left-side and right-side limits may
23not be the same; e.g., 1/x approaches +inf or -inf as x approaches 0
24from the positive or negative directions. In that specific case, the
25sign of the zero determines the result of 1/0.
26
274. At a point where a function has no defined result in the extended
28reals (i.e., the reals plus an infinity or two), invalid operation is
29signaled and a NaN is returned.
30
31And these are what Python has historically /tried/ to do (but not
32always successfully, as platform libm behavior varies a lot):
33
34For #1, raise OverflowError.
35
36For #2, return a zero (with the appropriate sign if that happens by
37accident ;-)).
38
39For #3 and #4, raise ValueError. It may have made sense to raise
40Python's ZeroDivisionError in #3, but historically that's only been
41raised for division by zero and mod by zero.
42
43*/
44
45/*
46 In general, on an IEEE-754 platform the aim is to follow the C99
47 standard, including Annex 'F', whenever possible. Where the
48 standard recommends raising the 'divide-by-zero' or 'invalid'
49 floating-point exceptions, Python should raise a ValueError. Where
50 the standard recommends raising 'overflow', Python should raise an
51 OverflowError. In all other circumstances a value should be
52 returned.
53 */
54
Barry Warsaw8b43b191996-12-09 22:32:36 +000055#include "Python.h"
Victor Stinnere9e7d282020-02-12 22:54:42 +010056#include "pycore_dtoa.h"
Mark Dickinson664b5112009-12-16 20:23:42 +000057#include "_math.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000058
Serhiy Storchakac9ea9332017-01-19 18:13:09 +020059#include "clinic/mathmodule.c.h"
60
61/*[clinic input]
62module math
63[clinic start generated code]*/
64/*[clinic end generated code: output=da39a3ee5e6b4b0d input=76bc7002685dd942]*/
65
66
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000067/*
68 sin(pi*x), giving accurate results for all finite x (especially x
69 integral or close to an integer). This is here for use in the
70 reflection formula for the gamma function. It conforms to IEEE
71 754-2008 for finite arguments, but not for infinities or nans.
72*/
Tim Petersa40c7932001-09-05 22:36:56 +000073
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000074static const double pi = 3.141592653589793238462643383279502884197;
Mark Dickinson9c91eb82010-07-07 16:17:31 +000075static const double logpi = 1.144729885849400174143427351353058711647;
Louie Lu7a264642017-03-31 01:05:10 +080076#if !defined(HAVE_ERF) || !defined(HAVE_ERFC)
77static const double sqrtpi = 1.772453850905516027298167483341145182798;
78#endif /* !defined(HAVE_ERF) || !defined(HAVE_ERFC) */
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000079
Raymond Hettingercfd735e2019-01-29 20:39:53 -080080
81/* Version of PyFloat_AsDouble() with in-line fast paths
82 for exact floats and integers. Gives a substantial
83 speed improvement for extracting float arguments.
84*/
85
86#define ASSIGN_DOUBLE(target_var, obj, error_label) \
87 if (PyFloat_CheckExact(obj)) { \
88 target_var = PyFloat_AS_DOUBLE(obj); \
89 } \
90 else if (PyLong_CheckExact(obj)) { \
91 target_var = PyLong_AsDouble(obj); \
92 if (target_var == -1.0 && PyErr_Occurred()) { \
93 goto error_label; \
94 } \
95 } \
96 else { \
97 target_var = PyFloat_AsDouble(obj); \
98 if (target_var == -1.0 && PyErr_Occurred()) { \
99 goto error_label; \
100 } \
101 }
102
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000103static double
Dima Pasechnikf57cd822019-02-26 06:36:11 +0000104m_sinpi(double x)
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000105{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 double y, r;
107 int n;
108 /* this function should only ever be called for finite arguments */
109 assert(Py_IS_FINITE(x));
110 y = fmod(fabs(x), 2.0);
111 n = (int)round(2.0*y);
112 assert(0 <= n && n <= 4);
113 switch (n) {
114 case 0:
115 r = sin(pi*y);
116 break;
117 case 1:
118 r = cos(pi*(y-0.5));
119 break;
120 case 2:
121 /* N.B. -sin(pi*(y-1.0)) is *not* equivalent: it would give
122 -0.0 instead of 0.0 when y == 1.0. */
123 r = sin(pi*(1.0-y));
124 break;
125 case 3:
126 r = -cos(pi*(y-1.5));
127 break;
128 case 4:
129 r = sin(pi*(y-2.0));
130 break;
131 default:
Barry Warsawb2e57942017-09-14 18:13:16 -0700132 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 }
134 return copysign(1.0, x)*r;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000135}
136
137/* Implementation of the real gamma function. In extensive but non-exhaustive
138 random tests, this function proved accurate to within <= 10 ulps across the
139 entire float domain. Note that accuracy may depend on the quality of the
140 system math functions, the pow function in particular. Special cases
141 follow C99 annex F. The parameters and method are tailored to platforms
142 whose double format is the IEEE 754 binary64 format.
143
144 Method: for x > 0.0 we use the Lanczos approximation with parameters N=13
145 and g=6.024680040776729583740234375; these parameters are amongst those
146 used by the Boost library. Following Boost (again), we re-express the
147 Lanczos sum as a rational function, and compute it that way. The
148 coefficients below were computed independently using MPFR, and have been
149 double-checked against the coefficients in the Boost source code.
150
151 For x < 0.0 we use the reflection formula.
152
153 There's one minor tweak that deserves explanation: Lanczos' formula for
154 Gamma(x) involves computing pow(x+g-0.5, x-0.5) / exp(x+g-0.5). For many x
155 values, x+g-0.5 can be represented exactly. However, in cases where it
156 can't be represented exactly the small error in x+g-0.5 can be magnified
157 significantly by the pow and exp calls, especially for large x. A cheap
158 correction is to multiply by (1 + e*g/(x+g-0.5)), where e is the error
159 involved in the computation of x+g-0.5 (that is, e = computed value of
160 x+g-0.5 - exact value of x+g-0.5). Here's the proof:
161
162 Correction factor
163 -----------------
164 Write x+g-0.5 = y-e, where y is exactly representable as an IEEE 754
165 double, and e is tiny. Then:
166
167 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) = pow(y-e, x-0.5)/exp(y-e)
168 = pow(y, x-0.5)/exp(y) * C,
169
170 where the correction_factor C is given by
171
172 C = pow(1-e/y, x-0.5) * exp(e)
173
174 Since e is tiny, pow(1-e/y, x-0.5) ~ 1-(x-0.5)*e/y, and exp(x) ~ 1+e, so:
175
176 C ~ (1-(x-0.5)*e/y) * (1+e) ~ 1 + e*(y-(x-0.5))/y
177
178 But y-(x-0.5) = g+e, and g+e ~ g. So we get C ~ 1 + e*g/y, and
179
180 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) ~ pow(y, x-0.5)/exp(y) * (1 + e*g/y),
181
182 Note that for accuracy, when computing r*C it's better to do
183
184 r + e*g/y*r;
185
186 than
187
188 r * (1 + e*g/y);
189
190 since the addition in the latter throws away most of the bits of
191 information in e*g/y.
192*/
193
194#define LANCZOS_N 13
195static const double lanczos_g = 6.024680040776729583740234375;
196static const double lanczos_g_minus_half = 5.524680040776729583740234375;
197static const double lanczos_num_coeffs[LANCZOS_N] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 23531376880.410759688572007674451636754734846804940,
199 42919803642.649098768957899047001988850926355848959,
200 35711959237.355668049440185451547166705960488635843,
201 17921034426.037209699919755754458931112671403265390,
202 6039542586.3520280050642916443072979210699388420708,
203 1439720407.3117216736632230727949123939715485786772,
204 248874557.86205415651146038641322942321632125127801,
205 31426415.585400194380614231628318205362874684987640,
206 2876370.6289353724412254090516208496135991145378768,
207 186056.26539522349504029498971604569928220784236328,
208 8071.6720023658162106380029022722506138218516325024,
209 210.82427775157934587250973392071336271166969580291,
210 2.5066282746310002701649081771338373386264310793408
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000211};
212
213/* denominator is x*(x+1)*...*(x+LANCZOS_N-2) */
214static const double lanczos_den_coeffs[LANCZOS_N] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000215 0.0, 39916800.0, 120543840.0, 150917976.0, 105258076.0, 45995730.0,
216 13339535.0, 2637558.0, 357423.0, 32670.0, 1925.0, 66.0, 1.0};
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000217
218/* gamma values for small positive integers, 1 though NGAMMA_INTEGRAL */
219#define NGAMMA_INTEGRAL 23
220static const double gamma_integral[NGAMMA_INTEGRAL] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0,
222 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0,
223 1307674368000.0, 20922789888000.0, 355687428096000.0,
224 6402373705728000.0, 121645100408832000.0, 2432902008176640000.0,
225 51090942171709440000.0, 1124000727777607680000.0,
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000226};
227
228/* Lanczos' sum L_g(x), for positive x */
229
230static double
231lanczos_sum(double x)
232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 double num = 0.0, den = 0.0;
234 int i;
235 assert(x > 0.0);
236 /* evaluate the rational function lanczos_sum(x). For large
237 x, the obvious algorithm risks overflow, so we instead
238 rescale the denominator and numerator of the rational
239 function by x**(1-LANCZOS_N) and treat this as a
240 rational function in 1/x. This also reduces the error for
241 larger x values. The choice of cutoff point (5.0 below) is
242 somewhat arbitrary; in tests, smaller cutoff values than
243 this resulted in lower accuracy. */
244 if (x < 5.0) {
245 for (i = LANCZOS_N; --i >= 0; ) {
246 num = num * x + lanczos_num_coeffs[i];
247 den = den * x + lanczos_den_coeffs[i];
248 }
249 }
250 else {
251 for (i = 0; i < LANCZOS_N; i++) {
252 num = num / x + lanczos_num_coeffs[i];
253 den = den / x + lanczos_den_coeffs[i];
254 }
255 }
256 return num/den;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000257}
258
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +0000259/* Constant for +infinity, generated in the same way as float('inf'). */
260
261static double
262m_inf(void)
263{
264#ifndef PY_NO_SHORT_FLOAT_REPR
265 return _Py_dg_infinity(0);
266#else
267 return Py_HUGE_VAL;
268#endif
269}
270
271/* Constant nan value, generated in the same way as float('nan'). */
272/* We don't currently assume that Py_NAN is defined everywhere. */
273
274#if !defined(PY_NO_SHORT_FLOAT_REPR) || defined(Py_NAN)
275
276static double
277m_nan(void)
278{
279#ifndef PY_NO_SHORT_FLOAT_REPR
280 return _Py_dg_stdnan(0);
281#else
282 return Py_NAN;
283#endif
284}
285
286#endif
287
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000288static double
289m_tgamma(double x)
290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 double absx, r, y, z, sqrtpow;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 /* special cases */
294 if (!Py_IS_FINITE(x)) {
295 if (Py_IS_NAN(x) || x > 0.0)
296 return x; /* tgamma(nan) = nan, tgamma(inf) = inf */
297 else {
298 errno = EDOM;
299 return Py_NAN; /* tgamma(-inf) = nan, invalid */
300 }
301 }
302 if (x == 0.0) {
303 errno = EDOM;
Mark Dickinson50203a62011-09-25 15:26:43 +0100304 /* tgamma(+-0.0) = +-inf, divide-by-zero */
305 return copysign(Py_HUGE_VAL, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 /* integer arguments */
309 if (x == floor(x)) {
310 if (x < 0.0) {
311 errno = EDOM; /* tgamma(n) = nan, invalid for */
312 return Py_NAN; /* negative integers n */
313 }
314 if (x <= NGAMMA_INTEGRAL)
315 return gamma_integral[(int)x - 1];
316 }
317 absx = fabs(x);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 /* tiny arguments: tgamma(x) ~ 1/x for x near 0 */
320 if (absx < 1e-20) {
321 r = 1.0/x;
322 if (Py_IS_INFINITY(r))
323 errno = ERANGE;
324 return r;
325 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 /* large arguments: assuming IEEE 754 doubles, tgamma(x) overflows for
328 x > 200, and underflows to +-0.0 for x < -200, not a negative
329 integer. */
330 if (absx > 200.0) {
331 if (x < 0.0) {
Dima Pasechnikf57cd822019-02-26 06:36:11 +0000332 return 0.0/m_sinpi(x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 }
334 else {
335 errno = ERANGE;
336 return Py_HUGE_VAL;
337 }
338 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 y = absx + lanczos_g_minus_half;
341 /* compute error in sum */
342 if (absx > lanczos_g_minus_half) {
343 /* note: the correction can be foiled by an optimizing
344 compiler that (incorrectly) thinks that an expression like
345 a + b - a - b can be optimized to 0.0. This shouldn't
346 happen in a standards-conforming compiler. */
347 double q = y - absx;
348 z = q - lanczos_g_minus_half;
349 }
350 else {
351 double q = y - lanczos_g_minus_half;
352 z = q - absx;
353 }
354 z = z * lanczos_g / y;
355 if (x < 0.0) {
Dima Pasechnikf57cd822019-02-26 06:36:11 +0000356 r = -pi / m_sinpi(absx) / absx * exp(y) / lanczos_sum(absx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 r -= z * r;
358 if (absx < 140.0) {
359 r /= pow(y, absx - 0.5);
360 }
361 else {
362 sqrtpow = pow(y, absx / 2.0 - 0.25);
363 r /= sqrtpow;
364 r /= sqrtpow;
365 }
366 }
367 else {
368 r = lanczos_sum(absx) / exp(y);
369 r += z * r;
370 if (absx < 140.0) {
371 r *= pow(y, absx - 0.5);
372 }
373 else {
374 sqrtpow = pow(y, absx / 2.0 - 0.25);
375 r *= sqrtpow;
376 r *= sqrtpow;
377 }
378 }
379 if (Py_IS_INFINITY(r))
380 errno = ERANGE;
381 return r;
Guido van Rossum8832b621991-12-16 15:44:24 +0000382}
383
Christian Heimes53876d92008-04-19 00:31:39 +0000384/*
Mark Dickinson05d2e082009-12-11 20:17:17 +0000385 lgamma: natural log of the absolute value of the Gamma function.
386 For large arguments, Lanczos' formula works extremely well here.
387*/
388
389static double
390m_lgamma(double x)
391{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200392 double r;
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200393 double absx;
Mark Dickinson05d2e082009-12-11 20:17:17 +0000394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 /* special cases */
396 if (!Py_IS_FINITE(x)) {
397 if (Py_IS_NAN(x))
398 return x; /* lgamma(nan) = nan */
399 else
400 return Py_HUGE_VAL; /* lgamma(+-inf) = +inf */
401 }
Mark Dickinson05d2e082009-12-11 20:17:17 +0000402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 /* integer arguments */
404 if (x == floor(x) && x <= 2.0) {
405 if (x <= 0.0) {
406 errno = EDOM; /* lgamma(n) = inf, divide-by-zero for */
407 return Py_HUGE_VAL; /* integers n <= 0 */
408 }
409 else {
410 return 0.0; /* lgamma(1) = lgamma(2) = 0.0 */
411 }
412 }
Mark Dickinson05d2e082009-12-11 20:17:17 +0000413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 absx = fabs(x);
415 /* tiny arguments: lgamma(x) ~ -log(fabs(x)) for small x */
416 if (absx < 1e-20)
417 return -log(absx);
Mark Dickinson05d2e082009-12-11 20:17:17 +0000418
Mark Dickinson9c91eb82010-07-07 16:17:31 +0000419 /* Lanczos' formula. We could save a fraction of a ulp in accuracy by
420 having a second set of numerator coefficients for lanczos_sum that
421 absorbed the exp(-lanczos_g) term, and throwing out the lanczos_g
422 subtraction below; it's probably not worth it. */
423 r = log(lanczos_sum(absx)) - lanczos_g;
424 r += (absx - 0.5) * (log(absx + lanczos_g - 0.5) - 1);
425 if (x < 0.0)
426 /* Use reflection formula to get value for negative x. */
Dima Pasechnikf57cd822019-02-26 06:36:11 +0000427 r = logpi - log(fabs(m_sinpi(absx))) - log(absx) - r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 if (Py_IS_INFINITY(r))
429 errno = ERANGE;
430 return r;
Mark Dickinson05d2e082009-12-11 20:17:17 +0000431}
432
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200433#if !defined(HAVE_ERF) || !defined(HAVE_ERFC)
434
Mark Dickinson45f992a2009-12-19 11:20:49 +0000435/*
436 Implementations of the error function erf(x) and the complementary error
437 function erfc(x).
438
Brett Cannon45adb312016-01-15 09:38:24 -0800439 Method: we use a series approximation for erf for small x, and a continued
440 fraction approximation for erfc(x) for larger x;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000441 combined with the relations erf(-x) = -erf(x) and erfc(x) = 1.0 - erf(x),
442 this gives us erf(x) and erfc(x) for all x.
443
444 The series expansion used is:
445
446 erf(x) = x*exp(-x*x)/sqrt(pi) * [
447 2/1 + 4/3 x**2 + 8/15 x**4 + 16/105 x**6 + ...]
448
449 The coefficient of x**(2k-2) here is 4**k*factorial(k)/factorial(2*k).
450 This series converges well for smallish x, but slowly for larger x.
451
452 The continued fraction expansion used is:
453
454 erfc(x) = x*exp(-x*x)/sqrt(pi) * [1/(0.5 + x**2 -) 0.5/(2.5 + x**2 - )
455 3.0/(4.5 + x**2 - ) 7.5/(6.5 + x**2 - ) ...]
456
457 after the first term, the general term has the form:
458
459 k*(k-0.5)/(2*k+0.5 + x**2 - ...).
460
461 This expansion converges fast for larger x, but convergence becomes
462 infinitely slow as x approaches 0.0. The (somewhat naive) continued
463 fraction evaluation algorithm used below also risks overflow for large x;
464 but for large x, erfc(x) == 0.0 to within machine precision. (For
465 example, erfc(30.0) is approximately 2.56e-393).
466
467 Parameters: use series expansion for abs(x) < ERF_SERIES_CUTOFF and
468 continued fraction expansion for ERF_SERIES_CUTOFF <= abs(x) <
469 ERFC_CONTFRAC_CUTOFF. ERFC_SERIES_TERMS and ERFC_CONTFRAC_TERMS are the
470 numbers of terms to use for the relevant expansions. */
471
472#define ERF_SERIES_CUTOFF 1.5
473#define ERF_SERIES_TERMS 25
474#define ERFC_CONTFRAC_CUTOFF 30.0
475#define ERFC_CONTFRAC_TERMS 50
476
477/*
478 Error function, via power series.
479
480 Given a finite float x, return an approximation to erf(x).
481 Converges reasonably fast for small x.
482*/
483
484static double
485m_erf_series(double x)
486{
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000487 double x2, acc, fk, result;
488 int i, saved_errno;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 x2 = x * x;
491 acc = 0.0;
492 fk = (double)ERF_SERIES_TERMS + 0.5;
493 for (i = 0; i < ERF_SERIES_TERMS; i++) {
494 acc = 2.0 + x2 * acc / fk;
495 fk -= 1.0;
496 }
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000497 /* Make sure the exp call doesn't affect errno;
498 see m_erfc_contfrac for more. */
499 saved_errno = errno;
500 result = acc * x * exp(-x2) / sqrtpi;
501 errno = saved_errno;
502 return result;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000503}
504
505/*
506 Complementary error function, via continued fraction expansion.
507
508 Given a positive float x, return an approximation to erfc(x). Converges
509 reasonably fast for x large (say, x > 2.0), and should be safe from
510 overflow if x and nterms are not too large. On an IEEE 754 machine, with x
511 <= 30.0, we're safe up to nterms = 100. For x >= 30.0, erfc(x) is smaller
512 than the smallest representable nonzero float. */
513
514static double
515m_erfc_contfrac(double x)
516{
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000517 double x2, a, da, p, p_last, q, q_last, b, result;
518 int i, saved_errno;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 if (x >= ERFC_CONTFRAC_CUTOFF)
521 return 0.0;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 x2 = x*x;
524 a = 0.0;
525 da = 0.5;
526 p = 1.0; p_last = 0.0;
527 q = da + x2; q_last = 1.0;
528 for (i = 0; i < ERFC_CONTFRAC_TERMS; i++) {
529 double temp;
530 a += da;
531 da += 2.0;
532 b = da + x2;
533 temp = p; p = b*p - a*p_last; p_last = temp;
534 temp = q; q = b*q - a*q_last; q_last = temp;
535 }
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000536 /* Issue #8986: On some platforms, exp sets errno on underflow to zero;
537 save the current errno value so that we can restore it later. */
538 saved_errno = errno;
539 result = p / q * x * exp(-x2) / sqrtpi;
540 errno = saved_errno;
541 return result;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000542}
543
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200544#endif /* !defined(HAVE_ERF) || !defined(HAVE_ERFC) */
545
Mark Dickinson45f992a2009-12-19 11:20:49 +0000546/* Error function erf(x), for general x */
547
548static double
549m_erf(double x)
550{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200551#ifdef HAVE_ERF
552 return erf(x);
553#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 double absx, cf;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 if (Py_IS_NAN(x))
557 return x;
558 absx = fabs(x);
559 if (absx < ERF_SERIES_CUTOFF)
560 return m_erf_series(x);
561 else {
562 cf = m_erfc_contfrac(absx);
563 return x > 0.0 ? 1.0 - cf : cf - 1.0;
564 }
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200565#endif
Mark Dickinson45f992a2009-12-19 11:20:49 +0000566}
567
568/* Complementary error function erfc(x), for general x. */
569
570static double
571m_erfc(double x)
572{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200573#ifdef HAVE_ERFC
574 return erfc(x);
575#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 double absx, cf;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 if (Py_IS_NAN(x))
579 return x;
580 absx = fabs(x);
581 if (absx < ERF_SERIES_CUTOFF)
582 return 1.0 - m_erf_series(x);
583 else {
584 cf = m_erfc_contfrac(absx);
585 return x > 0.0 ? cf : 2.0 - cf;
586 }
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200587#endif
Mark Dickinson45f992a2009-12-19 11:20:49 +0000588}
Mark Dickinson05d2e082009-12-11 20:17:17 +0000589
590/*
Christian Heimese57950f2008-04-21 13:08:03 +0000591 wrapper for atan2 that deals directly with special cases before
592 delegating to the platform libm for the remaining cases. This
593 is necessary to get consistent behaviour across platforms.
594 Windows, FreeBSD and alpha Tru64 are amongst platforms that don't
595 always follow C99.
596*/
597
598static double
599m_atan2(double y, double x)
600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 if (Py_IS_NAN(x) || Py_IS_NAN(y))
602 return Py_NAN;
603 if (Py_IS_INFINITY(y)) {
604 if (Py_IS_INFINITY(x)) {
605 if (copysign(1., x) == 1.)
606 /* atan2(+-inf, +inf) == +-pi/4 */
607 return copysign(0.25*Py_MATH_PI, y);
608 else
609 /* atan2(+-inf, -inf) == +-pi*3/4 */
610 return copysign(0.75*Py_MATH_PI, y);
611 }
612 /* atan2(+-inf, x) == +-pi/2 for finite x */
613 return copysign(0.5*Py_MATH_PI, y);
614 }
615 if (Py_IS_INFINITY(x) || y == 0.) {
616 if (copysign(1., x) == 1.)
617 /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */
618 return copysign(0., y);
619 else
620 /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */
621 return copysign(Py_MATH_PI, y);
622 }
623 return atan2(y, x);
Christian Heimese57950f2008-04-21 13:08:03 +0000624}
625
Mark Dickinsona0ce3752017-04-05 18:34:27 +0100626
627/* IEEE 754-style remainder operation: x - n*y where n*y is the nearest
628 multiple of y to x, taking n even in the case of a tie. Assuming an IEEE 754
629 binary floating-point format, the result is always exact. */
630
631static double
632m_remainder(double x, double y)
633{
634 /* Deal with most common case first. */
635 if (Py_IS_FINITE(x) && Py_IS_FINITE(y)) {
636 double absx, absy, c, m, r;
637
638 if (y == 0.0) {
639 return Py_NAN;
640 }
641
642 absx = fabs(x);
643 absy = fabs(y);
644 m = fmod(absx, absy);
645
646 /*
647 Warning: some subtlety here. What we *want* to know at this point is
648 whether the remainder m is less than, equal to, or greater than half
649 of absy. However, we can't do that comparison directly because we
Mark Dickinson01484702019-07-13 16:50:03 +0100650 can't be sure that 0.5*absy is representable (the multiplication
Mark Dickinsona0ce3752017-04-05 18:34:27 +0100651 might incur precision loss due to underflow). So instead we compare
652 m with the complement c = absy - m: m < 0.5*absy if and only if m <
653 c, and so on. The catch is that absy - m might also not be
654 representable, but it turns out that it doesn't matter:
655
656 - if m > 0.5*absy then absy - m is exactly representable, by
657 Sterbenz's lemma, so m > c
658 - if m == 0.5*absy then again absy - m is exactly representable
659 and m == c
660 - if m < 0.5*absy then either (i) 0.5*absy is exactly representable,
661 in which case 0.5*absy < absy - m, so 0.5*absy <= c and hence m <
662 c, or (ii) absy is tiny, either subnormal or in the lowest normal
663 binade. Then absy - m is exactly representable and again m < c.
664 */
665
666 c = absy - m;
667 if (m < c) {
668 r = m;
669 }
670 else if (m > c) {
671 r = -c;
672 }
673 else {
674 /*
675 Here absx is exactly halfway between two multiples of absy,
676 and we need to choose the even multiple. x now has the form
677
678 absx = n * absy + m
679
680 for some integer n (recalling that m = 0.5*absy at this point).
681 If n is even we want to return m; if n is odd, we need to
682 return -m.
683
684 So
685
686 0.5 * (absx - m) = (n/2) * absy
687
688 and now reducing modulo absy gives us:
689
690 | m, if n is odd
691 fmod(0.5 * (absx - m), absy) = |
692 | 0, if n is even
693
694 Now m - 2.0 * fmod(...) gives the desired result: m
695 if n is even, -m if m is odd.
696
697 Note that all steps in fmod(0.5 * (absx - m), absy)
698 will be computed exactly, with no rounding error
699 introduced.
700 */
701 assert(m == c);
702 r = m - 2.0 * fmod(0.5 * (absx - m), absy);
703 }
704 return copysign(1.0, x) * r;
705 }
706
707 /* Special values. */
708 if (Py_IS_NAN(x)) {
709 return x;
710 }
711 if (Py_IS_NAN(y)) {
712 return y;
713 }
714 if (Py_IS_INFINITY(x)) {
715 return Py_NAN;
716 }
717 assert(Py_IS_INFINITY(y));
718 return x;
719}
720
721
Christian Heimese57950f2008-04-21 13:08:03 +0000722/*
Mark Dickinsone675f082008-12-11 21:56:00 +0000723 Various platforms (Solaris, OpenBSD) do nonstandard things for log(0),
724 log(-ve), log(NaN). Here are wrappers for log and log10 that deal with
725 special values directly, passing positive non-special values through to
726 the system log/log10.
727 */
728
729static double
730m_log(double x)
731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 if (Py_IS_FINITE(x)) {
733 if (x > 0.0)
734 return log(x);
735 errno = EDOM;
736 if (x == 0.0)
737 return -Py_HUGE_VAL; /* log(0) = -inf */
738 else
739 return Py_NAN; /* log(-ve) = nan */
740 }
741 else if (Py_IS_NAN(x))
742 return x; /* log(nan) = nan */
743 else if (x > 0.0)
744 return x; /* log(inf) = inf */
745 else {
746 errno = EDOM;
747 return Py_NAN; /* log(-inf) = nan */
748 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000749}
750
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200751/*
752 log2: log to base 2.
753
754 Uses an algorithm that should:
Mark Dickinson83b8c0b2011-05-09 08:40:20 +0100755
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200756 (a) produce exact results for powers of 2, and
Mark Dickinson83b8c0b2011-05-09 08:40:20 +0100757 (b) give a monotonic log2 (for positive finite floats),
758 assuming that the system log is monotonic.
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200759*/
760
761static double
762m_log2(double x)
763{
764 if (!Py_IS_FINITE(x)) {
765 if (Py_IS_NAN(x))
766 return x; /* log2(nan) = nan */
767 else if (x > 0.0)
768 return x; /* log2(+inf) = +inf */
769 else {
770 errno = EDOM;
771 return Py_NAN; /* log2(-inf) = nan, invalid-operation */
772 }
773 }
774
775 if (x > 0.0) {
Victor Stinner8f9f8d62011-05-09 12:45:41 +0200776#ifdef HAVE_LOG2
777 return log2(x);
778#else
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200779 double m;
780 int e;
781 m = frexp(x, &e);
782 /* We want log2(m * 2**e) == log(m) / log(2) + e. Care is needed when
783 * x is just greater than 1.0: in that case e is 1, log(m) is negative,
784 * and we get significant cancellation error from the addition of
785 * log(m) / log(2) to e. The slight rewrite of the expression below
786 * avoids this problem.
787 */
788 if (x >= 1.0) {
789 return log(2.0 * m) / log(2.0) + (e - 1);
790 }
791 else {
792 return log(m) / log(2.0) + e;
793 }
Victor Stinner8f9f8d62011-05-09 12:45:41 +0200794#endif
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200795 }
796 else if (x == 0.0) {
797 errno = EDOM;
798 return -Py_HUGE_VAL; /* log2(0) = -inf, divide-by-zero */
799 }
800 else {
801 errno = EDOM;
Mark Dickinson23442582011-05-09 08:05:00 +0100802 return Py_NAN; /* log2(-inf) = nan, invalid-operation */
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200803 }
804}
805
Mark Dickinsone675f082008-12-11 21:56:00 +0000806static double
807m_log10(double x)
808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 if (Py_IS_FINITE(x)) {
810 if (x > 0.0)
811 return log10(x);
812 errno = EDOM;
813 if (x == 0.0)
814 return -Py_HUGE_VAL; /* log10(0) = -inf */
815 else
816 return Py_NAN; /* log10(-ve) = nan */
817 }
818 else if (Py_IS_NAN(x))
819 return x; /* log10(nan) = nan */
820 else if (x > 0.0)
821 return x; /* log10(inf) = inf */
822 else {
823 errno = EDOM;
824 return Py_NAN; /* log10(-inf) = nan */
825 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000826}
827
828
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200829/*[clinic input]
830math.gcd
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300831
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200832 x as a: object
833 y as b: object
834 /
835
836greatest common divisor of x and y
837[clinic start generated code]*/
838
839static PyObject *
840math_gcd_impl(PyObject *module, PyObject *a, PyObject *b)
841/*[clinic end generated code: output=7b2e0c151bd7a5d8 input=c2691e57fb2a98fa]*/
842{
843 PyObject *g;
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300844
845 a = PyNumber_Index(a);
846 if (a == NULL)
847 return NULL;
848 b = PyNumber_Index(b);
849 if (b == NULL) {
850 Py_DECREF(a);
851 return NULL;
852 }
853 g = _PyLong_GCD(a, b);
854 Py_DECREF(a);
855 Py_DECREF(b);
856 return g;
857}
858
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300859
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000860/* Call is_error when errno != 0, and where x is the result libm
861 * returned. is_error will usually set up an exception and return
862 * true (1), but may return false (0) without setting up an exception.
863 */
864static int
865is_error(double x)
866{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 int result = 1; /* presumption of guilt */
868 assert(errno); /* non-zero errno is a precondition for calling */
869 if (errno == EDOM)
870 PyErr_SetString(PyExc_ValueError, "math domain error");
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 else if (errno == ERANGE) {
873 /* ANSI C generally requires libm functions to set ERANGE
874 * on overflow, but also generally *allows* them to set
875 * ERANGE on underflow too. There's no consistency about
876 * the latter across platforms.
877 * Alas, C99 never requires that errno be set.
878 * Here we suppress the underflow errors (libm functions
879 * should return a zero on underflow, and +- HUGE_VAL on
880 * overflow, so testing the result for zero suffices to
881 * distinguish the cases).
882 *
883 * On some platforms (Ubuntu/ia64) it seems that errno can be
884 * set to ERANGE for subnormal results that do *not* underflow
885 * to zero. So to be safe, we'll ignore ERANGE whenever the
886 * function result is less than one in absolute value.
887 */
888 if (fabs(x) < 1.0)
889 result = 0;
890 else
891 PyErr_SetString(PyExc_OverflowError,
892 "math range error");
893 }
894 else
895 /* Unexpected math error */
896 PyErr_SetFromErrno(PyExc_ValueError);
897 return result;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000898}
899
Mark Dickinsone675f082008-12-11 21:56:00 +0000900/*
Christian Heimes53876d92008-04-19 00:31:39 +0000901 math_1 is used to wrap a libm function f that takes a double
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200902 argument and returns a double.
Christian Heimes53876d92008-04-19 00:31:39 +0000903
904 The error reporting follows these rules, which are designed to do
905 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
906 platforms.
907
908 - a NaN result from non-NaN inputs causes ValueError to be raised
909 - an infinite result from finite inputs causes OverflowError to be
910 raised if can_overflow is 1, or raises ValueError if can_overflow
911 is 0.
912 - if the result is finite and errno == EDOM then ValueError is
913 raised
914 - if the result is finite and nonzero and errno == ERANGE then
915 OverflowError is raised
916
917 The last rule is used to catch overflow on platforms which follow
918 C89 but for which HUGE_VAL is not an infinity.
919
920 For the majority of one-argument functions these rules are enough
921 to ensure that Python's functions behave as specified in 'Annex F'
922 of the C99 standard, with the 'invalid' and 'divide-by-zero'
923 floating-point exceptions mapping to Python's ValueError and the
924 'overflow' floating-point exception mapping to OverflowError.
925 math_1 only works for functions that don't have singularities *and*
926 the possibility of overflow; fortunately, that covers everything we
927 care about right now.
928*/
929
Barry Warsaw8b43b191996-12-09 22:32:36 +0000930static PyObject *
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000931math_1_to_whatever(PyObject *arg, double (*func) (double),
Christian Heimes53876d92008-04-19 00:31:39 +0000932 PyObject *(*from_double_func) (double),
933 int can_overflow)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000934{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 double x, r;
936 x = PyFloat_AsDouble(arg);
937 if (x == -1.0 && PyErr_Occurred())
938 return NULL;
939 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 r = (*func)(x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 if (Py_IS_NAN(r) && !Py_IS_NAN(x)) {
942 PyErr_SetString(PyExc_ValueError,
943 "math domain error"); /* invalid arg */
944 return NULL;
945 }
946 if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) {
Benjamin Peterson2354a752012-03-13 16:13:09 -0500947 if (can_overflow)
948 PyErr_SetString(PyExc_OverflowError,
949 "math range error"); /* overflow */
950 else
951 PyErr_SetString(PyExc_ValueError,
952 "math domain error"); /* singularity */
953 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 }
955 if (Py_IS_FINITE(r) && errno && is_error(r))
956 /* this branch unnecessary on most platforms */
957 return NULL;
Mark Dickinsonde429622008-05-01 00:19:23 +0000958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 return (*from_double_func)(r);
Christian Heimes53876d92008-04-19 00:31:39 +0000960}
961
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000962/* variant of math_1, to be used when the function being wrapped is known to
963 set errno properly (that is, errno = EDOM for invalid or divide-by-zero,
964 errno = ERANGE for overflow). */
965
966static PyObject *
967math_1a(PyObject *arg, double (*func) (double))
968{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 double x, r;
970 x = PyFloat_AsDouble(arg);
971 if (x == -1.0 && PyErr_Occurred())
972 return NULL;
973 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 r = (*func)(x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 if (errno && is_error(r))
976 return NULL;
977 return PyFloat_FromDouble(r);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000978}
979
Christian Heimes53876d92008-04-19 00:31:39 +0000980/*
981 math_2 is used to wrap a libm function f that takes two double
982 arguments and returns a double.
983
984 The error reporting follows these rules, which are designed to do
985 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
986 platforms.
987
988 - a NaN result from non-NaN inputs causes ValueError to be raised
989 - an infinite result from finite inputs causes OverflowError to be
990 raised.
991 - if the result is finite and errno == EDOM then ValueError is
992 raised
993 - if the result is finite and nonzero and errno == ERANGE then
994 OverflowError is raised
995
996 The last rule is used to catch overflow on platforms which follow
997 C89 but for which HUGE_VAL is not an infinity.
998
999 For most two-argument functions (copysign, fmod, hypot, atan2)
1000 these rules are enough to ensure that Python's functions behave as
1001 specified in 'Annex F' of the C99 standard, with the 'invalid' and
1002 'divide-by-zero' floating-point exceptions mapping to Python's
1003 ValueError and the 'overflow' floating-point exception mapping to
1004 OverflowError.
1005*/
1006
1007static PyObject *
1008math_1(PyObject *arg, double (*func) (double), int can_overflow)
1009{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow);
Jeffrey Yasskinc2155832008-01-05 20:03:11 +00001011}
1012
1013static PyObject *
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02001014math_2(PyObject *const *args, Py_ssize_t nargs,
1015 double (*func) (double, double), const char *funcname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001016{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 double x, y, r;
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02001018 if (!_PyArg_CheckPositional(funcname, nargs, 2, 2))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 return NULL;
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02001020 x = PyFloat_AsDouble(args[0]);
1021 y = PyFloat_AsDouble(args[1]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
1023 return NULL;
1024 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 r = (*func)(x, y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 if (Py_IS_NAN(r)) {
1027 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1028 errno = EDOM;
1029 else
1030 errno = 0;
1031 }
1032 else if (Py_IS_INFINITY(r)) {
1033 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
1034 errno = ERANGE;
1035 else
1036 errno = 0;
1037 }
1038 if (errno && is_error(r))
1039 return NULL;
1040 else
1041 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001042}
1043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044#define FUNC1(funcname, func, can_overflow, docstring) \
1045 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
1046 return math_1(args, func, can_overflow); \
1047 }\
1048 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050#define FUNC1A(funcname, func, docstring) \
1051 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
1052 return math_1a(args, func); \
1053 }\
1054 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001055
Fred Drake40c48682000-07-03 18:11:56 +00001056#define FUNC2(funcname, func, docstring) \
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02001057 static PyObject * math_##funcname(PyObject *self, PyObject *const *args, Py_ssize_t nargs) { \
1058 return math_2(args, nargs, func, #funcname); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 }\
1060 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001061
Christian Heimes53876d92008-04-19 00:31:39 +00001062FUNC1(acos, acos, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001063 "acos($module, x, /)\n--\n\n"
Giovanni Cappellottodc3f99f2019-07-13 09:59:55 -04001064 "Return the arc cosine (measured in radians) of x.\n\n"
1065 "The result is between 0 and pi.")
Mark Dickinsonf3718592009-12-21 15:27:41 +00001066FUNC1(acosh, m_acosh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001067 "acosh($module, x, /)\n--\n\n"
1068 "Return the inverse hyperbolic cosine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001069FUNC1(asin, asin, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001070 "asin($module, x, /)\n--\n\n"
Giovanni Cappellottodc3f99f2019-07-13 09:59:55 -04001071 "Return the arc sine (measured in radians) of x.\n\n"
1072 "The result is between -pi/2 and pi/2.")
Mark Dickinsonf3718592009-12-21 15:27:41 +00001073FUNC1(asinh, m_asinh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001074 "asinh($module, x, /)\n--\n\n"
1075 "Return the inverse hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001076FUNC1(atan, atan, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001077 "atan($module, x, /)\n--\n\n"
Giovanni Cappellottodc3f99f2019-07-13 09:59:55 -04001078 "Return the arc tangent (measured in radians) of x.\n\n"
1079 "The result is between -pi/2 and pi/2.")
Christian Heimese57950f2008-04-21 13:08:03 +00001080FUNC2(atan2, m_atan2,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001081 "atan2($module, y, x, /)\n--\n\n"
1082 "Return the arc tangent (measured in radians) of y/x.\n\n"
Tim Petersfe71f812001-08-07 22:10:00 +00001083 "Unlike atan(y/x), the signs of both x and y are considered.")
Mark Dickinsonf3718592009-12-21 15:27:41 +00001084FUNC1(atanh, m_atanh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001085 "atanh($module, x, /)\n--\n\n"
1086 "Return the inverse hyperbolic tangent of x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +00001087
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001088/*[clinic input]
1089math.ceil
1090
1091 x as number: object
1092 /
1093
1094Return the ceiling of x as an Integral.
1095
1096This is the smallest integer >= x.
1097[clinic start generated code]*/
1098
1099static PyObject *
1100math_ceil(PyObject *module, PyObject *number)
1101/*[clinic end generated code: output=6c3b8a78bc201c67 input=2725352806399cab]*/
1102{
Benjamin Petersonce798522012-01-22 11:24:29 -05001103 _Py_IDENTIFIER(__ceil__);
Guido van Rossum13e05de2007-08-23 22:56:55 +00001104
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001105 if (!PyFloat_CheckExact(number)) {
1106 PyObject *method = _PyObject_LookupSpecial(number, &PyId___ceil__);
1107 if (method != NULL) {
1108 PyObject *result = _PyObject_CallNoArg(method);
1109 Py_DECREF(method);
1110 return result;
1111 }
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001112 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 return NULL;
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001114 }
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001115 double x = PyFloat_AsDouble(number);
1116 if (x == -1.0 && PyErr_Occurred())
1117 return NULL;
1118
1119 return PyLong_FromDouble(ceil(x));
Guido van Rossum13e05de2007-08-23 22:56:55 +00001120}
1121
Christian Heimes072c0f12008-01-03 23:01:04 +00001122FUNC2(copysign, copysign,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001123 "copysign($module, x, y, /)\n--\n\n"
1124 "Return a float with the magnitude (absolute value) of x but the sign of y.\n\n"
1125 "On platforms that support signed zeros, copysign(1.0, -0.0)\n"
1126 "returns -1.0.\n")
Christian Heimes53876d92008-04-19 00:31:39 +00001127FUNC1(cos, cos, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001128 "cos($module, x, /)\n--\n\n"
1129 "Return the cosine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001130FUNC1(cosh, cosh, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001131 "cosh($module, x, /)\n--\n\n"
1132 "Return the hyperbolic cosine of x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +00001133FUNC1A(erf, m_erf,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001134 "erf($module, x, /)\n--\n\n"
1135 "Error function at x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +00001136FUNC1A(erfc, m_erfc,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001137 "erfc($module, x, /)\n--\n\n"
1138 "Complementary error function at x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001139FUNC1(exp, exp, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001140 "exp($module, x, /)\n--\n\n"
1141 "Return e raised to the power of x.")
Mark Dickinson664b5112009-12-16 20:23:42 +00001142FUNC1(expm1, m_expm1, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001143 "expm1($module, x, /)\n--\n\n"
1144 "Return exp(x)-1.\n\n"
Mark Dickinson664b5112009-12-16 20:23:42 +00001145 "This function avoids the loss of precision involved in the direct "
1146 "evaluation of exp(x)-1 for small x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001147FUNC1(fabs, fabs, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001148 "fabs($module, x, /)\n--\n\n"
1149 "Return the absolute value of the float x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +00001150
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001151/*[clinic input]
1152math.floor
1153
1154 x as number: object
1155 /
1156
1157Return the floor of x as an Integral.
1158
1159This is the largest integer <= x.
1160[clinic start generated code]*/
1161
1162static PyObject *
1163math_floor(PyObject *module, PyObject *number)
1164/*[clinic end generated code: output=c6a65c4884884b8a input=63af6b5d7ebcc3d6]*/
1165{
Benjamin Petersonce798522012-01-22 11:24:29 -05001166 _Py_IDENTIFIER(__floor__);
Guido van Rossum13e05de2007-08-23 22:56:55 +00001167
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001168 if (!PyFloat_CheckExact(number)) {
1169 PyObject *method = _PyObject_LookupSpecial(number, &PyId___floor__);
1170 if (method != NULL) {
1171 PyObject *result = _PyObject_CallNoArg(method);
1172 Py_DECREF(method);
1173 return result;
1174 }
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001175 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 return NULL;
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001177 }
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001178 double x = PyFloat_AsDouble(number);
1179 if (x == -1.0 && PyErr_Occurred())
1180 return NULL;
1181
1182 return PyLong_FromDouble(floor(x));
Guido van Rossum13e05de2007-08-23 22:56:55 +00001183}
1184
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001185FUNC1A(gamma, m_tgamma,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001186 "gamma($module, x, /)\n--\n\n"
1187 "Gamma function at x.")
Mark Dickinson05d2e082009-12-11 20:17:17 +00001188FUNC1A(lgamma, m_lgamma,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001189 "lgamma($module, x, /)\n--\n\n"
1190 "Natural logarithm of absolute value of Gamma function at x.")
Mark Dickinsonbe64d952010-07-07 16:21:29 +00001191FUNC1(log1p, m_log1p, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001192 "log1p($module, x, /)\n--\n\n"
1193 "Return the natural logarithm of 1+x (base e).\n\n"
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001194 "The result is computed in a way which is accurate for x near zero.")
Mark Dickinsona0ce3752017-04-05 18:34:27 +01001195FUNC2(remainder, m_remainder,
1196 "remainder($module, x, y, /)\n--\n\n"
1197 "Difference between x and the closest integer multiple of y.\n\n"
1198 "Return x - n*y where n*y is the closest integer multiple of y.\n"
1199 "In the case where x is exactly halfway between two multiples of\n"
1200 "y, the nearest even value of n is used. The result is always exact.")
Christian Heimes53876d92008-04-19 00:31:39 +00001201FUNC1(sin, sin, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001202 "sin($module, x, /)\n--\n\n"
1203 "Return the sine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001204FUNC1(sinh, sinh, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001205 "sinh($module, x, /)\n--\n\n"
1206 "Return the hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001207FUNC1(sqrt, sqrt, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001208 "sqrt($module, x, /)\n--\n\n"
1209 "Return the square root of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001210FUNC1(tan, tan, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001211 "tan($module, x, /)\n--\n\n"
1212 "Return the tangent of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001213FUNC1(tanh, tanh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001214 "tanh($module, x, /)\n--\n\n"
1215 "Return the hyperbolic tangent of x.")
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001216
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001217/* Precision summation function as msum() by Raymond Hettinger in
1218 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
1219 enhanced with the exact partials sum and roundoff from Mark
1220 Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
1221 See those links for more details, proofs and other references.
1222
1223 Note 1: IEEE 754R floating point semantics are assumed,
1224 but the current implementation does not re-establish special
1225 value semantics across iterations (i.e. handling -Inf + Inf).
1226
1227 Note 2: No provision is made for intermediate overflow handling;
Georg Brandlf78e02b2008-06-10 17:40:04 +00001228 therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001229 sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
1230 overflow of the first partial sum.
1231
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001232 Note 3: The intermediate values lo, yr, and hi are declared volatile so
1233 aggressive compilers won't algebraically reduce lo to always be exactly 0.0.
Georg Brandlf78e02b2008-06-10 17:40:04 +00001234 Also, the volatile declaration forces the values to be stored in memory as
1235 regular doubles instead of extended long precision (80-bit) values. This
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001236 prevents double rounding because any addition or subtraction of two doubles
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 can be resolved exactly into double-sized hi and lo values. As long as the
Georg Brandlf78e02b2008-06-10 17:40:04 +00001238 hi value gets forced into a double before yr and lo are computed, the extra
1239 bits in downstream extended precision operations (x87 for example) will be
1240 exactly zero and therefore can be losslessly stored back into a double,
1241 thereby preventing double rounding.
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001242
1243 Note 4: A similar implementation is in Modules/cmathmodule.c.
1244 Be sure to update both when making changes.
1245
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001246 Note 5: The signature of math.fsum() differs from builtins.sum()
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001247 because the start argument doesn't make sense in the context of
1248 accurate summation. Since the partials table is collapsed before
1249 returning a result, sum(seq2, start=sum(seq1)) may not equal the
1250 accurate result returned by sum(itertools.chain(seq1, seq2)).
1251*/
1252
1253#define NUM_PARTIALS 32 /* initial partials array size, on stack */
1254
1255/* Extend the partials array p[] by doubling its size. */
1256static int /* non-zero on error */
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001257_fsum_realloc(double **p_ptr, Py_ssize_t n,
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001258 double *ps, Py_ssize_t *m_ptr)
1259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 void *v = NULL;
1261 Py_ssize_t m = *m_ptr;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 m += m; /* double */
Victor Stinner049e5092014-08-17 22:20:00 +02001264 if (n < m && (size_t)m < ((size_t)PY_SSIZE_T_MAX / sizeof(double))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 double *p = *p_ptr;
1266 if (p == ps) {
1267 v = PyMem_Malloc(sizeof(double) * m);
1268 if (v != NULL)
1269 memcpy(v, ps, sizeof(double) * n);
1270 }
1271 else
1272 v = PyMem_Realloc(p, sizeof(double) * m);
1273 }
1274 if (v == NULL) { /* size overflow or no memory */
1275 PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
1276 return 1;
1277 }
1278 *p_ptr = (double*) v;
1279 *m_ptr = m;
1280 return 0;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001281}
1282
1283/* Full precision summation of a sequence of floats.
1284
1285 def msum(iterable):
1286 partials = [] # sorted, non-overlapping partial sums
1287 for x in iterable:
Mark Dickinsonfdb0acc2010-06-25 20:22:24 +00001288 i = 0
1289 for y in partials:
1290 if abs(x) < abs(y):
1291 x, y = y, x
1292 hi = x + y
1293 lo = y - (hi - x)
1294 if lo:
1295 partials[i] = lo
1296 i += 1
1297 x = hi
1298 partials[i:] = [x]
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001299 return sum_exact(partials)
1300
1301 Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
1302 are exactly equal to x+y. The inner loop applies hi/lo summation to each
1303 partial so that the list of partial sums remains exact.
1304
1305 Sum_exact() adds the partial sums exactly and correctly rounds the final
1306 result (using the round-half-to-even rule). The items in partials remain
1307 non-zero, non-special, non-overlapping and strictly increasing in
1308 magnitude, but possibly not all having the same sign.
1309
1310 Depends on IEEE 754 arithmetic guarantees and half-even rounding.
1311*/
1312
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001313/*[clinic input]
1314math.fsum
1315
1316 seq: object
1317 /
1318
1319Return an accurate floating point sum of values in the iterable seq.
1320
1321Assumes IEEE-754 floating point arithmetic.
1322[clinic start generated code]*/
1323
1324static PyObject *
1325math_fsum(PyObject *module, PyObject *seq)
1326/*[clinic end generated code: output=ba5c672b87fe34fc input=c51b7d8caf6f6e82]*/
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 PyObject *item, *iter, *sum = NULL;
1329 Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
1330 double x, y, t, ps[NUM_PARTIALS], *p = ps;
1331 double xsave, special_sum = 0.0, inf_sum = 0.0;
1332 volatile double hi, yr, lo;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 iter = PyObject_GetIter(seq);
1335 if (iter == NULL)
1336 return NULL;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 for(;;) { /* for x in iterable */
1339 assert(0 <= n && n <= m);
1340 assert((m == NUM_PARTIALS && p == ps) ||
1341 (m > NUM_PARTIALS && p != NULL));
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 item = PyIter_Next(iter);
1344 if (item == NULL) {
1345 if (PyErr_Occurred())
1346 goto _fsum_error;
1347 break;
1348 }
Raymond Hettingercfd735e2019-01-29 20:39:53 -08001349 ASSIGN_DOUBLE(x, item, error_with_item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 Py_DECREF(item);
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 xsave = x;
1353 for (i = j = 0; j < n; j++) { /* for y in partials */
1354 y = p[j];
1355 if (fabs(x) < fabs(y)) {
1356 t = x; x = y; y = t;
1357 }
1358 hi = x + y;
1359 yr = hi - x;
1360 lo = y - yr;
1361 if (lo != 0.0)
1362 p[i++] = lo;
1363 x = hi;
1364 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 n = i; /* ps[i:] = [x] */
1367 if (x != 0.0) {
1368 if (! Py_IS_FINITE(x)) {
1369 /* a nonfinite x could arise either as
1370 a result of intermediate overflow, or
1371 as a result of a nan or inf in the
1372 summands */
1373 if (Py_IS_FINITE(xsave)) {
1374 PyErr_SetString(PyExc_OverflowError,
1375 "intermediate overflow in fsum");
1376 goto _fsum_error;
1377 }
1378 if (Py_IS_INFINITY(xsave))
1379 inf_sum += xsave;
1380 special_sum += xsave;
1381 /* reset partials */
1382 n = 0;
1383 }
1384 else if (n >= m && _fsum_realloc(&p, n, ps, &m))
1385 goto _fsum_error;
1386 else
1387 p[n++] = x;
1388 }
1389 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 if (special_sum != 0.0) {
1392 if (Py_IS_NAN(inf_sum))
1393 PyErr_SetString(PyExc_ValueError,
1394 "-inf + inf in fsum");
1395 else
1396 sum = PyFloat_FromDouble(special_sum);
1397 goto _fsum_error;
1398 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 hi = 0.0;
1401 if (n > 0) {
1402 hi = p[--n];
1403 /* sum_exact(ps, hi) from the top, stop when the sum becomes
1404 inexact. */
1405 while (n > 0) {
1406 x = hi;
1407 y = p[--n];
1408 assert(fabs(y) < fabs(x));
1409 hi = x + y;
1410 yr = hi - x;
1411 lo = y - yr;
1412 if (lo != 0.0)
1413 break;
1414 }
1415 /* Make half-even rounding work across multiple partials.
1416 Needed so that sum([1e-16, 1, 1e16]) will round-up the last
1417 digit to two instead of down to zero (the 1e-16 makes the 1
1418 slightly closer to two). With a potential 1 ULP rounding
1419 error fixed-up, math.fsum() can guarantee commutativity. */
1420 if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
1421 (lo > 0.0 && p[n-1] > 0.0))) {
1422 y = lo * 2.0;
1423 x = hi + y;
1424 yr = x - hi;
1425 if (y == yr)
1426 hi = x;
1427 }
1428 }
1429 sum = PyFloat_FromDouble(hi);
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001430
Raymond Hettingercfd735e2019-01-29 20:39:53 -08001431 _fsum_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 Py_DECREF(iter);
1433 if (p != ps)
1434 PyMem_Free(p);
1435 return sum;
Raymond Hettingercfd735e2019-01-29 20:39:53 -08001436
1437 error_with_item:
1438 Py_DECREF(item);
1439 goto _fsum_error;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001440}
1441
1442#undef NUM_PARTIALS
1443
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001444
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001445static unsigned long
1446count_set_bits(unsigned long n)
1447{
1448 unsigned long count = 0;
1449 while (n != 0) {
1450 ++count;
1451 n &= n - 1; /* clear least significant bit */
1452 }
1453 return count;
1454}
1455
Mark Dickinson73934b92019-05-18 12:29:50 +01001456/* Integer square root
1457
1458Given a nonnegative integer `n`, we want to compute the largest integer
1459`a` for which `a * a <= n`, or equivalently the integer part of the exact
1460square root of `n`.
1461
1462We use an adaptive-precision pure-integer version of Newton's iteration. Given
1463a positive integer `n`, the algorithm produces at each iteration an integer
1464approximation `a` to the square root of `n >> s` for some even integer `s`,
1465with `s` decreasing as the iterations progress. On the final iteration, `s` is
1466zero and we have an approximation to the square root of `n` itself.
1467
1468At every step, the approximation `a` is strictly within 1.0 of the true square
1469root, so we have
1470
1471 (a - 1)**2 < (n >> s) < (a + 1)**2
1472
1473After the final iteration, a check-and-correct step is needed to determine
1474whether `a` or `a - 1` gives the desired integer square root of `n`.
1475
1476The algorithm is remarkable in its simplicity. There's no need for a
1477per-iteration check-and-correct step, and termination is straightforward: the
1478number of iterations is known in advance (it's exactly `floor(log2(log2(n)))`
1479for `n > 1`). The only tricky part of the correctness proof is in establishing
1480that the bound `(a - 1)**2 < (n >> s) < (a + 1)**2` is maintained from one
1481iteration to the next. A sketch of the proof of this is given below.
1482
1483In addition to the proof sketch, a formal, computer-verified proof
1484of correctness (using Lean) of an equivalent recursive algorithm can be found
1485here:
1486
1487 https://github.com/mdickinson/snippets/blob/master/proofs/isqrt/src/isqrt.lean
1488
1489
1490Here's Python code equivalent to the C implementation below:
1491
1492 def isqrt(n):
1493 """
1494 Return the integer part of the square root of the input.
1495 """
1496 n = operator.index(n)
1497
1498 if n < 0:
1499 raise ValueError("isqrt() argument must be nonnegative")
1500 if n == 0:
1501 return 0
1502
1503 c = (n.bit_length() - 1) // 2
1504 a = 1
1505 d = 0
1506 for s in reversed(range(c.bit_length())):
Mark Dickinson2dfeaa92019-06-16 17:53:21 +01001507 # Loop invariant: (a-1)**2 < (n >> 2*(c - d)) < (a+1)**2
Mark Dickinson73934b92019-05-18 12:29:50 +01001508 e = d
1509 d = c >> s
1510 a = (a << d - e - 1) + (n >> 2*c - e - d + 1) // a
Mark Dickinson73934b92019-05-18 12:29:50 +01001511
1512 return a - (a*a > n)
1513
1514
1515Sketch of proof of correctness
1516------------------------------
1517
1518The delicate part of the correctness proof is showing that the loop invariant
1519is preserved from one iteration to the next. That is, just before the line
1520
1521 a = (a << d - e - 1) + (n >> 2*c - e - d + 1) // a
1522
1523is executed in the above code, we know that
1524
1525 (1) (a - 1)**2 < (n >> 2*(c - e)) < (a + 1)**2.
1526
1527(since `e` is always the value of `d` from the previous iteration). We must
1528prove that after that line is executed, we have
1529
1530 (a - 1)**2 < (n >> 2*(c - d)) < (a + 1)**2
1531
Min ho Kimf7d72e42019-07-06 07:39:32 +10001532To facilitate the proof, we make some changes of notation. Write `m` for
Mark Dickinson73934b92019-05-18 12:29:50 +01001533`n >> 2*(c-d)`, and write `b` for the new value of `a`, so
1534
1535 b = (a << d - e - 1) + (n >> 2*c - e - d + 1) // a
1536
1537or equivalently:
1538
1539 (2) b = (a << d - e - 1) + (m >> d - e + 1) // a
1540
1541Then we can rewrite (1) as:
1542
1543 (3) (a - 1)**2 < (m >> 2*(d - e)) < (a + 1)**2
1544
1545and we must show that (b - 1)**2 < m < (b + 1)**2.
1546
1547From this point on, we switch to mathematical notation, so `/` means exact
1548division rather than integer division and `^` is used for exponentiation. We
1549use the `√` symbol for the exact square root. In (3), we can remove the
1550implicit floor operation to give:
1551
1552 (4) (a - 1)^2 < m / 4^(d - e) < (a + 1)^2
1553
1554Taking square roots throughout (4), scaling by `2^(d-e)`, and rearranging gives
1555
1556 (5) 0 <= | 2^(d-e)a - √m | < 2^(d-e)
1557
1558Squaring and dividing through by `2^(d-e+1) a` gives
1559
1560 (6) 0 <= 2^(d-e-1) a + m / (2^(d-e+1) a) - √m < 2^(d-e-1) / a
1561
1562We'll show below that `2^(d-e-1) <= a`. Given that, we can replace the
1563right-hand side of (6) with `1`, and now replacing the central
1564term `m / (2^(d-e+1) a)` with its floor in (6) gives
1565
1566 (7) -1 < 2^(d-e-1) a + m // 2^(d-e+1) a - √m < 1
1567
1568Or equivalently, from (2):
1569
1570 (7) -1 < b - √m < 1
1571
1572and rearranging gives that `(b-1)^2 < m < (b+1)^2`, which is what we needed
1573to prove.
1574
1575We're not quite done: we still have to prove the inequality `2^(d - e - 1) <=
1576a` that was used to get line (7) above. From the definition of `c`, we have
1577`4^c <= n`, which implies
1578
1579 (8) 4^d <= m
1580
1581also, since `e == d >> 1`, `d` is at most `2e + 1`, from which it follows
1582that `2d - 2e - 1 <= d` and hence that
1583
1584 (9) 4^(2d - 2e - 1) <= m
1585
1586Dividing both sides by `4^(d - e)` gives
1587
1588 (10) 4^(d - e - 1) <= m / 4^(d - e)
1589
1590But we know from (4) that `m / 4^(d-e) < (a + 1)^2`, hence
1591
1592 (11) 4^(d - e - 1) < (a + 1)^2
1593
1594Now taking square roots of both sides and observing that both `2^(d-e-1)` and
1595`a` are integers gives `2^(d - e - 1) <= a`, which is what we needed. This
1596completes the proof sketch.
1597
1598*/
1599
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001600
1601/* Approximate square root of a large 64-bit integer.
1602
1603 Given `n` satisfying `2**62 <= n < 2**64`, return `a`
1604 satisfying `(a - 1)**2 < n < (a + 1)**2`. */
1605
1606static uint64_t
1607_approximate_isqrt(uint64_t n)
1608{
1609 uint32_t u = 1U + (n >> 62);
1610 u = (u << 1) + (n >> 59) / u;
1611 u = (u << 3) + (n >> 53) / u;
1612 u = (u << 7) + (n >> 41) / u;
1613 return (u << 15) + (n >> 17) / u;
1614}
1615
Mark Dickinson73934b92019-05-18 12:29:50 +01001616/*[clinic input]
1617math.isqrt
1618
1619 n: object
1620 /
1621
1622Return the integer part of the square root of the input.
1623[clinic start generated code]*/
1624
1625static PyObject *
1626math_isqrt(PyObject *module, PyObject *n)
1627/*[clinic end generated code: output=35a6f7f980beab26 input=5b6e7ae4fa6c43d6]*/
1628{
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001629 int a_too_large, c_bit_length;
Mark Dickinson73934b92019-05-18 12:29:50 +01001630 size_t c, d;
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001631 uint64_t m, u;
Mark Dickinson73934b92019-05-18 12:29:50 +01001632 PyObject *a = NULL, *b;
1633
1634 n = PyNumber_Index(n);
1635 if (n == NULL) {
1636 return NULL;
1637 }
1638
1639 if (_PyLong_Sign(n) < 0) {
1640 PyErr_SetString(
1641 PyExc_ValueError,
1642 "isqrt() argument must be nonnegative");
1643 goto error;
1644 }
1645 if (_PyLong_Sign(n) == 0) {
1646 Py_DECREF(n);
1647 return PyLong_FromLong(0);
1648 }
1649
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001650 /* c = (n.bit_length() - 1) // 2 */
Mark Dickinson73934b92019-05-18 12:29:50 +01001651 c = _PyLong_NumBits(n);
1652 if (c == (size_t)(-1)) {
1653 goto error;
1654 }
1655 c = (c - 1U) / 2U;
1656
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001657 /* Fast path: if c <= 31 then n < 2**64 and we can compute directly with a
1658 fast, almost branch-free algorithm. In the final correction, we use `u*u
1659 - 1 >= m` instead of the simpler `u*u > m` in order to get the correct
1660 result in the corner case where `u=2**32`. */
1661 if (c <= 31U) {
1662 m = (uint64_t)PyLong_AsUnsignedLongLong(n);
1663 Py_DECREF(n);
1664 if (m == (uint64_t)(-1) && PyErr_Occurred()) {
1665 return NULL;
1666 }
1667 u = _approximate_isqrt(m << (62U - 2U*c)) >> (31U - c);
1668 u -= u * u - 1U >= m;
1669 return PyLong_FromUnsignedLongLong((unsigned long long)u);
Mark Dickinson73934b92019-05-18 12:29:50 +01001670 }
1671
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001672 /* Slow path: n >= 2**64. We perform the first five iterations in C integer
1673 arithmetic, then switch to using Python long integers. */
1674
1675 /* From n >= 2**64 it follows that c.bit_length() >= 6. */
1676 c_bit_length = 6;
1677 while ((c >> c_bit_length) > 0U) {
1678 ++c_bit_length;
1679 }
1680
1681 /* Initialise d and a. */
1682 d = c >> (c_bit_length - 5);
1683 b = _PyLong_Rshift(n, 2U*c - 62U);
1684 if (b == NULL) {
1685 goto error;
1686 }
1687 m = (uint64_t)PyLong_AsUnsignedLongLong(b);
1688 Py_DECREF(b);
1689 if (m == (uint64_t)(-1) && PyErr_Occurred()) {
1690 goto error;
1691 }
1692 u = _approximate_isqrt(m) >> (31U - d);
1693 a = PyLong_FromUnsignedLongLong((unsigned long long)u);
Mark Dickinson73934b92019-05-18 12:29:50 +01001694 if (a == NULL) {
1695 goto error;
1696 }
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001697
1698 for (int s = c_bit_length - 6; s >= 0; --s) {
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03001699 PyObject *q;
Mark Dickinson73934b92019-05-18 12:29:50 +01001700 size_t e = d;
1701
1702 d = c >> s;
1703
1704 /* q = (n >> 2*c - e - d + 1) // a */
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03001705 q = _PyLong_Rshift(n, 2U*c - d - e + 1U);
Mark Dickinson73934b92019-05-18 12:29:50 +01001706 if (q == NULL) {
1707 goto error;
1708 }
1709 Py_SETREF(q, PyNumber_FloorDivide(q, a));
1710 if (q == NULL) {
1711 goto error;
1712 }
1713
1714 /* a = (a << d - 1 - e) + q */
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03001715 Py_SETREF(a, _PyLong_Lshift(a, d - 1U - e));
Mark Dickinson73934b92019-05-18 12:29:50 +01001716 if (a == NULL) {
1717 Py_DECREF(q);
1718 goto error;
1719 }
1720 Py_SETREF(a, PyNumber_Add(a, q));
1721 Py_DECREF(q);
1722 if (a == NULL) {
1723 goto error;
1724 }
1725 }
1726
1727 /* The correct result is either a or a - 1. Figure out which, and
1728 decrement a if necessary. */
1729
1730 /* a_too_large = n < a * a */
1731 b = PyNumber_Multiply(a, a);
1732 if (b == NULL) {
1733 goto error;
1734 }
1735 a_too_large = PyObject_RichCompareBool(n, b, Py_LT);
1736 Py_DECREF(b);
1737 if (a_too_large == -1) {
1738 goto error;
1739 }
1740
1741 if (a_too_large) {
1742 Py_SETREF(a, PyNumber_Subtract(a, _PyLong_One));
1743 }
1744 Py_DECREF(n);
1745 return a;
1746
1747 error:
1748 Py_XDECREF(a);
1749 Py_DECREF(n);
1750 return NULL;
1751}
1752
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001753/* Divide-and-conquer factorial algorithm
1754 *
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07001755 * Based on the formula and pseudo-code provided at:
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001756 * http://www.luschny.de/math/factorial/binarysplitfact.html
1757 *
1758 * Faster algorithms exist, but they're more complicated and depend on
Ezio Melotti9527afd2010-07-08 15:03:02 +00001759 * a fast prime factorization algorithm.
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001760 *
1761 * Notes on the algorithm
1762 * ----------------------
1763 *
1764 * factorial(n) is written in the form 2**k * m, with m odd. k and m are
1765 * computed separately, and then combined using a left shift.
1766 *
1767 * The function factorial_odd_part computes the odd part m (i.e., the greatest
1768 * odd divisor) of factorial(n), using the formula:
1769 *
1770 * factorial_odd_part(n) =
1771 *
1772 * product_{i >= 0} product_{0 < j <= n / 2**i, j odd} j
1773 *
1774 * Example: factorial_odd_part(20) =
1775 *
1776 * (1) *
1777 * (1) *
1778 * (1 * 3 * 5) *
1779 * (1 * 3 * 5 * 7 * 9)
1780 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1781 *
1782 * Here i goes from large to small: the first term corresponds to i=4 (any
1783 * larger i gives an empty product), and the last term corresponds to i=0.
1784 * Each term can be computed from the last by multiplying by the extra odd
1785 * numbers required: e.g., to get from the penultimate term to the last one,
1786 * we multiply by (11 * 13 * 15 * 17 * 19).
1787 *
1788 * To see a hint of why this formula works, here are the same numbers as above
1789 * but with the even parts (i.e., the appropriate powers of 2) included. For
1790 * each subterm in the product for i, we multiply that subterm by 2**i:
1791 *
1792 * factorial(20) =
1793 *
1794 * (16) *
1795 * (8) *
1796 * (4 * 12 * 20) *
1797 * (2 * 6 * 10 * 14 * 18) *
1798 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1799 *
1800 * The factorial_partial_product function computes the product of all odd j in
1801 * range(start, stop) for given start and stop. It's used to compute the
1802 * partial products like (11 * 13 * 15 * 17 * 19) in the example above. It
1803 * operates recursively, repeatedly splitting the range into two roughly equal
1804 * pieces until the subranges are small enough to be computed using only C
1805 * integer arithmetic.
1806 *
1807 * The two-valuation k (i.e., the exponent of the largest power of 2 dividing
1808 * the factorial) is computed independently in the main math_factorial
1809 * function. By standard results, its value is:
1810 *
1811 * two_valuation = n//2 + n//4 + n//8 + ....
1812 *
1813 * It can be shown (e.g., by complete induction on n) that two_valuation is
1814 * equal to n - count_set_bits(n), where count_set_bits(n) gives the number of
1815 * '1'-bits in the binary expansion of n.
1816 */
1817
1818/* factorial_partial_product: Compute product(range(start, stop, 2)) using
1819 * divide and conquer. Assumes start and stop are odd and stop > start.
1820 * max_bits must be >= bit_length(stop - 2). */
1821
1822static PyObject *
1823factorial_partial_product(unsigned long start, unsigned long stop,
1824 unsigned long max_bits)
1825{
1826 unsigned long midpoint, num_operands;
1827 PyObject *left = NULL, *right = NULL, *result = NULL;
1828
1829 /* If the return value will fit an unsigned long, then we can
1830 * multiply in a tight, fast loop where each multiply is O(1).
1831 * Compute an upper bound on the number of bits required to store
1832 * the answer.
1833 *
1834 * Storing some integer z requires floor(lg(z))+1 bits, which is
1835 * conveniently the value returned by bit_length(z). The
1836 * product x*y will require at most
1837 * bit_length(x) + bit_length(y) bits to store, based
1838 * on the idea that lg product = lg x + lg y.
1839 *
1840 * We know that stop - 2 is the largest number to be multiplied. From
1841 * there, we have: bit_length(answer) <= num_operands *
1842 * bit_length(stop - 2)
1843 */
1844
1845 num_operands = (stop - start) / 2;
1846 /* The "num_operands <= 8 * SIZEOF_LONG" check guards against the
1847 * unlikely case of an overflow in num_operands * max_bits. */
1848 if (num_operands <= 8 * SIZEOF_LONG &&
1849 num_operands * max_bits <= 8 * SIZEOF_LONG) {
1850 unsigned long j, total;
1851 for (total = start, j = start + 2; j < stop; j += 2)
1852 total *= j;
1853 return PyLong_FromUnsignedLong(total);
1854 }
1855
1856 /* find midpoint of range(start, stop), rounded up to next odd number. */
1857 midpoint = (start + num_operands) | 1;
1858 left = factorial_partial_product(start, midpoint,
Niklas Fiekasc5b79002020-01-16 15:09:19 +01001859 _Py_bit_length(midpoint - 2));
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001860 if (left == NULL)
1861 goto error;
1862 right = factorial_partial_product(midpoint, stop, max_bits);
1863 if (right == NULL)
1864 goto error;
1865 result = PyNumber_Multiply(left, right);
1866
1867 error:
1868 Py_XDECREF(left);
1869 Py_XDECREF(right);
1870 return result;
1871}
1872
1873/* factorial_odd_part: compute the odd part of factorial(n). */
1874
1875static PyObject *
1876factorial_odd_part(unsigned long n)
1877{
1878 long i;
1879 unsigned long v, lower, upper;
1880 PyObject *partial, *tmp, *inner, *outer;
1881
1882 inner = PyLong_FromLong(1);
1883 if (inner == NULL)
1884 return NULL;
1885 outer = inner;
1886 Py_INCREF(outer);
1887
1888 upper = 3;
Niklas Fiekasc5b79002020-01-16 15:09:19 +01001889 for (i = _Py_bit_length(n) - 2; i >= 0; i--) {
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001890 v = n >> i;
1891 if (v <= 2)
1892 continue;
1893 lower = upper;
1894 /* (v + 1) | 1 = least odd integer strictly larger than n / 2**i */
1895 upper = (v + 1) | 1;
1896 /* Here inner is the product of all odd integers j in the range (0,
1897 n/2**(i+1)]. The factorial_partial_product call below gives the
1898 product of all odd integers j in the range (n/2**(i+1), n/2**i]. */
Niklas Fiekasc5b79002020-01-16 15:09:19 +01001899 partial = factorial_partial_product(lower, upper, _Py_bit_length(upper-2));
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001900 /* inner *= partial */
1901 if (partial == NULL)
1902 goto error;
1903 tmp = PyNumber_Multiply(inner, partial);
1904 Py_DECREF(partial);
1905 if (tmp == NULL)
1906 goto error;
1907 Py_DECREF(inner);
1908 inner = tmp;
1909 /* Now inner is the product of all odd integers j in the range (0,
1910 n/2**i], giving the inner product in the formula above. */
1911
1912 /* outer *= inner; */
1913 tmp = PyNumber_Multiply(outer, inner);
1914 if (tmp == NULL)
1915 goto error;
1916 Py_DECREF(outer);
1917 outer = tmp;
1918 }
Mark Dickinson76464492012-10-25 10:46:28 +01001919 Py_DECREF(inner);
1920 return outer;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001921
1922 error:
1923 Py_DECREF(outer);
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001924 Py_DECREF(inner);
Mark Dickinson76464492012-10-25 10:46:28 +01001925 return NULL;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001926}
1927
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001928
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001929/* Lookup table for small factorial values */
1930
1931static const unsigned long SmallFactorials[] = {
1932 1, 1, 2, 6, 24, 120, 720, 5040, 40320,
1933 362880, 3628800, 39916800, 479001600,
1934#if SIZEOF_LONG >= 8
1935 6227020800, 87178291200, 1307674368000,
1936 20922789888000, 355687428096000, 6402373705728000,
1937 121645100408832000, 2432902008176640000
1938#endif
1939};
1940
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001941/*[clinic input]
1942math.factorial
1943
1944 x as arg: object
1945 /
1946
1947Find x!.
1948
1949Raise a ValueError if x is negative or non-integral.
1950[clinic start generated code]*/
1951
Barry Warsaw8b43b191996-12-09 22:32:36 +00001952static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001953math_factorial(PyObject *module, PyObject *arg)
1954/*[clinic end generated code: output=6686f26fae00e9ca input=6d1c8105c0d91fb4]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001955{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03001956 long x, two_valuation;
Mark Dickinson5990d282014-04-10 09:29:39 -04001957 int overflow;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03001958 PyObject *result, *odd_part, *pyint_form;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 if (PyFloat_Check(arg)) {
Serhiy Storchaka231aad32019-06-17 16:57:27 +03001961 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1962 "Using factorial() with floats is deprecated",
1963 1) < 0)
1964 {
1965 return NULL;
1966 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 PyObject *lx;
1968 double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
1969 if (!(Py_IS_FINITE(dx) && dx == floor(dx))) {
1970 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001971 "factorial() only accepts integral values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 return NULL;
1973 }
1974 lx = PyLong_FromDouble(dx);
1975 if (lx == NULL)
1976 return NULL;
Mark Dickinson5990d282014-04-10 09:29:39 -04001977 x = PyLong_AsLongAndOverflow(lx, &overflow);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 Py_DECREF(lx);
1979 }
Pablo Galindoe9ba3702018-09-03 22:20:06 +01001980 else {
1981 pyint_form = PyNumber_Index(arg);
1982 if (pyint_form == NULL) {
1983 return NULL;
1984 }
1985 x = PyLong_AsLongAndOverflow(pyint_form, &overflow);
1986 Py_DECREF(pyint_form);
1987 }
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001988
Mark Dickinson5990d282014-04-10 09:29:39 -04001989 if (x == -1 && PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 return NULL;
Mark Dickinson5990d282014-04-10 09:29:39 -04001991 }
1992 else if (overflow == 1) {
1993 PyErr_Format(PyExc_OverflowError,
1994 "factorial() argument should not exceed %ld",
1995 LONG_MAX);
1996 return NULL;
1997 }
1998 else if (overflow == -1 || x < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002000 "factorial() not defined for negative values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 return NULL;
2002 }
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002003
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002004 /* use lookup table if x is small */
Victor Stinner63941882011-09-29 00:42:28 +02002005 if (x < (long)Py_ARRAY_LENGTH(SmallFactorials))
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002006 return PyLong_FromUnsignedLong(SmallFactorials[x]);
2007
2008 /* else express in the form odd_part * 2**two_valuation, and compute as
2009 odd_part << two_valuation. */
2010 odd_part = factorial_odd_part(x);
2011 if (odd_part == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03002013 two_valuation = x - count_set_bits(x);
2014 result = _PyLong_Lshift(odd_part, two_valuation);
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002015 Py_DECREF(odd_part);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 return result;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002017}
2018
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002019
2020/*[clinic input]
2021math.trunc
2022
2023 x: object
2024 /
2025
2026Truncates the Real x to the nearest Integral toward 0.
2027
2028Uses the __trunc__ magic method.
2029[clinic start generated code]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002030
2031static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002032math_trunc(PyObject *module, PyObject *x)
2033/*[clinic end generated code: output=34b9697b707e1031 input=2168b34e0a09134d]*/
Christian Heimes400adb02008-02-01 08:12:03 +00002034{
Benjamin Petersonce798522012-01-22 11:24:29 -05002035 _Py_IDENTIFIER(__trunc__);
Benjamin Petersonb0125892010-07-02 13:35:17 +00002036 PyObject *trunc, *result;
Christian Heimes400adb02008-02-01 08:12:03 +00002037
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02002038 if (PyFloat_CheckExact(x)) {
2039 return PyFloat_Type.tp_as_number->nb_int(x);
2040 }
2041
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002042 if (Py_TYPE(x)->tp_dict == NULL) {
2043 if (PyType_Ready(Py_TYPE(x)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 return NULL;
2045 }
Christian Heimes400adb02008-02-01 08:12:03 +00002046
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002047 trunc = _PyObject_LookupSpecial(x, &PyId___trunc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 if (trunc == NULL) {
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00002049 if (!PyErr_Occurred())
2050 PyErr_Format(PyExc_TypeError,
2051 "type %.100s doesn't define __trunc__ method",
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002052 Py_TYPE(x)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 return NULL;
2054 }
Victor Stinnerf17c3de2016-12-06 18:46:19 +01002055 result = _PyObject_CallNoArg(trunc);
Benjamin Petersonb0125892010-07-02 13:35:17 +00002056 Py_DECREF(trunc);
2057 return result;
Christian Heimes400adb02008-02-01 08:12:03 +00002058}
2059
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002060
2061/*[clinic input]
2062math.frexp
2063
2064 x: double
2065 /
2066
2067Return the mantissa and exponent of x, as pair (m, e).
2068
2069m is a float and e is an int, such that x = m * 2.**e.
2070If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.
2071[clinic start generated code]*/
Christian Heimes400adb02008-02-01 08:12:03 +00002072
2073static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002074math_frexp_impl(PyObject *module, double x)
2075/*[clinic end generated code: output=03e30d252a15ad4a input=96251c9e208bc6e9]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00002076{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 /* deal with special cases directly, to sidestep platform
2079 differences */
2080 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
2081 i = 0;
2082 }
2083 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 x = frexp(x, &i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 }
2086 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +00002087}
2088
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002089
2090/*[clinic input]
2091math.ldexp
2092
2093 x: double
2094 i: object
2095 /
2096
2097Return x * (2**i).
2098
2099This is essentially the inverse of frexp().
2100[clinic start generated code]*/
Guido van Rossumc6e22901998-12-04 19:26:43 +00002101
Barry Warsaw8b43b191996-12-09 22:32:36 +00002102static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002103math_ldexp_impl(PyObject *module, double x, PyObject *i)
2104/*[clinic end generated code: output=b6892f3c2df9cc6a input=17d5970c1a40a8c1]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00002105{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002106 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 long exp;
2108 int overflow;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00002109
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002110 if (PyLong_Check(i)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 /* on overflow, replace exponent with either LONG_MAX
2112 or LONG_MIN, depending on the sign. */
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002113 exp = PyLong_AsLongAndOverflow(i, &overflow);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 if (exp == -1 && PyErr_Occurred())
2115 return NULL;
2116 if (overflow)
2117 exp = overflow < 0 ? LONG_MIN : LONG_MAX;
2118 }
2119 else {
2120 PyErr_SetString(PyExc_TypeError,
Serhiy Storchaka95949422013-08-27 19:40:23 +03002121 "Expected an int as second argument to ldexp.");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 return NULL;
2123 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00002124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 if (x == 0. || !Py_IS_FINITE(x)) {
2126 /* NaNs, zeros and infinities are returned unchanged */
2127 r = x;
2128 errno = 0;
2129 } else if (exp > INT_MAX) {
2130 /* overflow */
2131 r = copysign(Py_HUGE_VAL, x);
2132 errno = ERANGE;
2133 } else if (exp < INT_MIN) {
2134 /* underflow to +-0 */
2135 r = copysign(0., x);
2136 errno = 0;
2137 } else {
2138 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 r = ldexp(x, (int)exp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 if (Py_IS_INFINITY(r))
2141 errno = ERANGE;
2142 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00002143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 if (errno && is_error(r))
2145 return NULL;
2146 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +00002147}
2148
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002149
2150/*[clinic input]
2151math.modf
2152
2153 x: double
2154 /
2155
2156Return the fractional and integer parts of x.
2157
2158Both results carry the sign of x and are floats.
2159[clinic start generated code]*/
Guido van Rossumc6e22901998-12-04 19:26:43 +00002160
Barry Warsaw8b43b191996-12-09 22:32:36 +00002161static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002162math_modf_impl(PyObject *module, double x)
2163/*[clinic end generated code: output=90cee0260014c3c0 input=b4cfb6786afd9035]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00002164{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002165 double y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 /* some platforms don't do the right thing for NaNs and
2167 infinities, so we take care of special cases directly. */
2168 if (!Py_IS_FINITE(x)) {
2169 if (Py_IS_INFINITY(x))
2170 return Py_BuildValue("(dd)", copysign(0., x), x);
2171 else if (Py_IS_NAN(x))
2172 return Py_BuildValue("(dd)", x, x);
2173 }
Christian Heimesa342c012008-04-20 21:01:16 +00002174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 x = modf(x, &y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +00002178}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002179
Guido van Rossumc6e22901998-12-04 19:26:43 +00002180
Serhiy Storchaka95949422013-08-27 19:40:23 +03002181/* A decent logarithm is easy to compute even for huge ints, but libm can't
Tim Peters78526162001-09-05 00:53:45 +00002182 do that by itself -- loghelper can. func is log or log10, and name is
Serhiy Storchaka95949422013-08-27 19:40:23 +03002183 "log" or "log10". Note that overflow of the result isn't possible: an int
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002184 can contain no more than INT_MAX * SHIFT bits, so has value certainly less
2185 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 +00002186 small enough to fit in an IEEE single. log and log10 are even smaller.
Serhiy Storchaka95949422013-08-27 19:40:23 +03002187 However, intermediate overflow is possible for an int if the number of bits
2188 in that int is larger than PY_SSIZE_T_MAX. */
Tim Peters78526162001-09-05 00:53:45 +00002189
2190static PyObject*
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002191loghelper(PyObject* arg, double (*func)(double), const char *funcname)
Tim Peters78526162001-09-05 00:53:45 +00002192{
Serhiy Storchaka95949422013-08-27 19:40:23 +03002193 /* If it is int, do it ourselves. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 if (PyLong_Check(arg)) {
Mark Dickinsonc6037172010-09-29 19:06:36 +00002195 double x, result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 Py_ssize_t e;
Mark Dickinsonc6037172010-09-29 19:06:36 +00002197
2198 /* Negative or zero inputs give a ValueError. */
2199 if (Py_SIZE(arg) <= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 PyErr_SetString(PyExc_ValueError,
2201 "math domain error");
2202 return NULL;
2203 }
Mark Dickinsonfa41e602010-09-28 07:22:27 +00002204
Mark Dickinsonc6037172010-09-29 19:06:36 +00002205 x = PyLong_AsDouble(arg);
2206 if (x == -1.0 && PyErr_Occurred()) {
2207 if (!PyErr_ExceptionMatches(PyExc_OverflowError))
2208 return NULL;
2209 /* Here the conversion to double overflowed, but it's possible
2210 to compute the log anyway. Clear the exception and continue. */
2211 PyErr_Clear();
2212 x = _PyLong_Frexp((PyLongObject *)arg, &e);
2213 if (x == -1.0 && PyErr_Occurred())
2214 return NULL;
2215 /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */
2216 result = func(x) + func(2.0) * e;
2217 }
2218 else
2219 /* Successfully converted x to a double. */
2220 result = func(x);
2221 return PyFloat_FromDouble(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 }
Tim Peters78526162001-09-05 00:53:45 +00002223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 /* Else let libm handle it by itself. */
2225 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +00002226}
2227
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002228
2229/*[clinic input]
2230math.log
2231
2232 x: object
2233 [
2234 base: object(c_default="NULL") = math.e
2235 ]
2236 /
2237
2238Return the logarithm of x to the given base.
2239
2240If the base not specified, returns the natural logarithm (base e) of x.
2241[clinic start generated code]*/
2242
Tim Peters78526162001-09-05 00:53:45 +00002243static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002244math_log_impl(PyObject *module, PyObject *x, int group_right_1,
2245 PyObject *base)
2246/*[clinic end generated code: output=7b5a39e526b73fc9 input=0f62d5726cbfebbd]*/
Tim Peters78526162001-09-05 00:53:45 +00002247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 PyObject *num, *den;
2249 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +00002250
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002251 num = loghelper(x, m_log, "log");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 if (num == NULL || base == NULL)
2253 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +00002254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 den = loghelper(base, m_log, "log");
2256 if (den == NULL) {
2257 Py_DECREF(num);
2258 return NULL;
2259 }
Raymond Hettinger866964c2002-12-14 19:51:34 +00002260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 ans = PyNumber_TrueDivide(num, den);
2262 Py_DECREF(num);
2263 Py_DECREF(den);
2264 return ans;
Tim Peters78526162001-09-05 00:53:45 +00002265}
2266
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002267
2268/*[clinic input]
2269math.log2
2270
2271 x: object
2272 /
2273
2274Return the base 2 logarithm of x.
2275[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002276
2277static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002278math_log2(PyObject *module, PyObject *x)
2279/*[clinic end generated code: output=5425899a4d5d6acb input=08321262bae4f39b]*/
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02002280{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002281 return loghelper(x, m_log2, "log2");
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02002282}
2283
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002284
2285/*[clinic input]
2286math.log10
2287
2288 x: object
2289 /
2290
2291Return the base 10 logarithm of x.
2292[clinic start generated code]*/
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02002293
2294static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002295math_log10(PyObject *module, PyObject *x)
2296/*[clinic end generated code: output=be72a64617df9c6f input=b2469d02c6469e53]*/
Tim Peters78526162001-09-05 00:53:45 +00002297{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002298 return loghelper(x, m_log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +00002299}
2300
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002301
2302/*[clinic input]
2303math.fmod
2304
2305 x: double
2306 y: double
2307 /
2308
2309Return fmod(x, y), according to platform C.
2310
2311x % y may differ.
2312[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002313
Christian Heimes53876d92008-04-19 00:31:39 +00002314static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002315math_fmod_impl(PyObject *module, double x, double y)
2316/*[clinic end generated code: output=7559d794343a27b5 input=4f84caa8cfc26a03]*/
Christian Heimes53876d92008-04-19 00:31:39 +00002317{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002318 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 /* fmod(x, +/-Inf) returns x for finite x. */
2320 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
2321 return PyFloat_FromDouble(x);
2322 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 r = fmod(x, y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 if (Py_IS_NAN(r)) {
2325 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
2326 errno = EDOM;
2327 else
2328 errno = 0;
2329 }
2330 if (errno && is_error(r))
2331 return NULL;
2332 else
2333 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00002334}
2335
Raymond Hettinger13990742018-08-11 11:26:36 -07002336/*
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002337Given an *n* length *vec* of values and a value *max*, compute:
Raymond Hettinger13990742018-08-11 11:26:36 -07002338
Raymond Hettingerc630e102018-08-11 18:39:05 -07002339 max * sqrt(sum((x / max) ** 2 for x in vec))
Raymond Hettinger13990742018-08-11 11:26:36 -07002340
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002341The value of the *max* variable must be non-negative and
Raymond Hettinger216aaaa2018-11-09 01:06:02 -08002342equal to the absolute value of the largest magnitude
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002343entry in the vector. If n==0, then *max* should be 0.0.
2344If an infinity is present in the vec, *max* should be INF.
Raymond Hettingerc630e102018-08-11 18:39:05 -07002345
2346The *found_nan* variable indicates whether some member of
2347the *vec* is a NaN.
Raymond Hettinger21786f52018-08-28 22:47:24 -07002348
2349To improve accuracy and to increase the number of cases where
2350vector_norm() is commutative, we use a variant of Neumaier
2351summation specialized to exploit that we always know that
2352|csum| >= |x|.
2353
2354The *csum* variable tracks the cumulative sum and *frac* tracks
2355the cumulative fractional errors at each step. Since this
2356variant assumes that |csum| >= |x| at each step, we establish
2357the precondition by starting the accumulation from 1.0 which
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002358represents the largest possible value of (x/max)**2.
2359
2360After the loop is finished, the initial 1.0 is subtracted out
2361for a net zero effect on the final sum. Since *csum* will be
2362greater than 1.0, the subtraction of 1.0 will not cause
2363fractional digits to be dropped from *csum*.
Raymond Hettinger21786f52018-08-28 22:47:24 -07002364
Raymond Hettinger13990742018-08-11 11:26:36 -07002365*/
2366
2367static inline double
Raymond Hettingerc630e102018-08-11 18:39:05 -07002368vector_norm(Py_ssize_t n, double *vec, double max, int found_nan)
Raymond Hettinger13990742018-08-11 11:26:36 -07002369{
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002370 double x, csum = 1.0, oldcsum, frac = 0.0;
Raymond Hettinger13990742018-08-11 11:26:36 -07002371 Py_ssize_t i;
2372
Raymond Hettingerc630e102018-08-11 18:39:05 -07002373 if (Py_IS_INFINITY(max)) {
2374 return max;
2375 }
2376 if (found_nan) {
2377 return Py_NAN;
2378 }
Raymond Hettingerf3267142018-09-02 13:34:21 -07002379 if (max == 0.0 || n <= 1) {
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002380 return max;
Raymond Hettinger13990742018-08-11 11:26:36 -07002381 }
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002382 for (i=0 ; i < n ; i++) {
Raymond Hettinger13990742018-08-11 11:26:36 -07002383 x = vec[i];
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002384 assert(Py_IS_FINITE(x) && fabs(x) <= max);
Raymond Hettinger13990742018-08-11 11:26:36 -07002385 x /= max;
Raymond Hettinger21786f52018-08-28 22:47:24 -07002386 x = x*x;
Raymond Hettinger13990742018-08-11 11:26:36 -07002387 oldcsum = csum;
2388 csum += x;
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002389 assert(csum >= x);
Raymond Hettinger21786f52018-08-28 22:47:24 -07002390 frac += (oldcsum - csum) + x;
Raymond Hettinger13990742018-08-11 11:26:36 -07002391 }
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002392 return max * sqrt(csum - 1.0 + frac);
Raymond Hettinger13990742018-08-11 11:26:36 -07002393}
2394
Raymond Hettingerc630e102018-08-11 18:39:05 -07002395#define NUM_STACK_ELEMS 16
2396
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002397/*[clinic input]
2398math.dist
2399
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002400 p: object
2401 q: object
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002402 /
2403
2404Return the Euclidean distance between two points p and q.
2405
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002406The points should be specified as sequences (or iterables) of
2407coordinates. Both inputs must have the same dimension.
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002408
2409Roughly equivalent to:
2410 sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
2411[clinic start generated code]*/
2412
2413static PyObject *
2414math_dist_impl(PyObject *module, PyObject *p, PyObject *q)
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002415/*[clinic end generated code: output=56bd9538d06bbcfe input=74e85e1b6092e68e]*/
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002416{
2417 PyObject *item;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002418 double max = 0.0;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002419 double x, px, qx, result;
2420 Py_ssize_t i, m, n;
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002421 int found_nan = 0, p_allocated = 0, q_allocated = 0;
Raymond Hettingerc630e102018-08-11 18:39:05 -07002422 double diffs_on_stack[NUM_STACK_ELEMS];
2423 double *diffs = diffs_on_stack;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002424
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002425 if (!PyTuple_Check(p)) {
2426 p = PySequence_Tuple(p);
2427 if (p == NULL) {
2428 return NULL;
2429 }
2430 p_allocated = 1;
2431 }
2432 if (!PyTuple_Check(q)) {
2433 q = PySequence_Tuple(q);
2434 if (q == NULL) {
2435 if (p_allocated) {
2436 Py_DECREF(p);
2437 }
2438 return NULL;
2439 }
2440 q_allocated = 1;
2441 }
2442
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002443 m = PyTuple_GET_SIZE(p);
2444 n = PyTuple_GET_SIZE(q);
2445 if (m != n) {
2446 PyErr_SetString(PyExc_ValueError,
2447 "both points must have the same number of dimensions");
2448 return NULL;
2449
2450 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002451 if (n > NUM_STACK_ELEMS) {
2452 diffs = (double *) PyObject_Malloc(n * sizeof(double));
2453 if (diffs == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07002454 return PyErr_NoMemory();
Raymond Hettingerc630e102018-08-11 18:39:05 -07002455 }
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002456 }
2457 for (i=0 ; i<n ; i++) {
2458 item = PyTuple_GET_ITEM(p, i);
Raymond Hettingercfd735e2019-01-29 20:39:53 -08002459 ASSIGN_DOUBLE(px, item, error_exit);
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002460 item = PyTuple_GET_ITEM(q, i);
Raymond Hettingercfd735e2019-01-29 20:39:53 -08002461 ASSIGN_DOUBLE(qx, item, error_exit);
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002462 x = fabs(px - qx);
2463 diffs[i] = x;
2464 found_nan |= Py_IS_NAN(x);
2465 if (x > max) {
2466 max = x;
2467 }
2468 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002469 result = vector_norm(n, diffs, max, found_nan);
2470 if (diffs != diffs_on_stack) {
2471 PyObject_Free(diffs);
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002472 }
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002473 if (p_allocated) {
2474 Py_DECREF(p);
2475 }
2476 if (q_allocated) {
2477 Py_DECREF(q);
2478 }
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002479 return PyFloat_FromDouble(result);
Raymond Hettingerc630e102018-08-11 18:39:05 -07002480
2481 error_exit:
2482 if (diffs != diffs_on_stack) {
2483 PyObject_Free(diffs);
2484 }
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002485 if (p_allocated) {
2486 Py_DECREF(p);
2487 }
2488 if (q_allocated) {
2489 Py_DECREF(q);
2490 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002491 return NULL;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002492}
2493
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002494/* AC: cannot convert yet, waiting for *args support */
Christian Heimes53876d92008-04-19 00:31:39 +00002495static PyObject *
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002496math_hypot(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Christian Heimes53876d92008-04-19 00:31:39 +00002497{
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002498 Py_ssize_t i;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002499 PyObject *item;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002500 double max = 0.0;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002501 double x, result;
2502 int found_nan = 0;
Raymond Hettingerc630e102018-08-11 18:39:05 -07002503 double coord_on_stack[NUM_STACK_ELEMS];
2504 double *coordinates = coord_on_stack;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002505
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002506 if (nargs > NUM_STACK_ELEMS) {
2507 coordinates = (double *) PyObject_Malloc(nargs * sizeof(double));
Zackery Spytz4c49da02018-12-07 03:11:30 -07002508 if (coordinates == NULL) {
2509 return PyErr_NoMemory();
2510 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002511 }
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002512 for (i = 0; i < nargs; i++) {
2513 item = args[i];
Raymond Hettingercfd735e2019-01-29 20:39:53 -08002514 ASSIGN_DOUBLE(x, item, error_exit);
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002515 x = fabs(x);
2516 coordinates[i] = x;
2517 found_nan |= Py_IS_NAN(x);
2518 if (x > max) {
2519 max = x;
2520 }
2521 }
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002522 result = vector_norm(nargs, coordinates, max, found_nan);
Raymond Hettingerc630e102018-08-11 18:39:05 -07002523 if (coordinates != coord_on_stack) {
2524 PyObject_Free(coordinates);
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002525 }
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002526 return PyFloat_FromDouble(result);
Raymond Hettingerc630e102018-08-11 18:39:05 -07002527
2528 error_exit:
2529 if (coordinates != coord_on_stack) {
2530 PyObject_Free(coordinates);
2531 }
2532 return NULL;
Christian Heimes53876d92008-04-19 00:31:39 +00002533}
2534
Raymond Hettingerc630e102018-08-11 18:39:05 -07002535#undef NUM_STACK_ELEMS
2536
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002537PyDoc_STRVAR(math_hypot_doc,
2538 "hypot(*coordinates) -> value\n\n\
2539Multidimensional Euclidean distance from the origin to a point.\n\
2540\n\
2541Roughly equivalent to:\n\
2542 sqrt(sum(x**2 for x in coordinates))\n\
2543\n\
2544For a two dimensional point (x, y), gives the hypotenuse\n\
2545using the Pythagorean theorem: sqrt(x*x + y*y).\n\
2546\n\
2547For example, the hypotenuse of a 3/4/5 right triangle is:\n\
2548\n\
2549 >>> hypot(3.0, 4.0)\n\
2550 5.0\n\
2551");
Christian Heimes53876d92008-04-19 00:31:39 +00002552
2553/* pow can't use math_2, but needs its own wrapper: the problem is
2554 that an infinite result can arise either as a result of overflow
2555 (in which case OverflowError should be raised) or as a result of
2556 e.g. 0.**-5. (for which ValueError needs to be raised.)
2557*/
2558
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002559/*[clinic input]
2560math.pow
Christian Heimes53876d92008-04-19 00:31:39 +00002561
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002562 x: double
2563 y: double
2564 /
2565
2566Return x**y (x to the power of y).
2567[clinic start generated code]*/
2568
2569static PyObject *
2570math_pow_impl(PyObject *module, double x, double y)
2571/*[clinic end generated code: output=fff93e65abccd6b0 input=c26f1f6075088bfd]*/
2572{
2573 double r;
2574 int odd_y;
Christian Heimesa342c012008-04-20 21:01:16 +00002575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002576 /* deal directly with IEEE specials, to cope with problems on various
2577 platforms whose semantics don't exactly match C99 */
2578 r = 0.; /* silence compiler warning */
2579 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
2580 errno = 0;
2581 if (Py_IS_NAN(x))
2582 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
2583 else if (Py_IS_NAN(y))
2584 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
2585 else if (Py_IS_INFINITY(x)) {
2586 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
2587 if (y > 0.)
2588 r = odd_y ? x : fabs(x);
2589 else if (y == 0.)
2590 r = 1.;
2591 else /* y < 0. */
2592 r = odd_y ? copysign(0., x) : 0.;
2593 }
2594 else if (Py_IS_INFINITY(y)) {
2595 if (fabs(x) == 1.0)
2596 r = 1.;
2597 else if (y > 0. && fabs(x) > 1.0)
2598 r = y;
2599 else if (y < 0. && fabs(x) < 1.0) {
2600 r = -y; /* result is +inf */
2601 if (x == 0.) /* 0**-inf: divide-by-zero */
2602 errno = EDOM;
2603 }
2604 else
2605 r = 0.;
2606 }
2607 }
2608 else {
2609 /* let libm handle finite**finite */
2610 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002611 r = pow(x, y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 /* a NaN result should arise only from (-ve)**(finite
2613 non-integer); in this case we want to raise ValueError. */
2614 if (!Py_IS_FINITE(r)) {
2615 if (Py_IS_NAN(r)) {
2616 errno = EDOM;
2617 }
2618 /*
2619 an infinite result here arises either from:
2620 (A) (+/-0.)**negative (-> divide-by-zero)
2621 (B) overflow of x**y with x and y finite
2622 */
2623 else if (Py_IS_INFINITY(r)) {
2624 if (x == 0.)
2625 errno = EDOM;
2626 else
2627 errno = ERANGE;
2628 }
2629 }
2630 }
Christian Heimes53876d92008-04-19 00:31:39 +00002631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 if (errno && is_error(r))
2633 return NULL;
2634 else
2635 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00002636}
2637
Christian Heimes53876d92008-04-19 00:31:39 +00002638
Christian Heimes072c0f12008-01-03 23:01:04 +00002639static const double degToRad = Py_MATH_PI / 180.0;
2640static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002641
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002642/*[clinic input]
2643math.degrees
2644
2645 x: double
2646 /
2647
2648Convert angle x from radians to degrees.
2649[clinic start generated code]*/
2650
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002651static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002652math_degrees_impl(PyObject *module, double x)
2653/*[clinic end generated code: output=7fea78b294acd12f input=81e016555d6e3660]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002654{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002656}
2657
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002658
2659/*[clinic input]
2660math.radians
2661
2662 x: double
2663 /
2664
2665Convert angle x from degrees to radians.
2666[clinic start generated code]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002667
2668static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002669math_radians_impl(PyObject *module, double x)
2670/*[clinic end generated code: output=34daa47caf9b1590 input=91626fc489fe3d63]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002671{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 return PyFloat_FromDouble(x * degToRad);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002673}
2674
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002675
2676/*[clinic input]
2677math.isfinite
2678
2679 x: double
2680 /
2681
2682Return True if x is neither an infinity nor a NaN, and False otherwise.
2683[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002684
Christian Heimes072c0f12008-01-03 23:01:04 +00002685static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002686math_isfinite_impl(PyObject *module, double x)
2687/*[clinic end generated code: output=8ba1f396440c9901 input=46967d254812e54a]*/
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002688{
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002689 return PyBool_FromLong((long)Py_IS_FINITE(x));
2690}
2691
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002692
2693/*[clinic input]
2694math.isnan
2695
2696 x: double
2697 /
2698
2699Return True if x is a NaN (not a number), and False otherwise.
2700[clinic start generated code]*/
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002701
2702static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002703math_isnan_impl(PyObject *module, double x)
2704/*[clinic end generated code: output=f537b4d6df878c3e input=935891e66083f46a]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002705{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002706 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00002707}
2708
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002709
2710/*[clinic input]
2711math.isinf
2712
2713 x: double
2714 /
2715
2716Return True if x is a positive or negative infinity, and False otherwise.
2717[clinic start generated code]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002718
2719static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002720math_isinf_impl(PyObject *module, double x)
2721/*[clinic end generated code: output=9f00cbec4de7b06b input=32630e4212cf961f]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002722{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00002724}
2725
Christian Heimes072c0f12008-01-03 23:01:04 +00002726
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002727/*[clinic input]
2728math.isclose -> bool
2729
2730 a: double
2731 b: double
2732 *
2733 rel_tol: double = 1e-09
2734 maximum difference for being considered "close", relative to the
2735 magnitude of the input values
2736 abs_tol: double = 0.0
2737 maximum difference for being considered "close", regardless of the
2738 magnitude of the input values
2739
2740Determine whether two floating point numbers are close in value.
2741
2742Return True if a is close in value to b, and False otherwise.
2743
2744For the values to be considered close, the difference between them
2745must be smaller than at least one of the tolerances.
2746
2747-inf, inf and NaN behave similarly to the IEEE 754 Standard. That
2748is, NaN is not close to anything, even itself. inf and -inf are
2749only close to themselves.
2750[clinic start generated code]*/
2751
2752static int
2753math_isclose_impl(PyObject *module, double a, double b, double rel_tol,
2754 double abs_tol)
2755/*[clinic end generated code: output=b73070207511952d input=f28671871ea5bfba]*/
Tal Einatd5519ed2015-05-31 22:05:00 +03002756{
Tal Einatd5519ed2015-05-31 22:05:00 +03002757 double diff = 0.0;
Tal Einatd5519ed2015-05-31 22:05:00 +03002758
2759 /* sanity check on the inputs */
2760 if (rel_tol < 0.0 || abs_tol < 0.0 ) {
2761 PyErr_SetString(PyExc_ValueError,
2762 "tolerances must be non-negative");
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002763 return -1;
Tal Einatd5519ed2015-05-31 22:05:00 +03002764 }
2765
2766 if ( a == b ) {
2767 /* short circuit exact equality -- needed to catch two infinities of
2768 the same sign. And perhaps speeds things up a bit sometimes.
2769 */
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002770 return 1;
Tal Einatd5519ed2015-05-31 22:05:00 +03002771 }
2772
2773 /* This catches the case of two infinities of opposite sign, or
2774 one infinity and one finite number. Two infinities of opposite
2775 sign would otherwise have an infinite relative tolerance.
2776 Two infinities of the same sign are caught by the equality check
2777 above.
2778 */
2779
2780 if (Py_IS_INFINITY(a) || Py_IS_INFINITY(b)) {
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002781 return 0;
Tal Einatd5519ed2015-05-31 22:05:00 +03002782 }
2783
2784 /* now do the regular computation
2785 this is essentially the "weak" test from the Boost library
2786 */
2787
2788 diff = fabs(b - a);
2789
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002790 return (((diff <= fabs(rel_tol * b)) ||
2791 (diff <= fabs(rel_tol * a))) ||
2792 (diff <= abs_tol));
Tal Einatd5519ed2015-05-31 22:05:00 +03002793}
2794
Pablo Galindo04114112019-03-09 19:18:08 +00002795static inline int
2796_check_long_mult_overflow(long a, long b) {
2797
2798 /* From Python2's int_mul code:
2799
2800 Integer overflow checking for * is painful: Python tried a couple ways, but
2801 they didn't work on all platforms, or failed in endcases (a product of
2802 -sys.maxint-1 has been a particular pain).
2803
2804 Here's another way:
2805
2806 The native long product x*y is either exactly right or *way* off, being
2807 just the last n bits of the true product, where n is the number of bits
2808 in a long (the delivered product is the true product plus i*2**n for
2809 some integer i).
2810
2811 The native double product (double)x * (double)y is subject to three
2812 rounding errors: on a sizeof(long)==8 box, each cast to double can lose
2813 info, and even on a sizeof(long)==4 box, the multiplication can lose info.
2814 But, unlike the native long product, it's not in *range* trouble: even
2815 if sizeof(long)==32 (256-bit longs), the product easily fits in the
2816 dynamic range of a double. So the leading 50 (or so) bits of the double
2817 product are correct.
2818
2819 We check these two ways against each other, and declare victory if they're
2820 approximately the same. Else, because the native long product is the only
2821 one that can lose catastrophic amounts of information, it's the native long
2822 product that must have overflowed.
2823
2824 */
2825
2826 long longprod = (long)((unsigned long)a * b);
2827 double doubleprod = (double)a * (double)b;
2828 double doubled_longprod = (double)longprod;
2829
2830 if (doubled_longprod == doubleprod) {
2831 return 0;
2832 }
2833
2834 const double diff = doubled_longprod - doubleprod;
2835 const double absdiff = diff >= 0.0 ? diff : -diff;
2836 const double absprod = doubleprod >= 0.0 ? doubleprod : -doubleprod;
2837
2838 if (32.0 * absdiff <= absprod) {
2839 return 0;
2840 }
2841
2842 return 1;
2843}
Tal Einatd5519ed2015-05-31 22:05:00 +03002844
Pablo Galindobc098512019-02-07 07:04:02 +00002845/*[clinic input]
2846math.prod
2847
2848 iterable: object
2849 /
2850 *
2851 start: object(c_default="NULL") = 1
2852
2853Calculate the product of all the elements in the input iterable.
2854
2855The default start value for the product is 1.
2856
2857When the iterable is empty, return the start value. This function is
2858intended specifically for use with numeric values and may reject
2859non-numeric types.
2860[clinic start generated code]*/
2861
2862static PyObject *
2863math_prod_impl(PyObject *module, PyObject *iterable, PyObject *start)
2864/*[clinic end generated code: output=36153bedac74a198 input=4c5ab0682782ed54]*/
2865{
2866 PyObject *result = start;
2867 PyObject *temp, *item, *iter;
2868
2869 iter = PyObject_GetIter(iterable);
2870 if (iter == NULL) {
2871 return NULL;
2872 }
2873
2874 if (result == NULL) {
2875 result = PyLong_FromLong(1);
2876 if (result == NULL) {
2877 Py_DECREF(iter);
2878 return NULL;
2879 }
2880 } else {
2881 Py_INCREF(result);
2882 }
2883#ifndef SLOW_PROD
2884 /* Fast paths for integers keeping temporary products in C.
2885 * Assumes all inputs are the same type.
2886 * If the assumption fails, default to use PyObjects instead.
2887 */
2888 if (PyLong_CheckExact(result)) {
2889 int overflow;
2890 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
2891 /* If this already overflowed, don't even enter the loop. */
2892 if (overflow == 0) {
2893 Py_DECREF(result);
2894 result = NULL;
2895 }
2896 /* Loop over all the items in the iterable until we finish, we overflow
2897 * or we found a non integer element */
2898 while(result == NULL) {
2899 item = PyIter_Next(iter);
2900 if (item == NULL) {
2901 Py_DECREF(iter);
2902 if (PyErr_Occurred()) {
2903 return NULL;
2904 }
2905 return PyLong_FromLong(i_result);
2906 }
2907 if (PyLong_CheckExact(item)) {
2908 long b = PyLong_AsLongAndOverflow(item, &overflow);
Pablo Galindo04114112019-03-09 19:18:08 +00002909 if (overflow == 0 && !_check_long_mult_overflow(i_result, b)) {
2910 long x = i_result * b;
Pablo Galindobc098512019-02-07 07:04:02 +00002911 i_result = x;
2912 Py_DECREF(item);
2913 continue;
2914 }
2915 }
2916 /* Either overflowed or is not an int.
2917 * Restore real objects and process normally */
2918 result = PyLong_FromLong(i_result);
2919 if (result == NULL) {
2920 Py_DECREF(item);
2921 Py_DECREF(iter);
2922 return NULL;
2923 }
2924 temp = PyNumber_Multiply(result, item);
2925 Py_DECREF(result);
2926 Py_DECREF(item);
2927 result = temp;
2928 if (result == NULL) {
2929 Py_DECREF(iter);
2930 return NULL;
2931 }
2932 }
2933 }
2934
2935 /* Fast paths for floats keeping temporary products in C.
2936 * Assumes all inputs are the same type.
2937 * If the assumption fails, default to use PyObjects instead.
2938 */
2939 if (PyFloat_CheckExact(result)) {
2940 double f_result = PyFloat_AS_DOUBLE(result);
2941 Py_DECREF(result);
2942 result = NULL;
2943 while(result == NULL) {
2944 item = PyIter_Next(iter);
2945 if (item == NULL) {
2946 Py_DECREF(iter);
2947 if (PyErr_Occurred()) {
2948 return NULL;
2949 }
2950 return PyFloat_FromDouble(f_result);
2951 }
2952 if (PyFloat_CheckExact(item)) {
2953 f_result *= PyFloat_AS_DOUBLE(item);
2954 Py_DECREF(item);
2955 continue;
2956 }
2957 if (PyLong_CheckExact(item)) {
2958 long value;
2959 int overflow;
2960 value = PyLong_AsLongAndOverflow(item, &overflow);
2961 if (!overflow) {
2962 f_result *= (double)value;
2963 Py_DECREF(item);
2964 continue;
2965 }
2966 }
2967 result = PyFloat_FromDouble(f_result);
2968 if (result == NULL) {
2969 Py_DECREF(item);
2970 Py_DECREF(iter);
2971 return NULL;
2972 }
2973 temp = PyNumber_Multiply(result, item);
2974 Py_DECREF(result);
2975 Py_DECREF(item);
2976 result = temp;
2977 if (result == NULL) {
2978 Py_DECREF(iter);
2979 return NULL;
2980 }
2981 }
2982 }
2983#endif
2984 /* Consume rest of the iterable (if any) that could not be handled
2985 * by specialized functions above.*/
2986 for(;;) {
2987 item = PyIter_Next(iter);
2988 if (item == NULL) {
2989 /* error, or end-of-sequence */
2990 if (PyErr_Occurred()) {
2991 Py_DECREF(result);
2992 result = NULL;
2993 }
2994 break;
2995 }
2996 temp = PyNumber_Multiply(result, item);
2997 Py_DECREF(result);
2998 Py_DECREF(item);
2999 result = temp;
3000 if (result == NULL)
3001 break;
3002 }
3003 Py_DECREF(iter);
3004 return result;
3005}
3006
3007
Yash Aggarwal4a686502019-06-01 12:51:27 +05303008/*[clinic input]
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003009math.perm
3010
3011 n: object
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003012 k: object = None
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003013 /
3014
3015Number of ways to choose k items from n items without repetition and with order.
3016
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003017Evaluates to n! / (n - k)! when k <= n and evaluates
3018to zero when k > n.
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003019
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003020If k is not specified or is None, then k defaults to n
3021and the function returns n!.
3022
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003023Raises TypeError if either of the arguments are not integers.
3024Raises ValueError if either of the arguments are negative.
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003025[clinic start generated code]*/
3026
3027static PyObject *
3028math_perm_impl(PyObject *module, PyObject *n, PyObject *k)
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003029/*[clinic end generated code: output=e021a25469653e23 input=5311c5a00f359b53]*/
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003030{
3031 PyObject *result = NULL, *factor = NULL;
3032 int overflow, cmp;
3033 long long i, factors;
3034
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003035 if (k == Py_None) {
3036 return math_factorial(module, n);
3037 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003038 n = PyNumber_Index(n);
3039 if (n == NULL) {
3040 return NULL;
3041 }
3042 if (!PyLong_CheckExact(n)) {
3043 Py_SETREF(n, _PyLong_Copy((PyLongObject *)n));
3044 if (n == NULL) {
3045 return NULL;
3046 }
3047 }
3048 k = PyNumber_Index(k);
3049 if (k == NULL) {
3050 Py_DECREF(n);
3051 return NULL;
3052 }
3053 if (!PyLong_CheckExact(k)) {
3054 Py_SETREF(k, _PyLong_Copy((PyLongObject *)k));
3055 if (k == NULL) {
3056 Py_DECREF(n);
3057 return NULL;
3058 }
3059 }
3060
3061 if (Py_SIZE(n) < 0) {
3062 PyErr_SetString(PyExc_ValueError,
3063 "n must be a non-negative integer");
3064 goto error;
3065 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003066 if (Py_SIZE(k) < 0) {
3067 PyErr_SetString(PyExc_ValueError,
3068 "k must be a non-negative integer");
3069 goto error;
3070 }
3071
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003072 cmp = PyObject_RichCompareBool(n, k, Py_LT);
3073 if (cmp != 0) {
3074 if (cmp > 0) {
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003075 result = PyLong_FromLong(0);
3076 goto done;
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003077 }
3078 goto error;
3079 }
3080
3081 factors = PyLong_AsLongLongAndOverflow(k, &overflow);
3082 if (overflow > 0) {
3083 PyErr_Format(PyExc_OverflowError,
3084 "k must not exceed %lld",
3085 LLONG_MAX);
3086 goto error;
3087 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003088 else if (factors == -1) {
3089 /* k is nonnegative, so a return value of -1 can only indicate error */
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003090 goto error;
3091 }
3092
3093 if (factors == 0) {
3094 result = PyLong_FromLong(1);
3095 goto done;
3096 }
3097
3098 result = n;
3099 Py_INCREF(result);
3100 if (factors == 1) {
3101 goto done;
3102 }
3103
3104 factor = n;
3105 Py_INCREF(factor);
3106 for (i = 1; i < factors; ++i) {
3107 Py_SETREF(factor, PyNumber_Subtract(factor, _PyLong_One));
3108 if (factor == NULL) {
3109 goto error;
3110 }
3111 Py_SETREF(result, PyNumber_Multiply(result, factor));
3112 if (result == NULL) {
3113 goto error;
3114 }
3115 }
3116 Py_DECREF(factor);
3117
3118done:
3119 Py_DECREF(n);
3120 Py_DECREF(k);
3121 return result;
3122
3123error:
3124 Py_XDECREF(factor);
3125 Py_XDECREF(result);
3126 Py_DECREF(n);
3127 Py_DECREF(k);
3128 return NULL;
3129}
3130
3131
3132/*[clinic input]
Yash Aggarwal4a686502019-06-01 12:51:27 +05303133math.comb
3134
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003135 n: object
3136 k: object
3137 /
Yash Aggarwal4a686502019-06-01 12:51:27 +05303138
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003139Number of ways to choose k items from n items without repetition and without order.
Yash Aggarwal4a686502019-06-01 12:51:27 +05303140
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003141Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates
3142to zero when k > n.
Yash Aggarwal4a686502019-06-01 12:51:27 +05303143
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003144Also called the binomial coefficient because it is equivalent
3145to the coefficient of k-th term in polynomial expansion of the
3146expression (1 + x)**n.
3147
3148Raises TypeError if either of the arguments are not integers.
3149Raises ValueError if either of the arguments are negative.
Yash Aggarwal4a686502019-06-01 12:51:27 +05303150
3151[clinic start generated code]*/
3152
3153static PyObject *
3154math_comb_impl(PyObject *module, PyObject *n, PyObject *k)
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003155/*[clinic end generated code: output=bd2cec8d854f3493 input=9a05315af2518709]*/
Yash Aggarwal4a686502019-06-01 12:51:27 +05303156{
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003157 PyObject *result = NULL, *factor = NULL, *temp;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303158 int overflow, cmp;
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003159 long long i, factors;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303160
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003161 n = PyNumber_Index(n);
3162 if (n == NULL) {
3163 return NULL;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303164 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003165 if (!PyLong_CheckExact(n)) {
3166 Py_SETREF(n, _PyLong_Copy((PyLongObject *)n));
3167 if (n == NULL) {
3168 return NULL;
3169 }
3170 }
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003171 k = PyNumber_Index(k);
3172 if (k == NULL) {
3173 Py_DECREF(n);
3174 return NULL;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303175 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003176 if (!PyLong_CheckExact(k)) {
3177 Py_SETREF(k, _PyLong_Copy((PyLongObject *)k));
3178 if (k == NULL) {
3179 Py_DECREF(n);
3180 return NULL;
3181 }
3182 }
Yash Aggarwal4a686502019-06-01 12:51:27 +05303183
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003184 if (Py_SIZE(n) < 0) {
3185 PyErr_SetString(PyExc_ValueError,
3186 "n must be a non-negative integer");
3187 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303188 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003189 if (Py_SIZE(k) < 0) {
3190 PyErr_SetString(PyExc_ValueError,
3191 "k must be a non-negative integer");
3192 goto error;
3193 }
3194
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003195 /* k = min(k, n - k) */
3196 temp = PyNumber_Subtract(n, k);
3197 if (temp == NULL) {
3198 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303199 }
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003200 if (Py_SIZE(temp) < 0) {
3201 Py_DECREF(temp);
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003202 result = PyLong_FromLong(0);
3203 goto done;
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003204 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003205 cmp = PyObject_RichCompareBool(temp, k, Py_LT);
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003206 if (cmp > 0) {
3207 Py_SETREF(k, temp);
Yash Aggarwal4a686502019-06-01 12:51:27 +05303208 }
3209 else {
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003210 Py_DECREF(temp);
3211 if (cmp < 0) {
3212 goto error;
3213 }
Yash Aggarwal4a686502019-06-01 12:51:27 +05303214 }
3215
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003216 factors = PyLong_AsLongLongAndOverflow(k, &overflow);
3217 if (overflow > 0) {
Yash Aggarwal4a686502019-06-01 12:51:27 +05303218 PyErr_Format(PyExc_OverflowError,
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003219 "min(n - k, k) must not exceed %lld",
Yash Aggarwal4a686502019-06-01 12:51:27 +05303220 LLONG_MAX);
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003221 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303222 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003223 if (factors == -1) {
3224 /* k is nonnegative, so a return value of -1 can only indicate error */
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003225 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303226 }
3227
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003228 if (factors == 0) {
3229 result = PyLong_FromLong(1);
3230 goto done;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303231 }
3232
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003233 result = n;
3234 Py_INCREF(result);
3235 if (factors == 1) {
3236 goto done;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303237 }
3238
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003239 factor = n;
3240 Py_INCREF(factor);
3241 for (i = 1; i < factors; ++i) {
3242 Py_SETREF(factor, PyNumber_Subtract(factor, _PyLong_One));
3243 if (factor == NULL) {
3244 goto error;
3245 }
3246 Py_SETREF(result, PyNumber_Multiply(result, factor));
3247 if (result == NULL) {
3248 goto error;
3249 }
Yash Aggarwal4a686502019-06-01 12:51:27 +05303250
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003251 temp = PyLong_FromUnsignedLongLong((unsigned long long)i + 1);
3252 if (temp == NULL) {
3253 goto error;
3254 }
3255 Py_SETREF(result, PyNumber_FloorDivide(result, temp));
3256 Py_DECREF(temp);
3257 if (result == NULL) {
3258 goto error;
3259 }
3260 }
3261 Py_DECREF(factor);
Yash Aggarwal4a686502019-06-01 12:51:27 +05303262
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003263done:
3264 Py_DECREF(n);
3265 Py_DECREF(k);
3266 return result;
3267
3268error:
3269 Py_XDECREF(factor);
3270 Py_XDECREF(result);
3271 Py_DECREF(n);
3272 Py_DECREF(k);
Yash Aggarwal4a686502019-06-01 12:51:27 +05303273 return NULL;
3274}
3275
3276
Victor Stinner100fafc2020-01-12 02:15:42 +01003277/*[clinic input]
3278math.nextafter
3279
3280 x: double
3281 y: double
3282 /
3283
3284Return the next floating-point value after x towards y.
3285[clinic start generated code]*/
3286
3287static PyObject *
3288math_nextafter_impl(PyObject *module, double x, double y)
3289/*[clinic end generated code: output=750c8266c1c540ce input=02b2d50cd1d9f9b6]*/
3290{
Victor Stinner85ead4f2020-01-21 11:14:10 +01003291#if defined(_AIX)
3292 if (x == y) {
3293 /* On AIX 7.1, libm nextafter(-0.0, +0.0) returns -0.0.
3294 Bug fixed in bos.adt.libm 7.2.2.0 by APAR IV95512. */
3295 return PyFloat_FromDouble(y);
3296 }
3297#endif
3298 return PyFloat_FromDouble(nextafter(x, y));
Victor Stinner100fafc2020-01-12 02:15:42 +01003299}
3300
3301
Victor Stinner0b2ab212020-01-13 12:44:35 +01003302/*[clinic input]
3303math.ulp -> double
3304
3305 x: double
3306 /
3307
3308Return the value of the least significant bit of the float x.
3309[clinic start generated code]*/
3310
3311static double
3312math_ulp_impl(PyObject *module, double x)
3313/*[clinic end generated code: output=f5207867a9384dd4 input=31f9bfbbe373fcaa]*/
3314{
3315 if (Py_IS_NAN(x)) {
3316 return x;
3317 }
3318 x = fabs(x);
3319 if (Py_IS_INFINITY(x)) {
3320 return x;
3321 }
3322 double inf = m_inf();
3323 double x2 = nextafter(x, inf);
3324 if (Py_IS_INFINITY(x2)) {
3325 /* special case: x is the largest positive representable float */
3326 x2 = nextafter(x, -inf);
3327 return x - x2;
3328 }
3329 return x2 - x;
3330}
3331
3332
Barry Warsaw8b43b191996-12-09 22:32:36 +00003333static PyMethodDef math_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003334 {"acos", math_acos, METH_O, math_acos_doc},
3335 {"acosh", math_acosh, METH_O, math_acosh_doc},
3336 {"asin", math_asin, METH_O, math_asin_doc},
3337 {"asinh", math_asinh, METH_O, math_asinh_doc},
3338 {"atan", math_atan, METH_O, math_atan_doc},
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003339 {"atan2", (PyCFunction)(void(*)(void))math_atan2, METH_FASTCALL, math_atan2_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003340 {"atanh", math_atanh, METH_O, math_atanh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003341 MATH_CEIL_METHODDEF
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003342 {"copysign", (PyCFunction)(void(*)(void))math_copysign, METH_FASTCALL, math_copysign_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003343 {"cos", math_cos, METH_O, math_cos_doc},
3344 {"cosh", math_cosh, METH_O, math_cosh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003345 MATH_DEGREES_METHODDEF
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07003346 MATH_DIST_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003347 {"erf", math_erf, METH_O, math_erf_doc},
3348 {"erfc", math_erfc, METH_O, math_erfc_doc},
3349 {"exp", math_exp, METH_O, math_exp_doc},
3350 {"expm1", math_expm1, METH_O, math_expm1_doc},
3351 {"fabs", math_fabs, METH_O, math_fabs_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003352 MATH_FACTORIAL_METHODDEF
3353 MATH_FLOOR_METHODDEF
3354 MATH_FMOD_METHODDEF
3355 MATH_FREXP_METHODDEF
3356 MATH_FSUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003357 {"gamma", math_gamma, METH_O, math_gamma_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003358 MATH_GCD_METHODDEF
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003359 {"hypot", (PyCFunction)(void(*)(void))math_hypot, METH_FASTCALL, math_hypot_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003360 MATH_ISCLOSE_METHODDEF
3361 MATH_ISFINITE_METHODDEF
3362 MATH_ISINF_METHODDEF
3363 MATH_ISNAN_METHODDEF
Mark Dickinson73934b92019-05-18 12:29:50 +01003364 MATH_ISQRT_METHODDEF
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003365 MATH_LDEXP_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003366 {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003367 MATH_LOG_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003368 {"log1p", math_log1p, METH_O, math_log1p_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003369 MATH_LOG10_METHODDEF
3370 MATH_LOG2_METHODDEF
3371 MATH_MODF_METHODDEF
3372 MATH_POW_METHODDEF
3373 MATH_RADIANS_METHODDEF
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003374 {"remainder", (PyCFunction)(void(*)(void))math_remainder, METH_FASTCALL, math_remainder_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003375 {"sin", math_sin, METH_O, math_sin_doc},
3376 {"sinh", math_sinh, METH_O, math_sinh_doc},
3377 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
3378 {"tan", math_tan, METH_O, math_tan_doc},
3379 {"tanh", math_tanh, METH_O, math_tanh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003380 MATH_TRUNC_METHODDEF
Pablo Galindobc098512019-02-07 07:04:02 +00003381 MATH_PROD_METHODDEF
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003382 MATH_PERM_METHODDEF
Yash Aggarwal4a686502019-06-01 12:51:27 +05303383 MATH_COMB_METHODDEF
Victor Stinner100fafc2020-01-12 02:15:42 +01003384 MATH_NEXTAFTER_METHODDEF
Victor Stinner0b2ab212020-01-13 12:44:35 +01003385 MATH_ULP_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003386 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003387};
3388
Guido van Rossumc6e22901998-12-04 19:26:43 +00003389
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003390PyDoc_STRVAR(module_doc,
Ned Batchelder6faad352019-05-17 05:59:14 -04003391"This module provides access to the mathematical functions\n"
3392"defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00003393
Martin v. Löwis1a214512008-06-11 05:26:20 +00003394
3395static struct PyModuleDef mathmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003396 PyModuleDef_HEAD_INIT,
3397 "math",
3398 module_doc,
3399 -1,
3400 math_methods,
3401 NULL,
3402 NULL,
3403 NULL,
3404 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003405};
3406
Mark Hammondfe51c6d2002-08-02 02:27:13 +00003407PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003408PyInit_math(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003410 PyObject *m;
Tim Petersfe71f812001-08-07 22:10:00 +00003411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003412 m = PyModule_Create(&mathmodule);
3413 if (m == NULL)
3414 goto finally;
Barry Warsawfc93f751996-12-17 00:47:03 +00003415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003416 PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
3417 PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
Guido van Rossum0a891d72016-08-15 09:12:52 -07003418 PyModule_AddObject(m, "tau", PyFloat_FromDouble(Py_MATH_TAU)); /* 2pi */
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +00003419 PyModule_AddObject(m, "inf", PyFloat_FromDouble(m_inf()));
3420#if !defined(PY_NO_SHORT_FLOAT_REPR) || defined(Py_NAN)
3421 PyModule_AddObject(m, "nan", PyFloat_FromDouble(m_nan()));
3422#endif
Barry Warsawfc93f751996-12-17 00:47:03 +00003423
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +00003424 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003425 return m;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003426}