blob: 1d6174132814b2ae8334f15e3f910953a93e14ee [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Math module -- standard C math library functions, pi and e */
2
Christian Heimes53876d92008-04-19 00:31:39 +00003/* Here are some comments from Tim Peters, extracted from the
4 discussion attached to http://bugs.python.org/issue1640. They
5 describe the general aims of the math module with respect to
6 special values, IEEE-754 floating-point exceptions, and Python
7 exceptions.
8
9These are the "spirit of 754" rules:
10
111. If the mathematical result is a real number, but of magnitude too
12large to approximate by a machine float, overflow is signaled and the
13result is an infinity (with the appropriate sign).
14
152. If the mathematical result is a real number, but of magnitude too
16small to approximate by a machine float, underflow is signaled and the
17result is a zero (with the appropriate sign).
18
193. At a singularity (a value x such that the limit of f(y) as y
20approaches x exists and is an infinity), "divide by zero" is signaled
21and the result is an infinity (with the appropriate sign). This is
22complicated a little by that the left-side and right-side limits may
23not be the same; e.g., 1/x approaches +inf or -inf as x approaches 0
24from the positive or negative directions. In that specific case, the
25sign of the zero determines the result of 1/0.
26
274. At a point where a function has no defined result in the extended
28reals (i.e., the reals plus an infinity or two), invalid operation is
29signaled and a NaN is returned.
30
31And these are what Python has historically /tried/ to do (but not
32always successfully, as platform libm behavior varies a lot):
33
34For #1, raise OverflowError.
35
36For #2, return a zero (with the appropriate sign if that happens by
37accident ;-)).
38
39For #3 and #4, raise ValueError. It may have made sense to raise
40Python's ZeroDivisionError in #3, but historically that's only been
41raised for division by zero and mod by zero.
42
43*/
44
45/*
46 In general, on an IEEE-754 platform the aim is to follow the C99
47 standard, including Annex 'F', whenever possible. Where the
48 standard recommends raising the 'divide-by-zero' or 'invalid'
49 floating-point exceptions, Python should raise a ValueError. Where
50 the standard recommends raising 'overflow', Python should raise an
51 OverflowError. In all other circumstances a value should be
52 returned.
53 */
54
Barry Warsaw8b43b191996-12-09 22:32:36 +000055#include "Python.h"
Niklas Fiekas794e7d12020-06-15 14:33:48 +020056#include "pycore_bitutils.h" // _Py_bit_length()
Victor Stinnere9e7d282020-02-12 22:54:42 +010057#include "pycore_dtoa.h"
Mark Dickinson664b5112009-12-16 20:23:42 +000058#include "_math.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000059
Serhiy Storchakac9ea9332017-01-19 18:13:09 +020060#include "clinic/mathmodule.c.h"
61
62/*[clinic input]
63module math
64[clinic start generated code]*/
65/*[clinic end generated code: output=da39a3ee5e6b4b0d input=76bc7002685dd942]*/
66
67
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000068/*
69 sin(pi*x), giving accurate results for all finite x (especially x
70 integral or close to an integer). This is here for use in the
71 reflection formula for the gamma function. It conforms to IEEE
72 754-2008 for finite arguments, but not for infinities or nans.
73*/
Tim Petersa40c7932001-09-05 22:36:56 +000074
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000075static const double pi = 3.141592653589793238462643383279502884197;
Mark Dickinson9c91eb82010-07-07 16:17:31 +000076static const double logpi = 1.144729885849400174143427351353058711647;
Louie Lu7a264642017-03-31 01:05:10 +080077#if !defined(HAVE_ERF) || !defined(HAVE_ERFC)
78static const double sqrtpi = 1.772453850905516027298167483341145182798;
79#endif /* !defined(HAVE_ERF) || !defined(HAVE_ERFC) */
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000080
Raymond Hettingercfd735e2019-01-29 20:39:53 -080081
82/* Version of PyFloat_AsDouble() with in-line fast paths
83 for exact floats and integers. Gives a substantial
84 speed improvement for extracting float arguments.
85*/
86
87#define ASSIGN_DOUBLE(target_var, obj, error_label) \
88 if (PyFloat_CheckExact(obj)) { \
89 target_var = PyFloat_AS_DOUBLE(obj); \
90 } \
91 else if (PyLong_CheckExact(obj)) { \
92 target_var = PyLong_AsDouble(obj); \
93 if (target_var == -1.0 && PyErr_Occurred()) { \
94 goto error_label; \
95 } \
96 } \
97 else { \
98 target_var = PyFloat_AsDouble(obj); \
99 if (target_var == -1.0 && PyErr_Occurred()) { \
100 goto error_label; \
101 } \
102 }
103
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000104static double
Dima Pasechnikf57cd822019-02-26 06:36:11 +0000105m_sinpi(double x)
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000106{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107 double y, r;
108 int n;
109 /* this function should only ever be called for finite arguments */
110 assert(Py_IS_FINITE(x));
111 y = fmod(fabs(x), 2.0);
112 n = (int)round(2.0*y);
113 assert(0 <= n && n <= 4);
114 switch (n) {
115 case 0:
116 r = sin(pi*y);
117 break;
118 case 1:
119 r = cos(pi*(y-0.5));
120 break;
121 case 2:
122 /* N.B. -sin(pi*(y-1.0)) is *not* equivalent: it would give
123 -0.0 instead of 0.0 when y == 1.0. */
124 r = sin(pi*(1.0-y));
125 break;
126 case 3:
127 r = -cos(pi*(y-1.5));
128 break;
129 case 4:
130 r = sin(pi*(y-2.0));
131 break;
132 default:
Barry Warsawb2e57942017-09-14 18:13:16 -0700133 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 }
135 return copysign(1.0, x)*r;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000136}
137
138/* Implementation of the real gamma function. In extensive but non-exhaustive
139 random tests, this function proved accurate to within <= 10 ulps across the
140 entire float domain. Note that accuracy may depend on the quality of the
141 system math functions, the pow function in particular. Special cases
142 follow C99 annex F. The parameters and method are tailored to platforms
143 whose double format is the IEEE 754 binary64 format.
144
145 Method: for x > 0.0 we use the Lanczos approximation with parameters N=13
146 and g=6.024680040776729583740234375; these parameters are amongst those
147 used by the Boost library. Following Boost (again), we re-express the
148 Lanczos sum as a rational function, and compute it that way. The
149 coefficients below were computed independently using MPFR, and have been
150 double-checked against the coefficients in the Boost source code.
151
152 For x < 0.0 we use the reflection formula.
153
154 There's one minor tweak that deserves explanation: Lanczos' formula for
155 Gamma(x) involves computing pow(x+g-0.5, x-0.5) / exp(x+g-0.5). For many x
156 values, x+g-0.5 can be represented exactly. However, in cases where it
157 can't be represented exactly the small error in x+g-0.5 can be magnified
158 significantly by the pow and exp calls, especially for large x. A cheap
159 correction is to multiply by (1 + e*g/(x+g-0.5)), where e is the error
160 involved in the computation of x+g-0.5 (that is, e = computed value of
161 x+g-0.5 - exact value of x+g-0.5). Here's the proof:
162
163 Correction factor
164 -----------------
165 Write x+g-0.5 = y-e, where y is exactly representable as an IEEE 754
166 double, and e is tiny. Then:
167
168 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) = pow(y-e, x-0.5)/exp(y-e)
169 = pow(y, x-0.5)/exp(y) * C,
170
171 where the correction_factor C is given by
172
173 C = pow(1-e/y, x-0.5) * exp(e)
174
175 Since e is tiny, pow(1-e/y, x-0.5) ~ 1-(x-0.5)*e/y, and exp(x) ~ 1+e, so:
176
177 C ~ (1-(x-0.5)*e/y) * (1+e) ~ 1 + e*(y-(x-0.5))/y
178
179 But y-(x-0.5) = g+e, and g+e ~ g. So we get C ~ 1 + e*g/y, and
180
181 pow(x+g-0.5,x-0.5)/exp(x+g-0.5) ~ pow(y, x-0.5)/exp(y) * (1 + e*g/y),
182
183 Note that for accuracy, when computing r*C it's better to do
184
185 r + e*g/y*r;
186
187 than
188
189 r * (1 + e*g/y);
190
191 since the addition in the latter throws away most of the bits of
192 information in e*g/y.
193*/
194
195#define LANCZOS_N 13
196static const double lanczos_g = 6.024680040776729583740234375;
197static const double lanczos_g_minus_half = 5.524680040776729583740234375;
198static const double lanczos_num_coeffs[LANCZOS_N] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 23531376880.410759688572007674451636754734846804940,
200 42919803642.649098768957899047001988850926355848959,
201 35711959237.355668049440185451547166705960488635843,
202 17921034426.037209699919755754458931112671403265390,
203 6039542586.3520280050642916443072979210699388420708,
204 1439720407.3117216736632230727949123939715485786772,
205 248874557.86205415651146038641322942321632125127801,
206 31426415.585400194380614231628318205362874684987640,
207 2876370.6289353724412254090516208496135991145378768,
208 186056.26539522349504029498971604569928220784236328,
209 8071.6720023658162106380029022722506138218516325024,
210 210.82427775157934587250973392071336271166969580291,
211 2.5066282746310002701649081771338373386264310793408
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000212};
213
214/* denominator is x*(x+1)*...*(x+LANCZOS_N-2) */
215static const double lanczos_den_coeffs[LANCZOS_N] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000216 0.0, 39916800.0, 120543840.0, 150917976.0, 105258076.0, 45995730.0,
217 13339535.0, 2637558.0, 357423.0, 32670.0, 1925.0, 66.0, 1.0};
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000218
219/* gamma values for small positive integers, 1 though NGAMMA_INTEGRAL */
220#define NGAMMA_INTEGRAL 23
221static const double gamma_integral[NGAMMA_INTEGRAL] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0,
223 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0,
224 1307674368000.0, 20922789888000.0, 355687428096000.0,
225 6402373705728000.0, 121645100408832000.0, 2432902008176640000.0,
226 51090942171709440000.0, 1124000727777607680000.0,
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000227};
228
229/* Lanczos' sum L_g(x), for positive x */
230
231static double
232lanczos_sum(double x)
233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 double num = 0.0, den = 0.0;
235 int i;
236 assert(x > 0.0);
237 /* evaluate the rational function lanczos_sum(x). For large
238 x, the obvious algorithm risks overflow, so we instead
239 rescale the denominator and numerator of the rational
240 function by x**(1-LANCZOS_N) and treat this as a
241 rational function in 1/x. This also reduces the error for
242 larger x values. The choice of cutoff point (5.0 below) is
243 somewhat arbitrary; in tests, smaller cutoff values than
244 this resulted in lower accuracy. */
245 if (x < 5.0) {
246 for (i = LANCZOS_N; --i >= 0; ) {
247 num = num * x + lanczos_num_coeffs[i];
248 den = den * x + lanczos_den_coeffs[i];
249 }
250 }
251 else {
252 for (i = 0; i < LANCZOS_N; i++) {
253 num = num / x + lanczos_num_coeffs[i];
254 den = den / x + lanczos_den_coeffs[i];
255 }
256 }
257 return num/den;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000258}
259
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +0000260/* Constant for +infinity, generated in the same way as float('inf'). */
261
262static double
263m_inf(void)
264{
265#ifndef PY_NO_SHORT_FLOAT_REPR
266 return _Py_dg_infinity(0);
267#else
268 return Py_HUGE_VAL;
269#endif
270}
271
272/* Constant nan value, generated in the same way as float('nan'). */
273/* We don't currently assume that Py_NAN is defined everywhere. */
274
275#if !defined(PY_NO_SHORT_FLOAT_REPR) || defined(Py_NAN)
276
277static double
278m_nan(void)
279{
280#ifndef PY_NO_SHORT_FLOAT_REPR
281 return _Py_dg_stdnan(0);
282#else
283 return Py_NAN;
284#endif
285}
286
287#endif
288
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000289static double
290m_tgamma(double x)
291{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 double absx, r, y, z, sqrtpow;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 /* special cases */
295 if (!Py_IS_FINITE(x)) {
296 if (Py_IS_NAN(x) || x > 0.0)
297 return x; /* tgamma(nan) = nan, tgamma(inf) = inf */
298 else {
299 errno = EDOM;
300 return Py_NAN; /* tgamma(-inf) = nan, invalid */
301 }
302 }
303 if (x == 0.0) {
304 errno = EDOM;
Mark Dickinson50203a62011-09-25 15:26:43 +0100305 /* tgamma(+-0.0) = +-inf, divide-by-zero */
306 return copysign(Py_HUGE_VAL, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 /* integer arguments */
310 if (x == floor(x)) {
311 if (x < 0.0) {
312 errno = EDOM; /* tgamma(n) = nan, invalid for */
313 return Py_NAN; /* negative integers n */
314 }
315 if (x <= NGAMMA_INTEGRAL)
316 return gamma_integral[(int)x - 1];
317 }
318 absx = fabs(x);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 /* tiny arguments: tgamma(x) ~ 1/x for x near 0 */
321 if (absx < 1e-20) {
322 r = 1.0/x;
323 if (Py_IS_INFINITY(r))
324 errno = ERANGE;
325 return r;
326 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 /* large arguments: assuming IEEE 754 doubles, tgamma(x) overflows for
329 x > 200, and underflows to +-0.0 for x < -200, not a negative
330 integer. */
331 if (absx > 200.0) {
332 if (x < 0.0) {
Dima Pasechnikf57cd822019-02-26 06:36:11 +0000333 return 0.0/m_sinpi(x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 }
335 else {
336 errno = ERANGE;
337 return Py_HUGE_VAL;
338 }
339 }
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 y = absx + lanczos_g_minus_half;
342 /* compute error in sum */
343 if (absx > lanczos_g_minus_half) {
344 /* note: the correction can be foiled by an optimizing
345 compiler that (incorrectly) thinks that an expression like
346 a + b - a - b can be optimized to 0.0. This shouldn't
347 happen in a standards-conforming compiler. */
348 double q = y - absx;
349 z = q - lanczos_g_minus_half;
350 }
351 else {
352 double q = y - lanczos_g_minus_half;
353 z = q - absx;
354 }
355 z = z * lanczos_g / y;
356 if (x < 0.0) {
Dima Pasechnikf57cd822019-02-26 06:36:11 +0000357 r = -pi / m_sinpi(absx) / absx * exp(y) / lanczos_sum(absx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 r -= z * r;
359 if (absx < 140.0) {
360 r /= pow(y, absx - 0.5);
361 }
362 else {
363 sqrtpow = pow(y, absx / 2.0 - 0.25);
364 r /= sqrtpow;
365 r /= sqrtpow;
366 }
367 }
368 else {
369 r = lanczos_sum(absx) / exp(y);
370 r += z * r;
371 if (absx < 140.0) {
372 r *= pow(y, absx - 0.5);
373 }
374 else {
375 sqrtpow = pow(y, absx / 2.0 - 0.25);
376 r *= sqrtpow;
377 r *= sqrtpow;
378 }
379 }
380 if (Py_IS_INFINITY(r))
381 errno = ERANGE;
382 return r;
Guido van Rossum8832b621991-12-16 15:44:24 +0000383}
384
Christian Heimes53876d92008-04-19 00:31:39 +0000385/*
Mark Dickinson05d2e082009-12-11 20:17:17 +0000386 lgamma: natural log of the absolute value of the Gamma function.
387 For large arguments, Lanczos' formula works extremely well here.
388*/
389
390static double
391m_lgamma(double x)
392{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200393 double r;
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200394 double absx;
Mark Dickinson05d2e082009-12-11 20:17:17 +0000395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 /* special cases */
397 if (!Py_IS_FINITE(x)) {
398 if (Py_IS_NAN(x))
399 return x; /* lgamma(nan) = nan */
400 else
401 return Py_HUGE_VAL; /* lgamma(+-inf) = +inf */
402 }
Mark Dickinson05d2e082009-12-11 20:17:17 +0000403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 /* integer arguments */
405 if (x == floor(x) && x <= 2.0) {
406 if (x <= 0.0) {
407 errno = EDOM; /* lgamma(n) = inf, divide-by-zero for */
408 return Py_HUGE_VAL; /* integers n <= 0 */
409 }
410 else {
411 return 0.0; /* lgamma(1) = lgamma(2) = 0.0 */
412 }
413 }
Mark Dickinson05d2e082009-12-11 20:17:17 +0000414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 absx = fabs(x);
416 /* tiny arguments: lgamma(x) ~ -log(fabs(x)) for small x */
417 if (absx < 1e-20)
418 return -log(absx);
Mark Dickinson05d2e082009-12-11 20:17:17 +0000419
Mark Dickinson9c91eb82010-07-07 16:17:31 +0000420 /* Lanczos' formula. We could save a fraction of a ulp in accuracy by
421 having a second set of numerator coefficients for lanczos_sum that
422 absorbed the exp(-lanczos_g) term, and throwing out the lanczos_g
423 subtraction below; it's probably not worth it. */
424 r = log(lanczos_sum(absx)) - lanczos_g;
425 r += (absx - 0.5) * (log(absx + lanczos_g - 0.5) - 1);
426 if (x < 0.0)
427 /* Use reflection formula to get value for negative x. */
Dima Pasechnikf57cd822019-02-26 06:36:11 +0000428 r = logpi - log(fabs(m_sinpi(absx))) - log(absx) - r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 if (Py_IS_INFINITY(r))
430 errno = ERANGE;
431 return r;
Mark Dickinson05d2e082009-12-11 20:17:17 +0000432}
433
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200434#if !defined(HAVE_ERF) || !defined(HAVE_ERFC)
435
Mark Dickinson45f992a2009-12-19 11:20:49 +0000436/*
437 Implementations of the error function erf(x) and the complementary error
438 function erfc(x).
439
Brett Cannon45adb312016-01-15 09:38:24 -0800440 Method: we use a series approximation for erf for small x, and a continued
441 fraction approximation for erfc(x) for larger x;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000442 combined with the relations erf(-x) = -erf(x) and erfc(x) = 1.0 - erf(x),
443 this gives us erf(x) and erfc(x) for all x.
444
445 The series expansion used is:
446
447 erf(x) = x*exp(-x*x)/sqrt(pi) * [
448 2/1 + 4/3 x**2 + 8/15 x**4 + 16/105 x**6 + ...]
449
450 The coefficient of x**(2k-2) here is 4**k*factorial(k)/factorial(2*k).
451 This series converges well for smallish x, but slowly for larger x.
452
453 The continued fraction expansion used is:
454
455 erfc(x) = x*exp(-x*x)/sqrt(pi) * [1/(0.5 + x**2 -) 0.5/(2.5 + x**2 - )
456 3.0/(4.5 + x**2 - ) 7.5/(6.5 + x**2 - ) ...]
457
458 after the first term, the general term has the form:
459
460 k*(k-0.5)/(2*k+0.5 + x**2 - ...).
461
462 This expansion converges fast for larger x, but convergence becomes
463 infinitely slow as x approaches 0.0. The (somewhat naive) continued
464 fraction evaluation algorithm used below also risks overflow for large x;
465 but for large x, erfc(x) == 0.0 to within machine precision. (For
466 example, erfc(30.0) is approximately 2.56e-393).
467
468 Parameters: use series expansion for abs(x) < ERF_SERIES_CUTOFF and
469 continued fraction expansion for ERF_SERIES_CUTOFF <= abs(x) <
470 ERFC_CONTFRAC_CUTOFF. ERFC_SERIES_TERMS and ERFC_CONTFRAC_TERMS are the
471 numbers of terms to use for the relevant expansions. */
472
473#define ERF_SERIES_CUTOFF 1.5
474#define ERF_SERIES_TERMS 25
475#define ERFC_CONTFRAC_CUTOFF 30.0
476#define ERFC_CONTFRAC_TERMS 50
477
478/*
479 Error function, via power series.
480
481 Given a finite float x, return an approximation to erf(x).
482 Converges reasonably fast for small x.
483*/
484
485static double
486m_erf_series(double x)
487{
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000488 double x2, acc, fk, result;
489 int i, saved_errno;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 x2 = x * x;
492 acc = 0.0;
493 fk = (double)ERF_SERIES_TERMS + 0.5;
494 for (i = 0; i < ERF_SERIES_TERMS; i++) {
495 acc = 2.0 + x2 * acc / fk;
496 fk -= 1.0;
497 }
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000498 /* Make sure the exp call doesn't affect errno;
499 see m_erfc_contfrac for more. */
500 saved_errno = errno;
501 result = acc * x * exp(-x2) / sqrtpi;
502 errno = saved_errno;
503 return result;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000504}
505
506/*
507 Complementary error function, via continued fraction expansion.
508
509 Given a positive float x, return an approximation to erfc(x). Converges
510 reasonably fast for x large (say, x > 2.0), and should be safe from
511 overflow if x and nterms are not too large. On an IEEE 754 machine, with x
512 <= 30.0, we're safe up to nterms = 100. For x >= 30.0, erfc(x) is smaller
513 than the smallest representable nonzero float. */
514
515static double
516m_erfc_contfrac(double x)
517{
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000518 double x2, a, da, p, p_last, q, q_last, b, result;
519 int i, saved_errno;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 if (x >= ERFC_CONTFRAC_CUTOFF)
522 return 0.0;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 x2 = x*x;
525 a = 0.0;
526 da = 0.5;
527 p = 1.0; p_last = 0.0;
528 q = da + x2; q_last = 1.0;
529 for (i = 0; i < ERFC_CONTFRAC_TERMS; i++) {
530 double temp;
531 a += da;
532 da += 2.0;
533 b = da + x2;
534 temp = p; p = b*p - a*p_last; p_last = temp;
535 temp = q; q = b*q - a*q_last; q_last = temp;
536 }
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +0000537 /* Issue #8986: On some platforms, exp sets errno on underflow to zero;
538 save the current errno value so that we can restore it later. */
539 saved_errno = errno;
540 result = p / q * x * exp(-x2) / sqrtpi;
541 errno = saved_errno;
542 return result;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000543}
544
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200545#endif /* !defined(HAVE_ERF) || !defined(HAVE_ERFC) */
546
Mark Dickinson45f992a2009-12-19 11:20:49 +0000547/* Error function erf(x), for general x */
548
549static double
550m_erf(double x)
551{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200552#ifdef HAVE_ERF
553 return erf(x);
554#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 double absx, cf;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 if (Py_IS_NAN(x))
558 return x;
559 absx = fabs(x);
560 if (absx < ERF_SERIES_CUTOFF)
561 return m_erf_series(x);
562 else {
563 cf = m_erfc_contfrac(absx);
564 return x > 0.0 ? 1.0 - cf : cf - 1.0;
565 }
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200566#endif
Mark Dickinson45f992a2009-12-19 11:20:49 +0000567}
568
569/* Complementary error function erfc(x), for general x. */
570
571static double
572m_erfc(double x)
573{
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200574#ifdef HAVE_ERFC
575 return erfc(x);
576#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 double absx, cf;
Mark Dickinson45f992a2009-12-19 11:20:49 +0000578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 if (Py_IS_NAN(x))
580 return x;
581 absx = fabs(x);
582 if (absx < ERF_SERIES_CUTOFF)
583 return 1.0 - m_erf_series(x);
584 else {
585 cf = m_erfc_contfrac(absx);
586 return x > 0.0 ? cf : 2.0 - cf;
587 }
Serhiy Storchaka97553fd2017-03-11 23:37:16 +0200588#endif
Mark Dickinson45f992a2009-12-19 11:20:49 +0000589}
Mark Dickinson05d2e082009-12-11 20:17:17 +0000590
591/*
Christian Heimese57950f2008-04-21 13:08:03 +0000592 wrapper for atan2 that deals directly with special cases before
593 delegating to the platform libm for the remaining cases. This
594 is necessary to get consistent behaviour across platforms.
595 Windows, FreeBSD and alpha Tru64 are amongst platforms that don't
596 always follow C99.
597*/
598
599static double
600m_atan2(double y, double x)
601{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 if (Py_IS_NAN(x) || Py_IS_NAN(y))
603 return Py_NAN;
604 if (Py_IS_INFINITY(y)) {
605 if (Py_IS_INFINITY(x)) {
606 if (copysign(1., x) == 1.)
607 /* atan2(+-inf, +inf) == +-pi/4 */
608 return copysign(0.25*Py_MATH_PI, y);
609 else
610 /* atan2(+-inf, -inf) == +-pi*3/4 */
611 return copysign(0.75*Py_MATH_PI, y);
612 }
613 /* atan2(+-inf, x) == +-pi/2 for finite x */
614 return copysign(0.5*Py_MATH_PI, y);
615 }
616 if (Py_IS_INFINITY(x) || y == 0.) {
617 if (copysign(1., x) == 1.)
618 /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */
619 return copysign(0., y);
620 else
621 /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */
622 return copysign(Py_MATH_PI, y);
623 }
624 return atan2(y, x);
Christian Heimese57950f2008-04-21 13:08:03 +0000625}
626
Mark Dickinsona0ce3752017-04-05 18:34:27 +0100627
628/* IEEE 754-style remainder operation: x - n*y where n*y is the nearest
629 multiple of y to x, taking n even in the case of a tie. Assuming an IEEE 754
630 binary floating-point format, the result is always exact. */
631
632static double
633m_remainder(double x, double y)
634{
635 /* Deal with most common case first. */
636 if (Py_IS_FINITE(x) && Py_IS_FINITE(y)) {
637 double absx, absy, c, m, r;
638
639 if (y == 0.0) {
640 return Py_NAN;
641 }
642
643 absx = fabs(x);
644 absy = fabs(y);
645 m = fmod(absx, absy);
646
647 /*
648 Warning: some subtlety here. What we *want* to know at this point is
649 whether the remainder m is less than, equal to, or greater than half
650 of absy. However, we can't do that comparison directly because we
Mark Dickinson01484702019-07-13 16:50:03 +0100651 can't be sure that 0.5*absy is representable (the multiplication
Mark Dickinsona0ce3752017-04-05 18:34:27 +0100652 might incur precision loss due to underflow). So instead we compare
653 m with the complement c = absy - m: m < 0.5*absy if and only if m <
654 c, and so on. The catch is that absy - m might also not be
655 representable, but it turns out that it doesn't matter:
656
657 - if m > 0.5*absy then absy - m is exactly representable, by
658 Sterbenz's lemma, so m > c
659 - if m == 0.5*absy then again absy - m is exactly representable
660 and m == c
661 - if m < 0.5*absy then either (i) 0.5*absy is exactly representable,
662 in which case 0.5*absy < absy - m, so 0.5*absy <= c and hence m <
663 c, or (ii) absy is tiny, either subnormal or in the lowest normal
664 binade. Then absy - m is exactly representable and again m < c.
665 */
666
667 c = absy - m;
668 if (m < c) {
669 r = m;
670 }
671 else if (m > c) {
672 r = -c;
673 }
674 else {
675 /*
676 Here absx is exactly halfway between two multiples of absy,
677 and we need to choose the even multiple. x now has the form
678
679 absx = n * absy + m
680
681 for some integer n (recalling that m = 0.5*absy at this point).
682 If n is even we want to return m; if n is odd, we need to
683 return -m.
684
685 So
686
687 0.5 * (absx - m) = (n/2) * absy
688
689 and now reducing modulo absy gives us:
690
691 | m, if n is odd
692 fmod(0.5 * (absx - m), absy) = |
693 | 0, if n is even
694
695 Now m - 2.0 * fmod(...) gives the desired result: m
696 if n is even, -m if m is odd.
697
698 Note that all steps in fmod(0.5 * (absx - m), absy)
699 will be computed exactly, with no rounding error
700 introduced.
701 */
702 assert(m == c);
703 r = m - 2.0 * fmod(0.5 * (absx - m), absy);
704 }
705 return copysign(1.0, x) * r;
706 }
707
708 /* Special values. */
709 if (Py_IS_NAN(x)) {
710 return x;
711 }
712 if (Py_IS_NAN(y)) {
713 return y;
714 }
715 if (Py_IS_INFINITY(x)) {
716 return Py_NAN;
717 }
718 assert(Py_IS_INFINITY(y));
719 return x;
720}
721
722
Christian Heimese57950f2008-04-21 13:08:03 +0000723/*
Mark Dickinsone675f082008-12-11 21:56:00 +0000724 Various platforms (Solaris, OpenBSD) do nonstandard things for log(0),
725 log(-ve), log(NaN). Here are wrappers for log and log10 that deal with
726 special values directly, passing positive non-special values through to
727 the system log/log10.
728 */
729
730static double
731m_log(double x)
732{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 if (Py_IS_FINITE(x)) {
734 if (x > 0.0)
735 return log(x);
736 errno = EDOM;
737 if (x == 0.0)
738 return -Py_HUGE_VAL; /* log(0) = -inf */
739 else
740 return Py_NAN; /* log(-ve) = nan */
741 }
742 else if (Py_IS_NAN(x))
743 return x; /* log(nan) = nan */
744 else if (x > 0.0)
745 return x; /* log(inf) = inf */
746 else {
747 errno = EDOM;
748 return Py_NAN; /* log(-inf) = nan */
749 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000750}
751
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200752/*
753 log2: log to base 2.
754
755 Uses an algorithm that should:
Mark Dickinson83b8c0b2011-05-09 08:40:20 +0100756
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200757 (a) produce exact results for powers of 2, and
Mark Dickinson83b8c0b2011-05-09 08:40:20 +0100758 (b) give a monotonic log2 (for positive finite floats),
759 assuming that the system log is monotonic.
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200760*/
761
762static double
763m_log2(double x)
764{
765 if (!Py_IS_FINITE(x)) {
766 if (Py_IS_NAN(x))
767 return x; /* log2(nan) = nan */
768 else if (x > 0.0)
769 return x; /* log2(+inf) = +inf */
770 else {
771 errno = EDOM;
772 return Py_NAN; /* log2(-inf) = nan, invalid-operation */
773 }
774 }
775
776 if (x > 0.0) {
Victor Stinner8f9f8d62011-05-09 12:45:41 +0200777#ifdef HAVE_LOG2
778 return log2(x);
779#else
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200780 double m;
781 int e;
782 m = frexp(x, &e);
783 /* We want log2(m * 2**e) == log(m) / log(2) + e. Care is needed when
784 * x is just greater than 1.0: in that case e is 1, log(m) is negative,
785 * and we get significant cancellation error from the addition of
786 * log(m) / log(2) to e. The slight rewrite of the expression below
787 * avoids this problem.
788 */
789 if (x >= 1.0) {
790 return log(2.0 * m) / log(2.0) + (e - 1);
791 }
792 else {
793 return log(m) / log(2.0) + e;
794 }
Victor Stinner8f9f8d62011-05-09 12:45:41 +0200795#endif
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200796 }
797 else if (x == 0.0) {
798 errno = EDOM;
799 return -Py_HUGE_VAL; /* log2(0) = -inf, divide-by-zero */
800 }
801 else {
802 errno = EDOM;
Mark Dickinson23442582011-05-09 08:05:00 +0100803 return Py_NAN; /* log2(-inf) = nan, invalid-operation */
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200804 }
805}
806
Mark Dickinsone675f082008-12-11 21:56:00 +0000807static double
808m_log10(double x)
809{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 if (Py_IS_FINITE(x)) {
811 if (x > 0.0)
812 return log10(x);
813 errno = EDOM;
814 if (x == 0.0)
815 return -Py_HUGE_VAL; /* log10(0) = -inf */
816 else
817 return Py_NAN; /* log10(-ve) = nan */
818 }
819 else if (Py_IS_NAN(x))
820 return x; /* log10(nan) = nan */
821 else if (x > 0.0)
822 return x; /* log10(inf) = inf */
823 else {
824 errno = EDOM;
825 return Py_NAN; /* log10(-inf) = nan */
826 }
Mark Dickinsone675f082008-12-11 21:56:00 +0000827}
828
829
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200830static PyObject *
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200831math_gcd(PyObject *module, PyObject * const *args, Py_ssize_t nargs)
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200832{
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200833 PyObject *res, *x;
834 Py_ssize_t i;
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300835
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200836 if (nargs == 0) {
837 return PyLong_FromLong(0);
838 }
839 res = PyNumber_Index(args[0]);
840 if (res == NULL) {
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300841 return NULL;
842 }
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200843 if (nargs == 1) {
844 Py_SETREF(res, PyNumber_Absolute(res));
845 return res;
846 }
847 for (i = 1; i < nargs; i++) {
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +0300848 x = _PyNumber_Index(args[i]);
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200849 if (x == NULL) {
850 Py_DECREF(res);
851 return NULL;
852 }
853 if (res == _PyLong_One) {
854 /* Fast path: just check arguments.
855 It is okay to use identity comparison here. */
856 Py_DECREF(x);
857 continue;
858 }
859 Py_SETREF(res, _PyLong_GCD(res, x));
860 Py_DECREF(x);
861 if (res == NULL) {
862 return NULL;
863 }
864 }
865 return res;
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300866}
867
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200868PyDoc_STRVAR(math_gcd_doc,
869"gcd($module, *integers)\n"
870"--\n"
871"\n"
872"Greatest Common Divisor.");
873
874
875static PyObject *
876long_lcm(PyObject *a, PyObject *b)
877{
878 PyObject *g, *m, *f, *ab;
879
880 if (Py_SIZE(a) == 0 || Py_SIZE(b) == 0) {
881 return PyLong_FromLong(0);
882 }
883 g = _PyLong_GCD(a, b);
884 if (g == NULL) {
885 return NULL;
886 }
887 f = PyNumber_FloorDivide(a, g);
888 Py_DECREF(g);
889 if (f == NULL) {
890 return NULL;
891 }
892 m = PyNumber_Multiply(f, b);
893 Py_DECREF(f);
894 if (m == NULL) {
895 return NULL;
896 }
897 ab = PyNumber_Absolute(m);
898 Py_DECREF(m);
899 return ab;
900}
901
902
903static PyObject *
904math_lcm(PyObject *module, PyObject * const *args, Py_ssize_t nargs)
905{
906 PyObject *res, *x;
907 Py_ssize_t i;
908
909 if (nargs == 0) {
910 return PyLong_FromLong(1);
911 }
912 res = PyNumber_Index(args[0]);
913 if (res == NULL) {
914 return NULL;
915 }
916 if (nargs == 1) {
917 Py_SETREF(res, PyNumber_Absolute(res));
918 return res;
919 }
920 for (i = 1; i < nargs; i++) {
921 x = PyNumber_Index(args[i]);
922 if (x == NULL) {
923 Py_DECREF(res);
924 return NULL;
925 }
926 if (res == _PyLong_Zero) {
927 /* Fast path: just check arguments.
928 It is okay to use identity comparison here. */
929 Py_DECREF(x);
930 continue;
931 }
932 Py_SETREF(res, long_lcm(res, x));
933 Py_DECREF(x);
934 if (res == NULL) {
935 return NULL;
936 }
937 }
938 return res;
939}
940
941
942PyDoc_STRVAR(math_lcm_doc,
943"lcm($module, *integers)\n"
944"--\n"
945"\n"
946"Least Common Multiple.");
947
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300948
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000949/* Call is_error when errno != 0, and where x is the result libm
950 * returned. is_error will usually set up an exception and return
951 * true (1), but may return false (0) without setting up an exception.
952 */
953static int
954is_error(double x)
955{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 int result = 1; /* presumption of guilt */
957 assert(errno); /* non-zero errno is a precondition for calling */
958 if (errno == EDOM)
959 PyErr_SetString(PyExc_ValueError, "math domain error");
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 else if (errno == ERANGE) {
962 /* ANSI C generally requires libm functions to set ERANGE
963 * on overflow, but also generally *allows* them to set
964 * ERANGE on underflow too. There's no consistency about
965 * the latter across platforms.
966 * Alas, C99 never requires that errno be set.
967 * Here we suppress the underflow errors (libm functions
968 * should return a zero on underflow, and +- HUGE_VAL on
969 * overflow, so testing the result for zero suffices to
970 * distinguish the cases).
971 *
972 * On some platforms (Ubuntu/ia64) it seems that errno can be
973 * set to ERANGE for subnormal results that do *not* underflow
974 * to zero. So to be safe, we'll ignore ERANGE whenever the
975 * function result is less than one in absolute value.
976 */
977 if (fabs(x) < 1.0)
978 result = 0;
979 else
980 PyErr_SetString(PyExc_OverflowError,
981 "math range error");
982 }
983 else
984 /* Unexpected math error */
985 PyErr_SetFromErrno(PyExc_ValueError);
986 return result;
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000987}
988
Mark Dickinsone675f082008-12-11 21:56:00 +0000989/*
Christian Heimes53876d92008-04-19 00:31:39 +0000990 math_1 is used to wrap a libm function f that takes a double
Serhiy Storchakac9ea9332017-01-19 18:13:09 +0200991 argument and returns a double.
Christian Heimes53876d92008-04-19 00:31:39 +0000992
993 The error reporting follows these rules, which are designed to do
994 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
995 platforms.
996
997 - a NaN result from non-NaN inputs causes ValueError to be raised
998 - an infinite result from finite inputs causes OverflowError to be
999 raised if can_overflow is 1, or raises ValueError if can_overflow
1000 is 0.
1001 - if the result is finite and errno == EDOM then ValueError is
1002 raised
1003 - if the result is finite and nonzero and errno == ERANGE then
1004 OverflowError is raised
1005
1006 The last rule is used to catch overflow on platforms which follow
1007 C89 but for which HUGE_VAL is not an infinity.
1008
1009 For the majority of one-argument functions these rules are enough
1010 to ensure that Python's functions behave as specified in 'Annex F'
1011 of the C99 standard, with the 'invalid' and 'divide-by-zero'
1012 floating-point exceptions mapping to Python's ValueError and the
1013 'overflow' floating-point exception mapping to OverflowError.
1014 math_1 only works for functions that don't have singularities *and*
1015 the possibility of overflow; fortunately, that covers everything we
1016 care about right now.
1017*/
1018
Barry Warsaw8b43b191996-12-09 22:32:36 +00001019static PyObject *
Jeffrey Yasskinc2155832008-01-05 20:03:11 +00001020math_1_to_whatever(PyObject *arg, double (*func) (double),
Christian Heimes53876d92008-04-19 00:31:39 +00001021 PyObject *(*from_double_func) (double),
1022 int can_overflow)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001023{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 double x, r;
1025 x = PyFloat_AsDouble(arg);
1026 if (x == -1.0 && PyErr_Occurred())
1027 return NULL;
1028 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 r = (*func)(x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 if (Py_IS_NAN(r) && !Py_IS_NAN(x)) {
1031 PyErr_SetString(PyExc_ValueError,
1032 "math domain error"); /* invalid arg */
1033 return NULL;
1034 }
1035 if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) {
Benjamin Peterson2354a752012-03-13 16:13:09 -05001036 if (can_overflow)
1037 PyErr_SetString(PyExc_OverflowError,
1038 "math range error"); /* overflow */
1039 else
1040 PyErr_SetString(PyExc_ValueError,
1041 "math domain error"); /* singularity */
1042 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 }
1044 if (Py_IS_FINITE(r) && errno && is_error(r))
1045 /* this branch unnecessary on most platforms */
1046 return NULL;
Mark Dickinsonde429622008-05-01 00:19:23 +00001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 return (*from_double_func)(r);
Christian Heimes53876d92008-04-19 00:31:39 +00001049}
1050
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001051/* variant of math_1, to be used when the function being wrapped is known to
1052 set errno properly (that is, errno = EDOM for invalid or divide-by-zero,
1053 errno = ERANGE for overflow). */
1054
1055static PyObject *
1056math_1a(PyObject *arg, double (*func) (double))
1057{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 double x, r;
1059 x = PyFloat_AsDouble(arg);
1060 if (x == -1.0 && PyErr_Occurred())
1061 return NULL;
1062 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 r = (*func)(x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 if (errno && is_error(r))
1065 return NULL;
1066 return PyFloat_FromDouble(r);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001067}
1068
Christian Heimes53876d92008-04-19 00:31:39 +00001069/*
1070 math_2 is used to wrap a libm function f that takes two double
1071 arguments and returns a double.
1072
1073 The error reporting follows these rules, which are designed to do
1074 the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
1075 platforms.
1076
1077 - a NaN result from non-NaN inputs causes ValueError to be raised
1078 - an infinite result from finite inputs causes OverflowError to be
1079 raised.
1080 - if the result is finite and errno == EDOM then ValueError is
1081 raised
1082 - if the result is finite and nonzero and errno == ERANGE then
1083 OverflowError is raised
1084
1085 The last rule is used to catch overflow on platforms which follow
1086 C89 but for which HUGE_VAL is not an infinity.
1087
1088 For most two-argument functions (copysign, fmod, hypot, atan2)
1089 these rules are enough to ensure that Python's functions behave as
1090 specified in 'Annex F' of the C99 standard, with the 'invalid' and
1091 'divide-by-zero' floating-point exceptions mapping to Python's
1092 ValueError and the 'overflow' floating-point exception mapping to
1093 OverflowError.
1094*/
1095
1096static PyObject *
1097math_1(PyObject *arg, double (*func) (double), int can_overflow)
1098{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow);
Jeffrey Yasskinc2155832008-01-05 20:03:11 +00001100}
1101
1102static PyObject *
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02001103math_2(PyObject *const *args, Py_ssize_t nargs,
1104 double (*func) (double, double), const char *funcname)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001105{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 double x, y, r;
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02001107 if (!_PyArg_CheckPositional(funcname, nargs, 2, 2))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 return NULL;
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02001109 x = PyFloat_AsDouble(args[0]);
Zackery Spytz5208b4b2020-03-14 04:45:32 -06001110 if (x == -1.0 && PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 return NULL;
Zackery Spytz5208b4b2020-03-14 04:45:32 -06001112 }
1113 y = PyFloat_AsDouble(args[1]);
1114 if (y == -1.0 && PyErr_Occurred()) {
1115 return NULL;
1116 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 r = (*func)(x, y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 if (Py_IS_NAN(r)) {
1120 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
1121 errno = EDOM;
1122 else
1123 errno = 0;
1124 }
1125 else if (Py_IS_INFINITY(r)) {
1126 if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
1127 errno = ERANGE;
1128 else
1129 errno = 0;
1130 }
1131 if (errno && is_error(r))
1132 return NULL;
1133 else
1134 return PyFloat_FromDouble(r);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001135}
1136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137#define FUNC1(funcname, func, can_overflow, docstring) \
1138 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
1139 return math_1(args, func, can_overflow); \
1140 }\
1141 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143#define FUNC1A(funcname, func, docstring) \
1144 static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
1145 return math_1a(args, func); \
1146 }\
1147 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001148
Fred Drake40c48682000-07-03 18:11:56 +00001149#define FUNC2(funcname, func, docstring) \
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02001150 static PyObject * math_##funcname(PyObject *self, PyObject *const *args, Py_ssize_t nargs) { \
1151 return math_2(args, nargs, func, #funcname); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 }\
1153 PyDoc_STRVAR(math_##funcname##_doc, docstring);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001154
Christian Heimes53876d92008-04-19 00:31:39 +00001155FUNC1(acos, acos, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001156 "acos($module, x, /)\n--\n\n"
Giovanni Cappellottodc3f99f2019-07-13 09:59:55 -04001157 "Return the arc cosine (measured in radians) of x.\n\n"
1158 "The result is between 0 and pi.")
Mark Dickinsonf3718592009-12-21 15:27:41 +00001159FUNC1(acosh, m_acosh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001160 "acosh($module, x, /)\n--\n\n"
1161 "Return the inverse hyperbolic cosine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001162FUNC1(asin, asin, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001163 "asin($module, x, /)\n--\n\n"
Giovanni Cappellottodc3f99f2019-07-13 09:59:55 -04001164 "Return the arc sine (measured in radians) of x.\n\n"
1165 "The result is between -pi/2 and pi/2.")
Mark Dickinsonf3718592009-12-21 15:27:41 +00001166FUNC1(asinh, m_asinh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001167 "asinh($module, x, /)\n--\n\n"
1168 "Return the inverse hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001169FUNC1(atan, atan, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001170 "atan($module, x, /)\n--\n\n"
Giovanni Cappellottodc3f99f2019-07-13 09:59:55 -04001171 "Return the arc tangent (measured in radians) of x.\n\n"
1172 "The result is between -pi/2 and pi/2.")
Christian Heimese57950f2008-04-21 13:08:03 +00001173FUNC2(atan2, m_atan2,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001174 "atan2($module, y, x, /)\n--\n\n"
1175 "Return the arc tangent (measured in radians) of y/x.\n\n"
Tim Petersfe71f812001-08-07 22:10:00 +00001176 "Unlike atan(y/x), the signs of both x and y are considered.")
Mark Dickinsonf3718592009-12-21 15:27:41 +00001177FUNC1(atanh, m_atanh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001178 "atanh($module, x, /)\n--\n\n"
1179 "Return the inverse hyperbolic tangent of x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +00001180
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001181/*[clinic input]
1182math.ceil
1183
1184 x as number: object
1185 /
1186
1187Return the ceiling of x as an Integral.
1188
1189This is the smallest integer >= x.
1190[clinic start generated code]*/
1191
1192static PyObject *
1193math_ceil(PyObject *module, PyObject *number)
1194/*[clinic end generated code: output=6c3b8a78bc201c67 input=2725352806399cab]*/
1195{
Benjamin Petersonce798522012-01-22 11:24:29 -05001196 _Py_IDENTIFIER(__ceil__);
Guido van Rossum13e05de2007-08-23 22:56:55 +00001197
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001198 if (!PyFloat_CheckExact(number)) {
1199 PyObject *method = _PyObject_LookupSpecial(number, &PyId___ceil__);
1200 if (method != NULL) {
1201 PyObject *result = _PyObject_CallNoArg(method);
1202 Py_DECREF(method);
1203 return result;
1204 }
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001205 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 return NULL;
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001207 }
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001208 double x = PyFloat_AsDouble(number);
1209 if (x == -1.0 && PyErr_Occurred())
1210 return NULL;
1211
1212 return PyLong_FromDouble(ceil(x));
Guido van Rossum13e05de2007-08-23 22:56:55 +00001213}
1214
Christian Heimes072c0f12008-01-03 23:01:04 +00001215FUNC2(copysign, copysign,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001216 "copysign($module, x, y, /)\n--\n\n"
1217 "Return a float with the magnitude (absolute value) of x but the sign of y.\n\n"
1218 "On platforms that support signed zeros, copysign(1.0, -0.0)\n"
1219 "returns -1.0.\n")
Christian Heimes53876d92008-04-19 00:31:39 +00001220FUNC1(cos, cos, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001221 "cos($module, x, /)\n--\n\n"
1222 "Return the cosine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001223FUNC1(cosh, cosh, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001224 "cosh($module, x, /)\n--\n\n"
1225 "Return the hyperbolic cosine of x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +00001226FUNC1A(erf, m_erf,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001227 "erf($module, x, /)\n--\n\n"
1228 "Error function at x.")
Mark Dickinson45f992a2009-12-19 11:20:49 +00001229FUNC1A(erfc, m_erfc,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001230 "erfc($module, x, /)\n--\n\n"
1231 "Complementary error function at x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001232FUNC1(exp, exp, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001233 "exp($module, x, /)\n--\n\n"
1234 "Return e raised to the power of x.")
Mark Dickinson664b5112009-12-16 20:23:42 +00001235FUNC1(expm1, m_expm1, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001236 "expm1($module, x, /)\n--\n\n"
1237 "Return exp(x)-1.\n\n"
Mark Dickinson664b5112009-12-16 20:23:42 +00001238 "This function avoids the loss of precision involved in the direct "
1239 "evaluation of exp(x)-1 for small x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001240FUNC1(fabs, fabs, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001241 "fabs($module, x, /)\n--\n\n"
1242 "Return the absolute value of the float x.")
Guido van Rossum13e05de2007-08-23 22:56:55 +00001243
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001244/*[clinic input]
1245math.floor
1246
1247 x as number: object
1248 /
1249
1250Return the floor of x as an Integral.
1251
1252This is the largest integer <= x.
1253[clinic start generated code]*/
1254
1255static PyObject *
1256math_floor(PyObject *module, PyObject *number)
1257/*[clinic end generated code: output=c6a65c4884884b8a input=63af6b5d7ebcc3d6]*/
1258{
Raymond Hettinger930f4512020-06-23 11:45:25 -07001259 double x;
1260
Benjamin Petersonce798522012-01-22 11:24:29 -05001261 _Py_IDENTIFIER(__floor__);
Guido van Rossum13e05de2007-08-23 22:56:55 +00001262
Raymond Hettinger930f4512020-06-23 11:45:25 -07001263 if (PyFloat_CheckExact(number)) {
1264 x = PyFloat_AS_DOUBLE(number);
1265 }
1266 else
1267 {
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001268 PyObject *method = _PyObject_LookupSpecial(number, &PyId___floor__);
1269 if (method != NULL) {
1270 PyObject *result = _PyObject_CallNoArg(method);
1271 Py_DECREF(method);
1272 return result;
1273 }
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001274 if (PyErr_Occurred())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 return NULL;
Raymond Hettinger930f4512020-06-23 11:45:25 -07001276 x = PyFloat_AsDouble(number);
1277 if (x == -1.0 && PyErr_Occurred())
1278 return NULL;
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001279 }
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001280 return PyLong_FromDouble(floor(x));
Guido van Rossum13e05de2007-08-23 22:56:55 +00001281}
1282
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001283FUNC1A(gamma, m_tgamma,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001284 "gamma($module, x, /)\n--\n\n"
1285 "Gamma function at x.")
Mark Dickinson05d2e082009-12-11 20:17:17 +00001286FUNC1A(lgamma, m_lgamma,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001287 "lgamma($module, x, /)\n--\n\n"
1288 "Natural logarithm of absolute value of Gamma function at x.")
Mark Dickinsonbe64d952010-07-07 16:21:29 +00001289FUNC1(log1p, m_log1p, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001290 "log1p($module, x, /)\n--\n\n"
1291 "Return the natural logarithm of 1+x (base e).\n\n"
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001292 "The result is computed in a way which is accurate for x near zero.")
Mark Dickinsona0ce3752017-04-05 18:34:27 +01001293FUNC2(remainder, m_remainder,
1294 "remainder($module, x, y, /)\n--\n\n"
1295 "Difference between x and the closest integer multiple of y.\n\n"
1296 "Return x - n*y where n*y is the closest integer multiple of y.\n"
1297 "In the case where x is exactly halfway between two multiples of\n"
1298 "y, the nearest even value of n is used. The result is always exact.")
Christian Heimes53876d92008-04-19 00:31:39 +00001299FUNC1(sin, sin, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001300 "sin($module, x, /)\n--\n\n"
1301 "Return the sine of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001302FUNC1(sinh, sinh, 1,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001303 "sinh($module, x, /)\n--\n\n"
1304 "Return the hyperbolic sine of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001305FUNC1(sqrt, sqrt, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001306 "sqrt($module, x, /)\n--\n\n"
1307 "Return the square root of x.")
Christian Heimes53876d92008-04-19 00:31:39 +00001308FUNC1(tan, tan, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001309 "tan($module, x, /)\n--\n\n"
1310 "Return the tangent of x (measured in radians).")
Christian Heimes53876d92008-04-19 00:31:39 +00001311FUNC1(tanh, tanh, 0,
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001312 "tanh($module, x, /)\n--\n\n"
1313 "Return the hyperbolic tangent of x.")
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001314
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001315/* Precision summation function as msum() by Raymond Hettinger in
1316 <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
1317 enhanced with the exact partials sum and roundoff from Mark
1318 Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
1319 See those links for more details, proofs and other references.
1320
1321 Note 1: IEEE 754R floating point semantics are assumed,
1322 but the current implementation does not re-establish special
1323 value semantics across iterations (i.e. handling -Inf + Inf).
1324
1325 Note 2: No provision is made for intermediate overflow handling;
Georg Brandlf78e02b2008-06-10 17:40:04 +00001326 therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001327 sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
1328 overflow of the first partial sum.
1329
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001330 Note 3: The intermediate values lo, yr, and hi are declared volatile so
1331 aggressive compilers won't algebraically reduce lo to always be exactly 0.0.
Georg Brandlf78e02b2008-06-10 17:40:04 +00001332 Also, the volatile declaration forces the values to be stored in memory as
1333 regular doubles instead of extended long precision (80-bit) values. This
Benjamin Petersonfea6a942008-07-02 16:11:42 +00001334 prevents double rounding because any addition or subtraction of two doubles
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 can be resolved exactly into double-sized hi and lo values. As long as the
Georg Brandlf78e02b2008-06-10 17:40:04 +00001336 hi value gets forced into a double before yr and lo are computed, the extra
1337 bits in downstream extended precision operations (x87 for example) will be
1338 exactly zero and therefore can be losslessly stored back into a double,
1339 thereby preventing double rounding.
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001340
1341 Note 4: A similar implementation is in Modules/cmathmodule.c.
1342 Be sure to update both when making changes.
1343
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001344 Note 5: The signature of math.fsum() differs from builtins.sum()
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001345 because the start argument doesn't make sense in the context of
1346 accurate summation. Since the partials table is collapsed before
1347 returning a result, sum(seq2, start=sum(seq1)) may not equal the
1348 accurate result returned by sum(itertools.chain(seq1, seq2)).
1349*/
1350
1351#define NUM_PARTIALS 32 /* initial partials array size, on stack */
1352
1353/* Extend the partials array p[] by doubling its size. */
1354static int /* non-zero on error */
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001355_fsum_realloc(double **p_ptr, Py_ssize_t n,
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001356 double *ps, Py_ssize_t *m_ptr)
1357{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 void *v = NULL;
1359 Py_ssize_t m = *m_ptr;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 m += m; /* double */
Victor Stinner049e5092014-08-17 22:20:00 +02001362 if (n < m && (size_t)m < ((size_t)PY_SSIZE_T_MAX / sizeof(double))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 double *p = *p_ptr;
1364 if (p == ps) {
1365 v = PyMem_Malloc(sizeof(double) * m);
1366 if (v != NULL)
1367 memcpy(v, ps, sizeof(double) * n);
1368 }
1369 else
1370 v = PyMem_Realloc(p, sizeof(double) * m);
1371 }
1372 if (v == NULL) { /* size overflow or no memory */
1373 PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
1374 return 1;
1375 }
1376 *p_ptr = (double*) v;
1377 *m_ptr = m;
1378 return 0;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001379}
1380
1381/* Full precision summation of a sequence of floats.
1382
1383 def msum(iterable):
1384 partials = [] # sorted, non-overlapping partial sums
1385 for x in iterable:
Mark Dickinsonfdb0acc2010-06-25 20:22:24 +00001386 i = 0
1387 for y in partials:
1388 if abs(x) < abs(y):
1389 x, y = y, x
1390 hi = x + y
1391 lo = y - (hi - x)
1392 if lo:
1393 partials[i] = lo
1394 i += 1
1395 x = hi
1396 partials[i:] = [x]
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001397 return sum_exact(partials)
1398
1399 Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
1400 are exactly equal to x+y. The inner loop applies hi/lo summation to each
1401 partial so that the list of partial sums remains exact.
1402
1403 Sum_exact() adds the partial sums exactly and correctly rounds the final
1404 result (using the round-half-to-even rule). The items in partials remain
1405 non-zero, non-special, non-overlapping and strictly increasing in
1406 magnitude, but possibly not all having the same sign.
1407
1408 Depends on IEEE 754 arithmetic guarantees and half-even rounding.
1409*/
1410
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02001411/*[clinic input]
1412math.fsum
1413
1414 seq: object
1415 /
1416
1417Return an accurate floating point sum of values in the iterable seq.
1418
1419Assumes IEEE-754 floating point arithmetic.
1420[clinic start generated code]*/
1421
1422static PyObject *
1423math_fsum(PyObject *module, PyObject *seq)
1424/*[clinic end generated code: output=ba5c672b87fe34fc input=c51b7d8caf6f6e82]*/
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 PyObject *item, *iter, *sum = NULL;
1427 Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
1428 double x, y, t, ps[NUM_PARTIALS], *p = ps;
1429 double xsave, special_sum = 0.0, inf_sum = 0.0;
1430 volatile double hi, yr, lo;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 iter = PyObject_GetIter(seq);
1433 if (iter == NULL)
1434 return NULL;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 for(;;) { /* for x in iterable */
1437 assert(0 <= n && n <= m);
1438 assert((m == NUM_PARTIALS && p == ps) ||
1439 (m > NUM_PARTIALS && p != NULL));
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 item = PyIter_Next(iter);
1442 if (item == NULL) {
1443 if (PyErr_Occurred())
1444 goto _fsum_error;
1445 break;
1446 }
Raymond Hettingercfd735e2019-01-29 20:39:53 -08001447 ASSIGN_DOUBLE(x, item, error_with_item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 Py_DECREF(item);
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 xsave = x;
1451 for (i = j = 0; j < n; j++) { /* for y in partials */
1452 y = p[j];
1453 if (fabs(x) < fabs(y)) {
1454 t = x; x = y; y = t;
1455 }
1456 hi = x + y;
1457 yr = hi - x;
1458 lo = y - yr;
1459 if (lo != 0.0)
1460 p[i++] = lo;
1461 x = hi;
1462 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 n = i; /* ps[i:] = [x] */
1465 if (x != 0.0) {
1466 if (! Py_IS_FINITE(x)) {
1467 /* a nonfinite x could arise either as
1468 a result of intermediate overflow, or
1469 as a result of a nan or inf in the
1470 summands */
1471 if (Py_IS_FINITE(xsave)) {
1472 PyErr_SetString(PyExc_OverflowError,
1473 "intermediate overflow in fsum");
1474 goto _fsum_error;
1475 }
1476 if (Py_IS_INFINITY(xsave))
1477 inf_sum += xsave;
1478 special_sum += xsave;
1479 /* reset partials */
1480 n = 0;
1481 }
1482 else if (n >= m && _fsum_realloc(&p, n, ps, &m))
1483 goto _fsum_error;
1484 else
1485 p[n++] = x;
1486 }
1487 }
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 if (special_sum != 0.0) {
1490 if (Py_IS_NAN(inf_sum))
1491 PyErr_SetString(PyExc_ValueError,
1492 "-inf + inf in fsum");
1493 else
1494 sum = PyFloat_FromDouble(special_sum);
1495 goto _fsum_error;
1496 }
Mark Dickinsonaa7633a2008-08-01 08:16:13 +00001497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 hi = 0.0;
1499 if (n > 0) {
1500 hi = p[--n];
1501 /* sum_exact(ps, hi) from the top, stop when the sum becomes
1502 inexact. */
1503 while (n > 0) {
1504 x = hi;
1505 y = p[--n];
1506 assert(fabs(y) < fabs(x));
1507 hi = x + y;
1508 yr = hi - x;
1509 lo = y - yr;
1510 if (lo != 0.0)
1511 break;
1512 }
1513 /* Make half-even rounding work across multiple partials.
1514 Needed so that sum([1e-16, 1, 1e16]) will round-up the last
1515 digit to two instead of down to zero (the 1e-16 makes the 1
1516 slightly closer to two). With a potential 1 ULP rounding
1517 error fixed-up, math.fsum() can guarantee commutativity. */
1518 if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
1519 (lo > 0.0 && p[n-1] > 0.0))) {
1520 y = lo * 2.0;
1521 x = hi + y;
1522 yr = x - hi;
1523 if (y == yr)
1524 hi = x;
1525 }
1526 }
1527 sum = PyFloat_FromDouble(hi);
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001528
Raymond Hettingercfd735e2019-01-29 20:39:53 -08001529 _fsum_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 Py_DECREF(iter);
1531 if (p != ps)
1532 PyMem_Free(p);
1533 return sum;
Raymond Hettingercfd735e2019-01-29 20:39:53 -08001534
1535 error_with_item:
1536 Py_DECREF(item);
1537 goto _fsum_error;
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001538}
1539
1540#undef NUM_PARTIALS
1541
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001542
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001543static unsigned long
1544count_set_bits(unsigned long n)
1545{
1546 unsigned long count = 0;
1547 while (n != 0) {
1548 ++count;
1549 n &= n - 1; /* clear least significant bit */
1550 }
1551 return count;
1552}
1553
Mark Dickinson73934b92019-05-18 12:29:50 +01001554/* Integer square root
1555
1556Given a nonnegative integer `n`, we want to compute the largest integer
1557`a` for which `a * a <= n`, or equivalently the integer part of the exact
1558square root of `n`.
1559
1560We use an adaptive-precision pure-integer version of Newton's iteration. Given
1561a positive integer `n`, the algorithm produces at each iteration an integer
1562approximation `a` to the square root of `n >> s` for some even integer `s`,
1563with `s` decreasing as the iterations progress. On the final iteration, `s` is
1564zero and we have an approximation to the square root of `n` itself.
1565
1566At every step, the approximation `a` is strictly within 1.0 of the true square
1567root, so we have
1568
1569 (a - 1)**2 < (n >> s) < (a + 1)**2
1570
1571After the final iteration, a check-and-correct step is needed to determine
1572whether `a` or `a - 1` gives the desired integer square root of `n`.
1573
1574The algorithm is remarkable in its simplicity. There's no need for a
1575per-iteration check-and-correct step, and termination is straightforward: the
1576number of iterations is known in advance (it's exactly `floor(log2(log2(n)))`
1577for `n > 1`). The only tricky part of the correctness proof is in establishing
1578that the bound `(a - 1)**2 < (n >> s) < (a + 1)**2` is maintained from one
1579iteration to the next. A sketch of the proof of this is given below.
1580
1581In addition to the proof sketch, a formal, computer-verified proof
1582of correctness (using Lean) of an equivalent recursive algorithm can be found
1583here:
1584
1585 https://github.com/mdickinson/snippets/blob/master/proofs/isqrt/src/isqrt.lean
1586
1587
1588Here's Python code equivalent to the C implementation below:
1589
1590 def isqrt(n):
1591 """
1592 Return the integer part of the square root of the input.
1593 """
1594 n = operator.index(n)
1595
1596 if n < 0:
1597 raise ValueError("isqrt() argument must be nonnegative")
1598 if n == 0:
1599 return 0
1600
1601 c = (n.bit_length() - 1) // 2
1602 a = 1
1603 d = 0
1604 for s in reversed(range(c.bit_length())):
Mark Dickinson2dfeaa92019-06-16 17:53:21 +01001605 # Loop invariant: (a-1)**2 < (n >> 2*(c - d)) < (a+1)**2
Mark Dickinson73934b92019-05-18 12:29:50 +01001606 e = d
1607 d = c >> s
1608 a = (a << d - e - 1) + (n >> 2*c - e - d + 1) // a
Mark Dickinson73934b92019-05-18 12:29:50 +01001609
1610 return a - (a*a > n)
1611
1612
1613Sketch of proof of correctness
1614------------------------------
1615
1616The delicate part of the correctness proof is showing that the loop invariant
1617is preserved from one iteration to the next. That is, just before the line
1618
1619 a = (a << d - e - 1) + (n >> 2*c - e - d + 1) // a
1620
1621is executed in the above code, we know that
1622
1623 (1) (a - 1)**2 < (n >> 2*(c - e)) < (a + 1)**2.
1624
1625(since `e` is always the value of `d` from the previous iteration). We must
1626prove that after that line is executed, we have
1627
1628 (a - 1)**2 < (n >> 2*(c - d)) < (a + 1)**2
1629
Min ho Kimf7d72e42019-07-06 07:39:32 +10001630To facilitate the proof, we make some changes of notation. Write `m` for
Mark Dickinson73934b92019-05-18 12:29:50 +01001631`n >> 2*(c-d)`, and write `b` for the new value of `a`, so
1632
1633 b = (a << d - e - 1) + (n >> 2*c - e - d + 1) // a
1634
1635or equivalently:
1636
1637 (2) b = (a << d - e - 1) + (m >> d - e + 1) // a
1638
1639Then we can rewrite (1) as:
1640
1641 (3) (a - 1)**2 < (m >> 2*(d - e)) < (a + 1)**2
1642
1643and we must show that (b - 1)**2 < m < (b + 1)**2.
1644
1645From this point on, we switch to mathematical notation, so `/` means exact
1646division rather than integer division and `^` is used for exponentiation. We
1647use the `√` symbol for the exact square root. In (3), we can remove the
1648implicit floor operation to give:
1649
1650 (4) (a - 1)^2 < m / 4^(d - e) < (a + 1)^2
1651
1652Taking square roots throughout (4), scaling by `2^(d-e)`, and rearranging gives
1653
1654 (5) 0 <= | 2^(d-e)a - √m | < 2^(d-e)
1655
1656Squaring and dividing through by `2^(d-e+1) a` gives
1657
1658 (6) 0 <= 2^(d-e-1) a + m / (2^(d-e+1) a) - √m < 2^(d-e-1) / a
1659
1660We'll show below that `2^(d-e-1) <= a`. Given that, we can replace the
1661right-hand side of (6) with `1`, and now replacing the central
1662term `m / (2^(d-e+1) a)` with its floor in (6) gives
1663
1664 (7) -1 < 2^(d-e-1) a + m // 2^(d-e+1) a - √m < 1
1665
1666Or equivalently, from (2):
1667
1668 (7) -1 < b - √m < 1
1669
1670and rearranging gives that `(b-1)^2 < m < (b+1)^2`, which is what we needed
1671to prove.
1672
1673We're not quite done: we still have to prove the inequality `2^(d - e - 1) <=
1674a` that was used to get line (7) above. From the definition of `c`, we have
1675`4^c <= n`, which implies
1676
1677 (8) 4^d <= m
1678
1679also, since `e == d >> 1`, `d` is at most `2e + 1`, from which it follows
1680that `2d - 2e - 1 <= d` and hence that
1681
1682 (9) 4^(2d - 2e - 1) <= m
1683
1684Dividing both sides by `4^(d - e)` gives
1685
1686 (10) 4^(d - e - 1) <= m / 4^(d - e)
1687
1688But we know from (4) that `m / 4^(d-e) < (a + 1)^2`, hence
1689
1690 (11) 4^(d - e - 1) < (a + 1)^2
1691
1692Now taking square roots of both sides and observing that both `2^(d-e-1)` and
1693`a` are integers gives `2^(d - e - 1) <= a`, which is what we needed. This
1694completes the proof sketch.
1695
1696*/
1697
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001698
1699/* Approximate square root of a large 64-bit integer.
1700
1701 Given `n` satisfying `2**62 <= n < 2**64`, return `a`
1702 satisfying `(a - 1)**2 < n < (a + 1)**2`. */
1703
1704static uint64_t
1705_approximate_isqrt(uint64_t n)
1706{
1707 uint32_t u = 1U + (n >> 62);
1708 u = (u << 1) + (n >> 59) / u;
1709 u = (u << 3) + (n >> 53) / u;
1710 u = (u << 7) + (n >> 41) / u;
1711 return (u << 15) + (n >> 17) / u;
1712}
1713
Mark Dickinson73934b92019-05-18 12:29:50 +01001714/*[clinic input]
1715math.isqrt
1716
1717 n: object
1718 /
1719
1720Return the integer part of the square root of the input.
1721[clinic start generated code]*/
1722
1723static PyObject *
1724math_isqrt(PyObject *module, PyObject *n)
1725/*[clinic end generated code: output=35a6f7f980beab26 input=5b6e7ae4fa6c43d6]*/
1726{
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001727 int a_too_large, c_bit_length;
Mark Dickinson73934b92019-05-18 12:29:50 +01001728 size_t c, d;
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001729 uint64_t m, u;
Mark Dickinson73934b92019-05-18 12:29:50 +01001730 PyObject *a = NULL, *b;
1731
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001732 n = _PyNumber_Index(n);
Mark Dickinson73934b92019-05-18 12:29:50 +01001733 if (n == NULL) {
1734 return NULL;
1735 }
1736
1737 if (_PyLong_Sign(n) < 0) {
1738 PyErr_SetString(
1739 PyExc_ValueError,
1740 "isqrt() argument must be nonnegative");
1741 goto error;
1742 }
1743 if (_PyLong_Sign(n) == 0) {
1744 Py_DECREF(n);
1745 return PyLong_FromLong(0);
1746 }
1747
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001748 /* c = (n.bit_length() - 1) // 2 */
Mark Dickinson73934b92019-05-18 12:29:50 +01001749 c = _PyLong_NumBits(n);
1750 if (c == (size_t)(-1)) {
1751 goto error;
1752 }
1753 c = (c - 1U) / 2U;
1754
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001755 /* Fast path: if c <= 31 then n < 2**64 and we can compute directly with a
1756 fast, almost branch-free algorithm. In the final correction, we use `u*u
1757 - 1 >= m` instead of the simpler `u*u > m` in order to get the correct
1758 result in the corner case where `u=2**32`. */
1759 if (c <= 31U) {
1760 m = (uint64_t)PyLong_AsUnsignedLongLong(n);
1761 Py_DECREF(n);
1762 if (m == (uint64_t)(-1) && PyErr_Occurred()) {
1763 return NULL;
1764 }
1765 u = _approximate_isqrt(m << (62U - 2U*c)) >> (31U - c);
1766 u -= u * u - 1U >= m;
1767 return PyLong_FromUnsignedLongLong((unsigned long long)u);
Mark Dickinson73934b92019-05-18 12:29:50 +01001768 }
1769
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001770 /* Slow path: n >= 2**64. We perform the first five iterations in C integer
1771 arithmetic, then switch to using Python long integers. */
1772
1773 /* From n >= 2**64 it follows that c.bit_length() >= 6. */
1774 c_bit_length = 6;
1775 while ((c >> c_bit_length) > 0U) {
1776 ++c_bit_length;
1777 }
1778
1779 /* Initialise d and a. */
1780 d = c >> (c_bit_length - 5);
1781 b = _PyLong_Rshift(n, 2U*c - 62U);
1782 if (b == NULL) {
1783 goto error;
1784 }
1785 m = (uint64_t)PyLong_AsUnsignedLongLong(b);
1786 Py_DECREF(b);
1787 if (m == (uint64_t)(-1) && PyErr_Occurred()) {
1788 goto error;
1789 }
1790 u = _approximate_isqrt(m) >> (31U - d);
1791 a = PyLong_FromUnsignedLongLong((unsigned long long)u);
Mark Dickinson73934b92019-05-18 12:29:50 +01001792 if (a == NULL) {
1793 goto error;
1794 }
Mark Dickinson5c08ce92019-05-19 17:51:56 +01001795
1796 for (int s = c_bit_length - 6; s >= 0; --s) {
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03001797 PyObject *q;
Mark Dickinson73934b92019-05-18 12:29:50 +01001798 size_t e = d;
1799
1800 d = c >> s;
1801
1802 /* q = (n >> 2*c - e - d + 1) // a */
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03001803 q = _PyLong_Rshift(n, 2U*c - d - e + 1U);
Mark Dickinson73934b92019-05-18 12:29:50 +01001804 if (q == NULL) {
1805 goto error;
1806 }
1807 Py_SETREF(q, PyNumber_FloorDivide(q, a));
1808 if (q == NULL) {
1809 goto error;
1810 }
1811
1812 /* a = (a << d - 1 - e) + q */
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03001813 Py_SETREF(a, _PyLong_Lshift(a, d - 1U - e));
Mark Dickinson73934b92019-05-18 12:29:50 +01001814 if (a == NULL) {
1815 Py_DECREF(q);
1816 goto error;
1817 }
1818 Py_SETREF(a, PyNumber_Add(a, q));
1819 Py_DECREF(q);
1820 if (a == NULL) {
1821 goto error;
1822 }
1823 }
1824
1825 /* The correct result is either a or a - 1. Figure out which, and
1826 decrement a if necessary. */
1827
1828 /* a_too_large = n < a * a */
1829 b = PyNumber_Multiply(a, a);
1830 if (b == NULL) {
1831 goto error;
1832 }
1833 a_too_large = PyObject_RichCompareBool(n, b, Py_LT);
1834 Py_DECREF(b);
1835 if (a_too_large == -1) {
1836 goto error;
1837 }
1838
1839 if (a_too_large) {
1840 Py_SETREF(a, PyNumber_Subtract(a, _PyLong_One));
1841 }
1842 Py_DECREF(n);
1843 return a;
1844
1845 error:
1846 Py_XDECREF(a);
1847 Py_DECREF(n);
1848 return NULL;
1849}
1850
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001851/* Divide-and-conquer factorial algorithm
1852 *
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07001853 * Based on the formula and pseudo-code provided at:
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001854 * http://www.luschny.de/math/factorial/binarysplitfact.html
1855 *
1856 * Faster algorithms exist, but they're more complicated and depend on
Ezio Melotti9527afd2010-07-08 15:03:02 +00001857 * a fast prime factorization algorithm.
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001858 *
1859 * Notes on the algorithm
1860 * ----------------------
1861 *
1862 * factorial(n) is written in the form 2**k * m, with m odd. k and m are
1863 * computed separately, and then combined using a left shift.
1864 *
1865 * The function factorial_odd_part computes the odd part m (i.e., the greatest
1866 * odd divisor) of factorial(n), using the formula:
1867 *
1868 * factorial_odd_part(n) =
1869 *
1870 * product_{i >= 0} product_{0 < j <= n / 2**i, j odd} j
1871 *
1872 * Example: factorial_odd_part(20) =
1873 *
1874 * (1) *
1875 * (1) *
1876 * (1 * 3 * 5) *
1877 * (1 * 3 * 5 * 7 * 9)
1878 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1879 *
1880 * Here i goes from large to small: the first term corresponds to i=4 (any
1881 * larger i gives an empty product), and the last term corresponds to i=0.
1882 * Each term can be computed from the last by multiplying by the extra odd
1883 * numbers required: e.g., to get from the penultimate term to the last one,
1884 * we multiply by (11 * 13 * 15 * 17 * 19).
1885 *
1886 * To see a hint of why this formula works, here are the same numbers as above
1887 * but with the even parts (i.e., the appropriate powers of 2) included. For
1888 * each subterm in the product for i, we multiply that subterm by 2**i:
1889 *
1890 * factorial(20) =
1891 *
1892 * (16) *
1893 * (8) *
1894 * (4 * 12 * 20) *
1895 * (2 * 6 * 10 * 14 * 18) *
1896 * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
1897 *
1898 * The factorial_partial_product function computes the product of all odd j in
1899 * range(start, stop) for given start and stop. It's used to compute the
1900 * partial products like (11 * 13 * 15 * 17 * 19) in the example above. It
1901 * operates recursively, repeatedly splitting the range into two roughly equal
1902 * pieces until the subranges are small enough to be computed using only C
1903 * integer arithmetic.
1904 *
1905 * The two-valuation k (i.e., the exponent of the largest power of 2 dividing
1906 * the factorial) is computed independently in the main math_factorial
1907 * function. By standard results, its value is:
1908 *
1909 * two_valuation = n//2 + n//4 + n//8 + ....
1910 *
1911 * It can be shown (e.g., by complete induction on n) that two_valuation is
1912 * equal to n - count_set_bits(n), where count_set_bits(n) gives the number of
1913 * '1'-bits in the binary expansion of n.
1914 */
1915
1916/* factorial_partial_product: Compute product(range(start, stop, 2)) using
1917 * divide and conquer. Assumes start and stop are odd and stop > start.
1918 * max_bits must be >= bit_length(stop - 2). */
1919
1920static PyObject *
1921factorial_partial_product(unsigned long start, unsigned long stop,
1922 unsigned long max_bits)
1923{
1924 unsigned long midpoint, num_operands;
1925 PyObject *left = NULL, *right = NULL, *result = NULL;
1926
1927 /* If the return value will fit an unsigned long, then we can
1928 * multiply in a tight, fast loop where each multiply is O(1).
1929 * Compute an upper bound on the number of bits required to store
1930 * the answer.
1931 *
1932 * Storing some integer z requires floor(lg(z))+1 bits, which is
1933 * conveniently the value returned by bit_length(z). The
1934 * product x*y will require at most
1935 * bit_length(x) + bit_length(y) bits to store, based
1936 * on the idea that lg product = lg x + lg y.
1937 *
1938 * We know that stop - 2 is the largest number to be multiplied. From
1939 * there, we have: bit_length(answer) <= num_operands *
1940 * bit_length(stop - 2)
1941 */
1942
1943 num_operands = (stop - start) / 2;
1944 /* The "num_operands <= 8 * SIZEOF_LONG" check guards against the
1945 * unlikely case of an overflow in num_operands * max_bits. */
1946 if (num_operands <= 8 * SIZEOF_LONG &&
1947 num_operands * max_bits <= 8 * SIZEOF_LONG) {
1948 unsigned long j, total;
1949 for (total = start, j = start + 2; j < stop; j += 2)
1950 total *= j;
1951 return PyLong_FromUnsignedLong(total);
1952 }
1953
1954 /* find midpoint of range(start, stop), rounded up to next odd number. */
1955 midpoint = (start + num_operands) | 1;
1956 left = factorial_partial_product(start, midpoint,
Niklas Fiekasc5b79002020-01-16 15:09:19 +01001957 _Py_bit_length(midpoint - 2));
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001958 if (left == NULL)
1959 goto error;
1960 right = factorial_partial_product(midpoint, stop, max_bits);
1961 if (right == NULL)
1962 goto error;
1963 result = PyNumber_Multiply(left, right);
1964
1965 error:
1966 Py_XDECREF(left);
1967 Py_XDECREF(right);
1968 return result;
1969}
1970
1971/* factorial_odd_part: compute the odd part of factorial(n). */
1972
1973static PyObject *
1974factorial_odd_part(unsigned long n)
1975{
1976 long i;
1977 unsigned long v, lower, upper;
1978 PyObject *partial, *tmp, *inner, *outer;
1979
1980 inner = PyLong_FromLong(1);
1981 if (inner == NULL)
1982 return NULL;
1983 outer = inner;
1984 Py_INCREF(outer);
1985
1986 upper = 3;
Niklas Fiekasc5b79002020-01-16 15:09:19 +01001987 for (i = _Py_bit_length(n) - 2; i >= 0; i--) {
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001988 v = n >> i;
1989 if (v <= 2)
1990 continue;
1991 lower = upper;
1992 /* (v + 1) | 1 = least odd integer strictly larger than n / 2**i */
1993 upper = (v + 1) | 1;
1994 /* Here inner is the product of all odd integers j in the range (0,
1995 n/2**(i+1)]. The factorial_partial_product call below gives the
1996 product of all odd integers j in the range (n/2**(i+1), n/2**i]. */
Niklas Fiekasc5b79002020-01-16 15:09:19 +01001997 partial = factorial_partial_product(lower, upper, _Py_bit_length(upper-2));
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00001998 /* inner *= partial */
1999 if (partial == NULL)
2000 goto error;
2001 tmp = PyNumber_Multiply(inner, partial);
2002 Py_DECREF(partial);
2003 if (tmp == NULL)
2004 goto error;
2005 Py_DECREF(inner);
2006 inner = tmp;
2007 /* Now inner is the product of all odd integers j in the range (0,
2008 n/2**i], giving the inner product in the formula above. */
2009
2010 /* outer *= inner; */
2011 tmp = PyNumber_Multiply(outer, inner);
2012 if (tmp == NULL)
2013 goto error;
2014 Py_DECREF(outer);
2015 outer = tmp;
2016 }
Mark Dickinson76464492012-10-25 10:46:28 +01002017 Py_DECREF(inner);
2018 return outer;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002019
2020 error:
2021 Py_DECREF(outer);
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002022 Py_DECREF(inner);
Mark Dickinson76464492012-10-25 10:46:28 +01002023 return NULL;
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002024}
2025
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002026
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002027/* Lookup table for small factorial values */
2028
2029static const unsigned long SmallFactorials[] = {
2030 1, 1, 2, 6, 24, 120, 720, 5040, 40320,
2031 362880, 3628800, 39916800, 479001600,
2032#if SIZEOF_LONG >= 8
2033 6227020800, 87178291200, 1307674368000,
2034 20922789888000, 355687428096000, 6402373705728000,
2035 121645100408832000, 2432902008176640000
2036#endif
2037};
2038
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002039/*[clinic input]
2040math.factorial
2041
2042 x as arg: object
2043 /
2044
2045Find x!.
2046
2047Raise a ValueError if x is negative or non-integral.
2048[clinic start generated code]*/
2049
Barry Warsaw8b43b191996-12-09 22:32:36 +00002050static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002051math_factorial(PyObject *module, PyObject *arg)
2052/*[clinic end generated code: output=6686f26fae00e9ca input=6d1c8105c0d91fb4]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002053{
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03002054 long x, two_valuation;
Mark Dickinson5990d282014-04-10 09:29:39 -04002055 int overflow;
Serhiy Storchaka578c3952020-05-26 18:43:38 +03002056 PyObject *result, *odd_part;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002057
Serhiy Storchaka578c3952020-05-26 18:43:38 +03002058 x = PyLong_AsLongAndOverflow(arg, &overflow);
Mark Dickinson5990d282014-04-10 09:29:39 -04002059 if (x == -1 && PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 return NULL;
Mark Dickinson5990d282014-04-10 09:29:39 -04002061 }
2062 else if (overflow == 1) {
2063 PyErr_Format(PyExc_OverflowError,
2064 "factorial() argument should not exceed %ld",
2065 LONG_MAX);
2066 return NULL;
2067 }
2068 else if (overflow == -1 || x < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 PyErr_SetString(PyExc_ValueError,
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002070 "factorial() not defined for negative values");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 return NULL;
2072 }
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002073
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002074 /* use lookup table if x is small */
Victor Stinner63941882011-09-29 00:42:28 +02002075 if (x < (long)Py_ARRAY_LENGTH(SmallFactorials))
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002076 return PyLong_FromUnsignedLong(SmallFactorials[x]);
2077
2078 /* else express in the form odd_part * 2**two_valuation, and compute as
2079 odd_part << two_valuation. */
2080 odd_part = factorial_odd_part(x);
2081 if (odd_part == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 return NULL;
Serhiy Storchakaa5119e72019-05-19 14:14:38 +03002083 two_valuation = x - count_set_bits(x);
2084 result = _PyLong_Lshift(odd_part, two_valuation);
Mark Dickinson4c8a9a22010-05-15 17:02:38 +00002085 Py_DECREF(odd_part);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 return result;
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002087}
2088
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002089
2090/*[clinic input]
2091math.trunc
2092
2093 x: object
2094 /
2095
2096Truncates the Real x to the nearest Integral toward 0.
2097
2098Uses the __trunc__ magic method.
2099[clinic start generated code]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002100
2101static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002102math_trunc(PyObject *module, PyObject *x)
2103/*[clinic end generated code: output=34b9697b707e1031 input=2168b34e0a09134d]*/
Christian Heimes400adb02008-02-01 08:12:03 +00002104{
Benjamin Petersonce798522012-01-22 11:24:29 -05002105 _Py_IDENTIFIER(__trunc__);
Benjamin Petersonb0125892010-07-02 13:35:17 +00002106 PyObject *trunc, *result;
Christian Heimes400adb02008-02-01 08:12:03 +00002107
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02002108 if (PyFloat_CheckExact(x)) {
2109 return PyFloat_Type.tp_as_number->nb_int(x);
2110 }
2111
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002112 if (Py_TYPE(x)->tp_dict == NULL) {
2113 if (PyType_Ready(Py_TYPE(x)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 return NULL;
2115 }
Christian Heimes400adb02008-02-01 08:12:03 +00002116
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002117 trunc = _PyObject_LookupSpecial(x, &PyId___trunc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 if (trunc == NULL) {
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00002119 if (!PyErr_Occurred())
2120 PyErr_Format(PyExc_TypeError,
2121 "type %.100s doesn't define __trunc__ method",
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002122 Py_TYPE(x)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 return NULL;
2124 }
Victor Stinnerf17c3de2016-12-06 18:46:19 +01002125 result = _PyObject_CallNoArg(trunc);
Benjamin Petersonb0125892010-07-02 13:35:17 +00002126 Py_DECREF(trunc);
2127 return result;
Christian Heimes400adb02008-02-01 08:12:03 +00002128}
2129
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002130
2131/*[clinic input]
2132math.frexp
2133
2134 x: double
2135 /
2136
2137Return the mantissa and exponent of x, as pair (m, e).
2138
2139m is a float and e is an int, such that x = m * 2.**e.
2140If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.
2141[clinic start generated code]*/
Christian Heimes400adb02008-02-01 08:12:03 +00002142
2143static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002144math_frexp_impl(PyObject *module, double x)
2145/*[clinic end generated code: output=03e30d252a15ad4a input=96251c9e208bc6e9]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00002146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 /* deal with special cases directly, to sidestep platform
2149 differences */
2150 if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
2151 i = 0;
2152 }
2153 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 x = frexp(x, &i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 }
2156 return Py_BuildValue("(di)", x, i);
Guido van Rossumd18ad581991-10-24 14:57:21 +00002157}
2158
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002159
2160/*[clinic input]
2161math.ldexp
2162
2163 x: double
2164 i: object
2165 /
2166
2167Return x * (2**i).
2168
2169This is essentially the inverse of frexp().
2170[clinic start generated code]*/
Guido van Rossumc6e22901998-12-04 19:26:43 +00002171
Barry Warsaw8b43b191996-12-09 22:32:36 +00002172static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002173math_ldexp_impl(PyObject *module, double x, PyObject *i)
2174/*[clinic end generated code: output=b6892f3c2df9cc6a input=17d5970c1a40a8c1]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00002175{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002176 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 long exp;
2178 int overflow;
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00002179
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002180 if (PyLong_Check(i)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 /* on overflow, replace exponent with either LONG_MAX
2182 or LONG_MIN, depending on the sign. */
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002183 exp = PyLong_AsLongAndOverflow(i, &overflow);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 if (exp == -1 && PyErr_Occurred())
2185 return NULL;
2186 if (overflow)
2187 exp = overflow < 0 ? LONG_MIN : LONG_MAX;
2188 }
2189 else {
2190 PyErr_SetString(PyExc_TypeError,
Serhiy Storchaka95949422013-08-27 19:40:23 +03002191 "Expected an int as second argument to ldexp.");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 return NULL;
2193 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00002194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 if (x == 0. || !Py_IS_FINITE(x)) {
2196 /* NaNs, zeros and infinities are returned unchanged */
2197 r = x;
2198 errno = 0;
2199 } else if (exp > INT_MAX) {
2200 /* overflow */
2201 r = copysign(Py_HUGE_VAL, x);
2202 errno = ERANGE;
2203 } else if (exp < INT_MIN) {
2204 /* underflow to +-0 */
2205 r = copysign(0., x);
2206 errno = 0;
2207 } else {
2208 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 r = ldexp(x, (int)exp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 if (Py_IS_INFINITY(r))
2211 errno = ERANGE;
2212 }
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00002213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 if (errno && is_error(r))
2215 return NULL;
2216 return PyFloat_FromDouble(r);
Guido van Rossumd18ad581991-10-24 14:57:21 +00002217}
2218
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002219
2220/*[clinic input]
2221math.modf
2222
2223 x: double
2224 /
2225
2226Return the fractional and integer parts of x.
2227
2228Both results carry the sign of x and are floats.
2229[clinic start generated code]*/
Guido van Rossumc6e22901998-12-04 19:26:43 +00002230
Barry Warsaw8b43b191996-12-09 22:32:36 +00002231static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002232math_modf_impl(PyObject *module, double x)
2233/*[clinic end generated code: output=90cee0260014c3c0 input=b4cfb6786afd9035]*/
Guido van Rossumd18ad581991-10-24 14:57:21 +00002234{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002235 double y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 /* some platforms don't do the right thing for NaNs and
2237 infinities, so we take care of special cases directly. */
2238 if (!Py_IS_FINITE(x)) {
2239 if (Py_IS_INFINITY(x))
2240 return Py_BuildValue("(dd)", copysign(0., x), x);
2241 else if (Py_IS_NAN(x))
2242 return Py_BuildValue("(dd)", x, x);
2243 }
Christian Heimesa342c012008-04-20 21:01:16 +00002244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 x = modf(x, &y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 return Py_BuildValue("(dd)", x, y);
Guido van Rossumd18ad581991-10-24 14:57:21 +00002248}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002249
Guido van Rossumc6e22901998-12-04 19:26:43 +00002250
Serhiy Storchaka95949422013-08-27 19:40:23 +03002251/* A decent logarithm is easy to compute even for huge ints, but libm can't
Tim Peters78526162001-09-05 00:53:45 +00002252 do that by itself -- loghelper can. func is log or log10, and name is
Serhiy Storchaka95949422013-08-27 19:40:23 +03002253 "log" or "log10". Note that overflow of the result isn't possible: an int
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002254 can contain no more than INT_MAX * SHIFT bits, so has value certainly less
2255 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 +00002256 small enough to fit in an IEEE single. log and log10 are even smaller.
Serhiy Storchaka95949422013-08-27 19:40:23 +03002257 However, intermediate overflow is possible for an int if the number of bits
2258 in that int is larger than PY_SSIZE_T_MAX. */
Tim Peters78526162001-09-05 00:53:45 +00002259
2260static PyObject*
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002261loghelper(PyObject* arg, double (*func)(double), const char *funcname)
Tim Peters78526162001-09-05 00:53:45 +00002262{
Serhiy Storchaka95949422013-08-27 19:40:23 +03002263 /* If it is int, do it ourselves. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 if (PyLong_Check(arg)) {
Mark Dickinsonc6037172010-09-29 19:06:36 +00002265 double x, result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 Py_ssize_t e;
Mark Dickinsonc6037172010-09-29 19:06:36 +00002267
2268 /* Negative or zero inputs give a ValueError. */
2269 if (Py_SIZE(arg) <= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 PyErr_SetString(PyExc_ValueError,
2271 "math domain error");
2272 return NULL;
2273 }
Mark Dickinsonfa41e602010-09-28 07:22:27 +00002274
Mark Dickinsonc6037172010-09-29 19:06:36 +00002275 x = PyLong_AsDouble(arg);
2276 if (x == -1.0 && PyErr_Occurred()) {
2277 if (!PyErr_ExceptionMatches(PyExc_OverflowError))
2278 return NULL;
2279 /* Here the conversion to double overflowed, but it's possible
2280 to compute the log anyway. Clear the exception and continue. */
2281 PyErr_Clear();
2282 x = _PyLong_Frexp((PyLongObject *)arg, &e);
2283 if (x == -1.0 && PyErr_Occurred())
2284 return NULL;
2285 /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */
2286 result = func(x) + func(2.0) * e;
2287 }
2288 else
2289 /* Successfully converted x to a double. */
2290 result = func(x);
2291 return PyFloat_FromDouble(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 }
Tim Peters78526162001-09-05 00:53:45 +00002293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 /* Else let libm handle it by itself. */
2295 return math_1(arg, func, 0);
Tim Peters78526162001-09-05 00:53:45 +00002296}
2297
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002298
2299/*[clinic input]
2300math.log
2301
2302 x: object
2303 [
2304 base: object(c_default="NULL") = math.e
2305 ]
2306 /
2307
2308Return the logarithm of x to the given base.
2309
2310If the base not specified, returns the natural logarithm (base e) of x.
2311[clinic start generated code]*/
2312
Tim Peters78526162001-09-05 00:53:45 +00002313static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002314math_log_impl(PyObject *module, PyObject *x, int group_right_1,
2315 PyObject *base)
2316/*[clinic end generated code: output=7b5a39e526b73fc9 input=0f62d5726cbfebbd]*/
Tim Peters78526162001-09-05 00:53:45 +00002317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 PyObject *num, *den;
2319 PyObject *ans;
Raymond Hettinger866964c2002-12-14 19:51:34 +00002320
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002321 num = loghelper(x, m_log, "log");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 if (num == NULL || base == NULL)
2323 return num;
Raymond Hettinger866964c2002-12-14 19:51:34 +00002324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 den = loghelper(base, m_log, "log");
2326 if (den == NULL) {
2327 Py_DECREF(num);
2328 return NULL;
2329 }
Raymond Hettinger866964c2002-12-14 19:51:34 +00002330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 ans = PyNumber_TrueDivide(num, den);
2332 Py_DECREF(num);
2333 Py_DECREF(den);
2334 return ans;
Tim Peters78526162001-09-05 00:53:45 +00002335}
2336
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002337
2338/*[clinic input]
2339math.log2
2340
2341 x: object
2342 /
2343
2344Return the base 2 logarithm of x.
2345[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002346
2347static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002348math_log2(PyObject *module, PyObject *x)
2349/*[clinic end generated code: output=5425899a4d5d6acb input=08321262bae4f39b]*/
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02002350{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002351 return loghelper(x, m_log2, "log2");
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02002352}
2353
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002354
2355/*[clinic input]
2356math.log10
2357
2358 x: object
2359 /
2360
2361Return the base 10 logarithm of x.
2362[clinic start generated code]*/
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02002363
2364static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002365math_log10(PyObject *module, PyObject *x)
2366/*[clinic end generated code: output=be72a64617df9c6f input=b2469d02c6469e53]*/
Tim Peters78526162001-09-05 00:53:45 +00002367{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002368 return loghelper(x, m_log10, "log10");
Tim Peters78526162001-09-05 00:53:45 +00002369}
2370
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002371
2372/*[clinic input]
2373math.fmod
2374
2375 x: double
2376 y: double
2377 /
2378
2379Return fmod(x, y), according to platform C.
2380
2381x % y may differ.
2382[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002383
Christian Heimes53876d92008-04-19 00:31:39 +00002384static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002385math_fmod_impl(PyObject *module, double x, double y)
2386/*[clinic end generated code: output=7559d794343a27b5 input=4f84caa8cfc26a03]*/
Christian Heimes53876d92008-04-19 00:31:39 +00002387{
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002388 double r;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 /* fmod(x, +/-Inf) returns x for finite x. */
2390 if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
2391 return PyFloat_FromDouble(x);
2392 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 r = fmod(x, y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 if (Py_IS_NAN(r)) {
2395 if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
2396 errno = EDOM;
2397 else
2398 errno = 0;
2399 }
2400 if (errno && is_error(r))
2401 return NULL;
2402 else
2403 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00002404}
2405
Raymond Hettinger13990742018-08-11 11:26:36 -07002406/*
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002407Given a *vec* of values, compute the vector norm:
Raymond Hettinger13990742018-08-11 11:26:36 -07002408
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002409 sqrt(sum(x ** 2 for x in vec))
Raymond Hettingerfff3c282020-08-15 19:38:19 -07002410
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002411The *max* variable should be equal to the largest fabs(x).
2412The *n* variable is the length of *vec*.
2413If n==0, then *max* should be 0.0.
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002414If an infinity is present in the vec, *max* should be INF.
Raymond Hettingerc630e102018-08-11 18:39:05 -07002415The *found_nan* variable indicates whether some member of
2416the *vec* is a NaN.
Raymond Hettinger21786f52018-08-28 22:47:24 -07002417
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002418To avoid overflow/underflow and to achieve high accuracy giving results
2419that are almost always correctly rounded, four techniques are used:
Raymond Hettinger21786f52018-08-28 22:47:24 -07002420
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002421* lossless scaling using a power-of-two scaling factor
2422* accurate squaring using Veltkamp-Dekker splitting
2423* compensated summation using a variant of the Neumaier algorithm
2424* differential correction of the square root
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002425
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002426The usual presentation of the Neumaier summation algorithm has an
2427expensive branch depending on which operand has the larger
2428magnitude. We avoid this cost by arranging the calculation so that
2429fabs(csum) is always as large as fabs(x).
Raymond Hettinger21786f52018-08-28 22:47:24 -07002430
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002431To establish the invariant, *csum* is initialized to 1.0 which is
2432always larger than x**2 after scaling or division by *max*.
2433After the loop is finished, the initial 1.0 is subtracted out for a
2434net zero effect on the final sum. Since *csum* will be greater than
24351.0, the subtraction of 1.0 will not cause fractional digits to be
2436dropped from *csum*.
2437
2438To get the full benefit from compensated summation, the largest
2439addend should be in the range: 0.5 <= |x| <= 1.0. Accordingly,
2440scaling or division by *max* should not be skipped even if not
2441otherwise needed to prevent overflow or loss of precision.
2442
2443The assertion that hi*hi >= 1.0 is a bit subtle. Each vector element
2444gets scaled to a magnitude below 1.0. The Veltkamp-Dekker splitting
2445algorithm gives a *hi* value that is correctly rounded to half
2446precision. When a value at or below 1.0 is correctly rounded, it
2447never goes above 1.0. And when values at or below 1.0 are squared,
2448they remain at or below 1.0, thus preserving the summation invariant.
2449
2450The square root differential correction is needed because a
2451correctly rounded square root of a correctly rounded sum of
2452squares can still be off by as much as one ulp.
2453
2454The differential correction starts with a value *x* that is
2455the difference between the square of *h*, the possibly inaccurately
2456rounded square root, and the accurately computed sum of squares.
2457The correction is the first order term of the Maclaurin series
2458expansion of sqrt(h**2 + x) == h + x/(2*h) + O(x**2).
2459
2460Essentially, this differential correction is equivalent to one
2461refinement step in the Newton divide-and-average square root
2462algorithm, effectively doubling the number of accurate bits.
2463This technique is used in Dekker's SQRT2 algorithm and again in
2464Borges' ALGORITHM 4 and 5.
2465
2466References:
2467
24681. Veltkamp-Dekker splitting: http://csclub.uwaterloo.ca/~pbarfuss/dekker1971.pdf
24692. Compensated summation: http://www.ti3.tu-harburg.de/paper/rump/Ru08b.pdf
24703. Square root diffential correction: https://arxiv.org/pdf/1904.09481.pdf
Raymond Hettingerfff3c282020-08-15 19:38:19 -07002471
Raymond Hettinger13990742018-08-11 11:26:36 -07002472*/
2473
2474static inline double
Raymond Hettingerc630e102018-08-11 18:39:05 -07002475vector_norm(Py_ssize_t n, double *vec, double max, int found_nan)
Raymond Hettinger13990742018-08-11 11:26:36 -07002476{
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002477 const double T27 = 134217729.0; /* ldexp(1.0, 27)+1.0) */
Raymond Hettingerfff3c282020-08-15 19:38:19 -07002478 double x, csum = 1.0, oldcsum, frac = 0.0, scale;
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002479 double t, hi, lo, h;
Raymond Hettingerfff3c282020-08-15 19:38:19 -07002480 int max_e;
Raymond Hettinger13990742018-08-11 11:26:36 -07002481 Py_ssize_t i;
2482
Raymond Hettingerc630e102018-08-11 18:39:05 -07002483 if (Py_IS_INFINITY(max)) {
2484 return max;
2485 }
2486 if (found_nan) {
2487 return Py_NAN;
2488 }
Raymond Hettingerf3267142018-09-02 13:34:21 -07002489 if (max == 0.0 || n <= 1) {
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002490 return max;
Raymond Hettinger13990742018-08-11 11:26:36 -07002491 }
Raymond Hettingerfff3c282020-08-15 19:38:19 -07002492 frexp(max, &max_e);
2493 if (max_e >= -1023) {
2494 scale = ldexp(1.0, -max_e);
2495 assert(max * scale >= 0.5);
2496 assert(max * scale < 1.0);
2497 for (i=0 ; i < n ; i++) {
2498 x = vec[i];
2499 assert(Py_IS_FINITE(x) && fabs(x) <= max);
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002500
Raymond Hettingerfff3c282020-08-15 19:38:19 -07002501 x *= scale;
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002502 assert(fabs(x) < 1.0);
2503
2504 t = x * T27;
2505 hi = t - (t - x);
2506 lo = x - hi;
2507 assert(hi + lo == x);
2508
2509 x = hi * hi;
Raymond Hettingerfff3c282020-08-15 19:38:19 -07002510 assert(x <= 1.0);
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002511 assert(fabs(csum) >= fabs(x));
2512 oldcsum = csum;
2513 csum += x;
2514 frac += (oldcsum - csum) + x;
2515
2516 x = 2.0 * hi * lo;
2517 assert(fabs(csum) >= fabs(x));
2518 oldcsum = csum;
2519 csum += x;
2520 frac += (oldcsum - csum) + x;
2521
2522 x = lo * lo;
2523 assert(fabs(csum) >= fabs(x));
Raymond Hettingerfff3c282020-08-15 19:38:19 -07002524 oldcsum = csum;
2525 csum += x;
2526 frac += (oldcsum - csum) + x;
2527 }
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002528 h = sqrt(csum - 1.0 + frac);
2529
2530 x = h;
2531 t = x * T27;
2532 hi = t - (t - x);
2533 lo = x - hi;
2534 assert (hi + lo == x);
2535
2536 x = -hi * hi;
2537 assert(fabs(csum) >= fabs(x));
2538 oldcsum = csum;
2539 csum += x;
2540 frac += (oldcsum - csum) + x;
2541
2542 x = -2.0 * hi * lo;
2543 assert(fabs(csum) >= fabs(x));
2544 oldcsum = csum;
2545 csum += x;
2546 frac += (oldcsum - csum) + x;
2547
2548 x = -lo * lo;
2549 assert(fabs(csum) >= fabs(x));
2550 oldcsum = csum;
2551 csum += x;
2552 frac += (oldcsum - csum) + x;
2553
2554 x = csum - 1.0 + frac;
2555 return (h + x / (2.0 * h)) / scale;
Raymond Hettingerfff3c282020-08-15 19:38:19 -07002556 }
2557 /* When max_e < -1023, ldexp(1.0, -max_e) overflows.
2558 So instead of multiplying by a scale, we just divide by *max*.
2559 */
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002560 for (i=0 ; i < n ; i++) {
Raymond Hettinger13990742018-08-11 11:26:36 -07002561 x = vec[i];
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002562 assert(Py_IS_FINITE(x) && fabs(x) <= max);
Raymond Hettinger13990742018-08-11 11:26:36 -07002563 x /= max;
Raymond Hettinger21786f52018-08-28 22:47:24 -07002564 x = x*x;
Raymond Hettingerfff3c282020-08-15 19:38:19 -07002565 assert(x <= 1.0);
Raymond Hettinger8e19c8b2020-08-24 17:40:08 -07002566 assert(fabs(csum) >= fabs(x));
Raymond Hettinger13990742018-08-11 11:26:36 -07002567 oldcsum = csum;
2568 csum += x;
Raymond Hettinger21786f52018-08-28 22:47:24 -07002569 frac += (oldcsum - csum) + x;
Raymond Hettinger13990742018-08-11 11:26:36 -07002570 }
Raymond Hettinger745c0f32018-08-31 11:22:13 -07002571 return max * sqrt(csum - 1.0 + frac);
Raymond Hettinger13990742018-08-11 11:26:36 -07002572}
2573
Raymond Hettingerc630e102018-08-11 18:39:05 -07002574#define NUM_STACK_ELEMS 16
2575
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002576/*[clinic input]
2577math.dist
2578
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002579 p: object
2580 q: object
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002581 /
2582
2583Return the Euclidean distance between two points p and q.
2584
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002585The points should be specified as sequences (or iterables) of
2586coordinates. Both inputs must have the same dimension.
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002587
2588Roughly equivalent to:
2589 sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
2590[clinic start generated code]*/
2591
2592static PyObject *
2593math_dist_impl(PyObject *module, PyObject *p, PyObject *q)
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002594/*[clinic end generated code: output=56bd9538d06bbcfe input=74e85e1b6092e68e]*/
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002595{
2596 PyObject *item;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002597 double max = 0.0;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002598 double x, px, qx, result;
2599 Py_ssize_t i, m, n;
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002600 int found_nan = 0, p_allocated = 0, q_allocated = 0;
Raymond Hettingerc630e102018-08-11 18:39:05 -07002601 double diffs_on_stack[NUM_STACK_ELEMS];
2602 double *diffs = diffs_on_stack;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002603
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002604 if (!PyTuple_Check(p)) {
2605 p = PySequence_Tuple(p);
2606 if (p == NULL) {
2607 return NULL;
2608 }
2609 p_allocated = 1;
2610 }
2611 if (!PyTuple_Check(q)) {
2612 q = PySequence_Tuple(q);
2613 if (q == NULL) {
2614 if (p_allocated) {
2615 Py_DECREF(p);
2616 }
2617 return NULL;
2618 }
2619 q_allocated = 1;
2620 }
2621
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002622 m = PyTuple_GET_SIZE(p);
2623 n = PyTuple_GET_SIZE(q);
2624 if (m != n) {
2625 PyErr_SetString(PyExc_ValueError,
2626 "both points must have the same number of dimensions");
2627 return NULL;
2628
2629 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002630 if (n > NUM_STACK_ELEMS) {
2631 diffs = (double *) PyObject_Malloc(n * sizeof(double));
2632 if (diffs == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07002633 return PyErr_NoMemory();
Raymond Hettingerc630e102018-08-11 18:39:05 -07002634 }
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002635 }
2636 for (i=0 ; i<n ; i++) {
2637 item = PyTuple_GET_ITEM(p, i);
Raymond Hettingercfd735e2019-01-29 20:39:53 -08002638 ASSIGN_DOUBLE(px, item, error_exit);
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002639 item = PyTuple_GET_ITEM(q, i);
Raymond Hettingercfd735e2019-01-29 20:39:53 -08002640 ASSIGN_DOUBLE(qx, item, error_exit);
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002641 x = fabs(px - qx);
2642 diffs[i] = x;
2643 found_nan |= Py_IS_NAN(x);
2644 if (x > max) {
2645 max = x;
2646 }
2647 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002648 result = vector_norm(n, diffs, max, found_nan);
2649 if (diffs != diffs_on_stack) {
2650 PyObject_Free(diffs);
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002651 }
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002652 if (p_allocated) {
2653 Py_DECREF(p);
2654 }
2655 if (q_allocated) {
2656 Py_DECREF(q);
2657 }
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002658 return PyFloat_FromDouble(result);
Raymond Hettingerc630e102018-08-11 18:39:05 -07002659
2660 error_exit:
2661 if (diffs != diffs_on_stack) {
2662 PyObject_Free(diffs);
2663 }
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -07002664 if (p_allocated) {
2665 Py_DECREF(p);
2666 }
2667 if (q_allocated) {
2668 Py_DECREF(q);
2669 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002670 return NULL;
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07002671}
2672
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002673/* AC: cannot convert yet, waiting for *args support */
Christian Heimes53876d92008-04-19 00:31:39 +00002674static PyObject *
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002675math_hypot(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
Christian Heimes53876d92008-04-19 00:31:39 +00002676{
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002677 Py_ssize_t i;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002678 PyObject *item;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002679 double max = 0.0;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002680 double x, result;
2681 int found_nan = 0;
Raymond Hettingerc630e102018-08-11 18:39:05 -07002682 double coord_on_stack[NUM_STACK_ELEMS];
2683 double *coordinates = coord_on_stack;
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002684
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002685 if (nargs > NUM_STACK_ELEMS) {
2686 coordinates = (double *) PyObject_Malloc(nargs * sizeof(double));
Zackery Spytz4c49da02018-12-07 03:11:30 -07002687 if (coordinates == NULL) {
2688 return PyErr_NoMemory();
2689 }
Raymond Hettingerc630e102018-08-11 18:39:05 -07002690 }
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002691 for (i = 0; i < nargs; i++) {
2692 item = args[i];
Raymond Hettingercfd735e2019-01-29 20:39:53 -08002693 ASSIGN_DOUBLE(x, item, error_exit);
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002694 x = fabs(x);
2695 coordinates[i] = x;
2696 found_nan |= Py_IS_NAN(x);
2697 if (x > max) {
2698 max = x;
2699 }
2700 }
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02002701 result = vector_norm(nargs, coordinates, max, found_nan);
Raymond Hettingerc630e102018-08-11 18:39:05 -07002702 if (coordinates != coord_on_stack) {
2703 PyObject_Free(coordinates);
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002704 }
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002705 return PyFloat_FromDouble(result);
Raymond Hettingerc630e102018-08-11 18:39:05 -07002706
2707 error_exit:
2708 if (coordinates != coord_on_stack) {
2709 PyObject_Free(coordinates);
2710 }
2711 return NULL;
Christian Heimes53876d92008-04-19 00:31:39 +00002712}
2713
Raymond Hettingerc630e102018-08-11 18:39:05 -07002714#undef NUM_STACK_ELEMS
2715
Raymond Hettingerc6dabe32018-07-28 07:48:04 -07002716PyDoc_STRVAR(math_hypot_doc,
2717 "hypot(*coordinates) -> value\n\n\
2718Multidimensional Euclidean distance from the origin to a point.\n\
2719\n\
2720Roughly equivalent to:\n\
2721 sqrt(sum(x**2 for x in coordinates))\n\
2722\n\
2723For a two dimensional point (x, y), gives the hypotenuse\n\
2724using the Pythagorean theorem: sqrt(x*x + y*y).\n\
2725\n\
2726For example, the hypotenuse of a 3/4/5 right triangle is:\n\
2727\n\
2728 >>> hypot(3.0, 4.0)\n\
2729 5.0\n\
2730");
Christian Heimes53876d92008-04-19 00:31:39 +00002731
2732/* pow can't use math_2, but needs its own wrapper: the problem is
2733 that an infinite result can arise either as a result of overflow
2734 (in which case OverflowError should be raised) or as a result of
2735 e.g. 0.**-5. (for which ValueError needs to be raised.)
2736*/
2737
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002738/*[clinic input]
2739math.pow
Christian Heimes53876d92008-04-19 00:31:39 +00002740
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002741 x: double
2742 y: double
2743 /
2744
2745Return x**y (x to the power of y).
2746[clinic start generated code]*/
2747
2748static PyObject *
2749math_pow_impl(PyObject *module, double x, double y)
2750/*[clinic end generated code: output=fff93e65abccd6b0 input=c26f1f6075088bfd]*/
2751{
2752 double r;
2753 int odd_y;
Christian Heimesa342c012008-04-20 21:01:16 +00002754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002755 /* deal directly with IEEE specials, to cope with problems on various
2756 platforms whose semantics don't exactly match C99 */
2757 r = 0.; /* silence compiler warning */
2758 if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
2759 errno = 0;
2760 if (Py_IS_NAN(x))
2761 r = y == 0. ? 1. : x; /* NaN**0 = 1 */
2762 else if (Py_IS_NAN(y))
2763 r = x == 1. ? 1. : y; /* 1**NaN = 1 */
2764 else if (Py_IS_INFINITY(x)) {
2765 odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
2766 if (y > 0.)
2767 r = odd_y ? x : fabs(x);
2768 else if (y == 0.)
2769 r = 1.;
2770 else /* y < 0. */
2771 r = odd_y ? copysign(0., x) : 0.;
2772 }
2773 else if (Py_IS_INFINITY(y)) {
2774 if (fabs(x) == 1.0)
2775 r = 1.;
2776 else if (y > 0. && fabs(x) > 1.0)
2777 r = y;
2778 else if (y < 0. && fabs(x) < 1.0) {
2779 r = -y; /* result is +inf */
2780 if (x == 0.) /* 0**-inf: divide-by-zero */
2781 errno = EDOM;
2782 }
2783 else
2784 r = 0.;
2785 }
2786 }
2787 else {
2788 /* let libm handle finite**finite */
2789 errno = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002790 r = pow(x, y);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002791 /* a NaN result should arise only from (-ve)**(finite
2792 non-integer); in this case we want to raise ValueError. */
2793 if (!Py_IS_FINITE(r)) {
2794 if (Py_IS_NAN(r)) {
2795 errno = EDOM;
2796 }
2797 /*
2798 an infinite result here arises either from:
2799 (A) (+/-0.)**negative (-> divide-by-zero)
2800 (B) overflow of x**y with x and y finite
2801 */
2802 else if (Py_IS_INFINITY(r)) {
2803 if (x == 0.)
2804 errno = EDOM;
2805 else
2806 errno = ERANGE;
2807 }
2808 }
2809 }
Christian Heimes53876d92008-04-19 00:31:39 +00002810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002811 if (errno && is_error(r))
2812 return NULL;
2813 else
2814 return PyFloat_FromDouble(r);
Christian Heimes53876d92008-04-19 00:31:39 +00002815}
2816
Christian Heimes53876d92008-04-19 00:31:39 +00002817
Christian Heimes072c0f12008-01-03 23:01:04 +00002818static const double degToRad = Py_MATH_PI / 180.0;
2819static const double radToDeg = 180.0 / Py_MATH_PI;
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002820
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002821/*[clinic input]
2822math.degrees
2823
2824 x: double
2825 /
2826
2827Convert angle x from radians to degrees.
2828[clinic start generated code]*/
2829
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002830static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002831math_degrees_impl(PyObject *module, double x)
2832/*[clinic end generated code: output=7fea78b294acd12f input=81e016555d6e3660]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002833{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 return PyFloat_FromDouble(x * radToDeg);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002835}
2836
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002837
2838/*[clinic input]
2839math.radians
2840
2841 x: double
2842 /
2843
2844Convert angle x from degrees to radians.
2845[clinic start generated code]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002846
2847static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002848math_radians_impl(PyObject *module, double x)
2849/*[clinic end generated code: output=34daa47caf9b1590 input=91626fc489fe3d63]*/
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 return PyFloat_FromDouble(x * degToRad);
Raymond Hettingerd6f22672002-05-13 03:56:10 +00002852}
2853
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002854
2855/*[clinic input]
2856math.isfinite
2857
2858 x: double
2859 /
2860
2861Return True if x is neither an infinity nor a NaN, and False otherwise.
2862[clinic start generated code]*/
Tim Peters78526162001-09-05 00:53:45 +00002863
Christian Heimes072c0f12008-01-03 23:01:04 +00002864static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002865math_isfinite_impl(PyObject *module, double x)
2866/*[clinic end generated code: output=8ba1f396440c9901 input=46967d254812e54a]*/
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002867{
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002868 return PyBool_FromLong((long)Py_IS_FINITE(x));
2869}
2870
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002871
2872/*[clinic input]
2873math.isnan
2874
2875 x: double
2876 /
2877
2878Return True if x is a NaN (not a number), and False otherwise.
2879[clinic start generated code]*/
Mark Dickinson8e0c9962010-07-11 17:38:24 +00002880
2881static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002882math_isnan_impl(PyObject *module, double x)
2883/*[clinic end generated code: output=f537b4d6df878c3e input=935891e66083f46a]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002884{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002885 return PyBool_FromLong((long)Py_IS_NAN(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00002886}
2887
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002888
2889/*[clinic input]
2890math.isinf
2891
2892 x: double
2893 /
2894
2895Return True if x is a positive or negative infinity, and False otherwise.
2896[clinic start generated code]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002897
2898static PyObject *
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002899math_isinf_impl(PyObject *module, double x)
2900/*[clinic end generated code: output=9f00cbec4de7b06b input=32630e4212cf961f]*/
Christian Heimes072c0f12008-01-03 23:01:04 +00002901{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002902 return PyBool_FromLong((long)Py_IS_INFINITY(x));
Christian Heimes072c0f12008-01-03 23:01:04 +00002903}
2904
Christian Heimes072c0f12008-01-03 23:01:04 +00002905
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002906/*[clinic input]
2907math.isclose -> bool
2908
2909 a: double
2910 b: double
2911 *
2912 rel_tol: double = 1e-09
2913 maximum difference for being considered "close", relative to the
2914 magnitude of the input values
2915 abs_tol: double = 0.0
2916 maximum difference for being considered "close", regardless of the
2917 magnitude of the input values
2918
2919Determine whether two floating point numbers are close in value.
2920
2921Return True if a is close in value to b, and False otherwise.
2922
2923For the values to be considered close, the difference between them
2924must be smaller than at least one of the tolerances.
2925
2926-inf, inf and NaN behave similarly to the IEEE 754 Standard. That
2927is, NaN is not close to anything, even itself. inf and -inf are
2928only close to themselves.
2929[clinic start generated code]*/
2930
2931static int
2932math_isclose_impl(PyObject *module, double a, double b, double rel_tol,
2933 double abs_tol)
2934/*[clinic end generated code: output=b73070207511952d input=f28671871ea5bfba]*/
Tal Einatd5519ed2015-05-31 22:05:00 +03002935{
Tal Einatd5519ed2015-05-31 22:05:00 +03002936 double diff = 0.0;
Tal Einatd5519ed2015-05-31 22:05:00 +03002937
2938 /* sanity check on the inputs */
2939 if (rel_tol < 0.0 || abs_tol < 0.0 ) {
2940 PyErr_SetString(PyExc_ValueError,
2941 "tolerances must be non-negative");
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002942 return -1;
Tal Einatd5519ed2015-05-31 22:05:00 +03002943 }
2944
2945 if ( a == b ) {
2946 /* short circuit exact equality -- needed to catch two infinities of
2947 the same sign. And perhaps speeds things up a bit sometimes.
2948 */
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002949 return 1;
Tal Einatd5519ed2015-05-31 22:05:00 +03002950 }
2951
2952 /* This catches the case of two infinities of opposite sign, or
2953 one infinity and one finite number. Two infinities of opposite
2954 sign would otherwise have an infinite relative tolerance.
2955 Two infinities of the same sign are caught by the equality check
2956 above.
2957 */
2958
2959 if (Py_IS_INFINITY(a) || Py_IS_INFINITY(b)) {
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002960 return 0;
Tal Einatd5519ed2015-05-31 22:05:00 +03002961 }
2962
2963 /* now do the regular computation
2964 this is essentially the "weak" test from the Boost library
2965 */
2966
2967 diff = fabs(b - a);
2968
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02002969 return (((diff <= fabs(rel_tol * b)) ||
2970 (diff <= fabs(rel_tol * a))) ||
2971 (diff <= abs_tol));
Tal Einatd5519ed2015-05-31 22:05:00 +03002972}
2973
Pablo Galindo04114112019-03-09 19:18:08 +00002974static inline int
2975_check_long_mult_overflow(long a, long b) {
2976
2977 /* From Python2's int_mul code:
2978
2979 Integer overflow checking for * is painful: Python tried a couple ways, but
2980 they didn't work on all platforms, or failed in endcases (a product of
2981 -sys.maxint-1 has been a particular pain).
2982
2983 Here's another way:
2984
2985 The native long product x*y is either exactly right or *way* off, being
2986 just the last n bits of the true product, where n is the number of bits
2987 in a long (the delivered product is the true product plus i*2**n for
2988 some integer i).
2989
2990 The native double product (double)x * (double)y is subject to three
2991 rounding errors: on a sizeof(long)==8 box, each cast to double can lose
2992 info, and even on a sizeof(long)==4 box, the multiplication can lose info.
2993 But, unlike the native long product, it's not in *range* trouble: even
2994 if sizeof(long)==32 (256-bit longs), the product easily fits in the
2995 dynamic range of a double. So the leading 50 (or so) bits of the double
2996 product are correct.
2997
2998 We check these two ways against each other, and declare victory if they're
2999 approximately the same. Else, because the native long product is the only
3000 one that can lose catastrophic amounts of information, it's the native long
3001 product that must have overflowed.
3002
3003 */
3004
3005 long longprod = (long)((unsigned long)a * b);
3006 double doubleprod = (double)a * (double)b;
3007 double doubled_longprod = (double)longprod;
3008
3009 if (doubled_longprod == doubleprod) {
3010 return 0;
3011 }
3012
3013 const double diff = doubled_longprod - doubleprod;
3014 const double absdiff = diff >= 0.0 ? diff : -diff;
3015 const double absprod = doubleprod >= 0.0 ? doubleprod : -doubleprod;
3016
3017 if (32.0 * absdiff <= absprod) {
3018 return 0;
3019 }
3020
3021 return 1;
3022}
Tal Einatd5519ed2015-05-31 22:05:00 +03003023
Pablo Galindobc098512019-02-07 07:04:02 +00003024/*[clinic input]
3025math.prod
3026
3027 iterable: object
3028 /
3029 *
3030 start: object(c_default="NULL") = 1
3031
3032Calculate the product of all the elements in the input iterable.
3033
3034The default start value for the product is 1.
3035
3036When the iterable is empty, return the start value. This function is
3037intended specifically for use with numeric values and may reject
3038non-numeric types.
3039[clinic start generated code]*/
3040
3041static PyObject *
3042math_prod_impl(PyObject *module, PyObject *iterable, PyObject *start)
3043/*[clinic end generated code: output=36153bedac74a198 input=4c5ab0682782ed54]*/
3044{
3045 PyObject *result = start;
3046 PyObject *temp, *item, *iter;
3047
3048 iter = PyObject_GetIter(iterable);
3049 if (iter == NULL) {
3050 return NULL;
3051 }
3052
3053 if (result == NULL) {
3054 result = PyLong_FromLong(1);
3055 if (result == NULL) {
3056 Py_DECREF(iter);
3057 return NULL;
3058 }
3059 } else {
3060 Py_INCREF(result);
3061 }
3062#ifndef SLOW_PROD
3063 /* Fast paths for integers keeping temporary products in C.
3064 * Assumes all inputs are the same type.
3065 * If the assumption fails, default to use PyObjects instead.
3066 */
3067 if (PyLong_CheckExact(result)) {
3068 int overflow;
3069 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
3070 /* If this already overflowed, don't even enter the loop. */
3071 if (overflow == 0) {
3072 Py_DECREF(result);
3073 result = NULL;
3074 }
3075 /* Loop over all the items in the iterable until we finish, we overflow
3076 * or we found a non integer element */
3077 while(result == NULL) {
3078 item = PyIter_Next(iter);
3079 if (item == NULL) {
3080 Py_DECREF(iter);
3081 if (PyErr_Occurred()) {
3082 return NULL;
3083 }
3084 return PyLong_FromLong(i_result);
3085 }
3086 if (PyLong_CheckExact(item)) {
3087 long b = PyLong_AsLongAndOverflow(item, &overflow);
Pablo Galindo04114112019-03-09 19:18:08 +00003088 if (overflow == 0 && !_check_long_mult_overflow(i_result, b)) {
3089 long x = i_result * b;
Pablo Galindobc098512019-02-07 07:04:02 +00003090 i_result = x;
3091 Py_DECREF(item);
3092 continue;
3093 }
3094 }
3095 /* Either overflowed or is not an int.
3096 * Restore real objects and process normally */
3097 result = PyLong_FromLong(i_result);
3098 if (result == NULL) {
3099 Py_DECREF(item);
3100 Py_DECREF(iter);
3101 return NULL;
3102 }
3103 temp = PyNumber_Multiply(result, item);
3104 Py_DECREF(result);
3105 Py_DECREF(item);
3106 result = temp;
3107 if (result == NULL) {
3108 Py_DECREF(iter);
3109 return NULL;
3110 }
3111 }
3112 }
3113
3114 /* Fast paths for floats keeping temporary products in C.
3115 * Assumes all inputs are the same type.
3116 * If the assumption fails, default to use PyObjects instead.
3117 */
3118 if (PyFloat_CheckExact(result)) {
3119 double f_result = PyFloat_AS_DOUBLE(result);
3120 Py_DECREF(result);
3121 result = NULL;
3122 while(result == NULL) {
3123 item = PyIter_Next(iter);
3124 if (item == NULL) {
3125 Py_DECREF(iter);
3126 if (PyErr_Occurred()) {
3127 return NULL;
3128 }
3129 return PyFloat_FromDouble(f_result);
3130 }
3131 if (PyFloat_CheckExact(item)) {
3132 f_result *= PyFloat_AS_DOUBLE(item);
3133 Py_DECREF(item);
3134 continue;
3135 }
3136 if (PyLong_CheckExact(item)) {
3137 long value;
3138 int overflow;
3139 value = PyLong_AsLongAndOverflow(item, &overflow);
3140 if (!overflow) {
3141 f_result *= (double)value;
3142 Py_DECREF(item);
3143 continue;
3144 }
3145 }
3146 result = PyFloat_FromDouble(f_result);
3147 if (result == NULL) {
3148 Py_DECREF(item);
3149 Py_DECREF(iter);
3150 return NULL;
3151 }
3152 temp = PyNumber_Multiply(result, item);
3153 Py_DECREF(result);
3154 Py_DECREF(item);
3155 result = temp;
3156 if (result == NULL) {
3157 Py_DECREF(iter);
3158 return NULL;
3159 }
3160 }
3161 }
3162#endif
3163 /* Consume rest of the iterable (if any) that could not be handled
3164 * by specialized functions above.*/
3165 for(;;) {
3166 item = PyIter_Next(iter);
3167 if (item == NULL) {
3168 /* error, or end-of-sequence */
3169 if (PyErr_Occurred()) {
3170 Py_DECREF(result);
3171 result = NULL;
3172 }
3173 break;
3174 }
3175 temp = PyNumber_Multiply(result, item);
3176 Py_DECREF(result);
3177 Py_DECREF(item);
3178 result = temp;
3179 if (result == NULL)
3180 break;
3181 }
3182 Py_DECREF(iter);
3183 return result;
3184}
3185
3186
Yash Aggarwal4a686502019-06-01 12:51:27 +05303187/*[clinic input]
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003188math.perm
3189
3190 n: object
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003191 k: object = None
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003192 /
3193
3194Number of ways to choose k items from n items without repetition and with order.
3195
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003196Evaluates to n! / (n - k)! when k <= n and evaluates
3197to zero when k > n.
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003198
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003199If k is not specified or is None, then k defaults to n
3200and the function returns n!.
3201
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003202Raises TypeError if either of the arguments are not integers.
3203Raises ValueError if either of the arguments are negative.
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003204[clinic start generated code]*/
3205
3206static PyObject *
3207math_perm_impl(PyObject *module, PyObject *n, PyObject *k)
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003208/*[clinic end generated code: output=e021a25469653e23 input=5311c5a00f359b53]*/
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003209{
3210 PyObject *result = NULL, *factor = NULL;
3211 int overflow, cmp;
3212 long long i, factors;
3213
Raymond Hettingere119b3d2019-06-08 08:58:11 -07003214 if (k == Py_None) {
3215 return math_factorial(module, n);
3216 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003217 n = PyNumber_Index(n);
3218 if (n == NULL) {
3219 return NULL;
3220 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003221 k = PyNumber_Index(k);
3222 if (k == NULL) {
3223 Py_DECREF(n);
3224 return NULL;
3225 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003226
3227 if (Py_SIZE(n) < 0) {
3228 PyErr_SetString(PyExc_ValueError,
3229 "n must be a non-negative integer");
3230 goto error;
3231 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003232 if (Py_SIZE(k) < 0) {
3233 PyErr_SetString(PyExc_ValueError,
3234 "k must be a non-negative integer");
3235 goto error;
3236 }
3237
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003238 cmp = PyObject_RichCompareBool(n, k, Py_LT);
3239 if (cmp != 0) {
3240 if (cmp > 0) {
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003241 result = PyLong_FromLong(0);
3242 goto done;
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003243 }
3244 goto error;
3245 }
3246
3247 factors = PyLong_AsLongLongAndOverflow(k, &overflow);
3248 if (overflow > 0) {
3249 PyErr_Format(PyExc_OverflowError,
3250 "k must not exceed %lld",
3251 LLONG_MAX);
3252 goto error;
3253 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003254 else if (factors == -1) {
3255 /* k is nonnegative, so a return value of -1 can only indicate error */
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003256 goto error;
3257 }
3258
3259 if (factors == 0) {
3260 result = PyLong_FromLong(1);
3261 goto done;
3262 }
3263
3264 result = n;
3265 Py_INCREF(result);
3266 if (factors == 1) {
3267 goto done;
3268 }
3269
3270 factor = n;
3271 Py_INCREF(factor);
3272 for (i = 1; i < factors; ++i) {
3273 Py_SETREF(factor, PyNumber_Subtract(factor, _PyLong_One));
3274 if (factor == NULL) {
3275 goto error;
3276 }
3277 Py_SETREF(result, PyNumber_Multiply(result, factor));
3278 if (result == NULL) {
3279 goto error;
3280 }
3281 }
3282 Py_DECREF(factor);
3283
3284done:
3285 Py_DECREF(n);
3286 Py_DECREF(k);
3287 return result;
3288
3289error:
3290 Py_XDECREF(factor);
3291 Py_XDECREF(result);
3292 Py_DECREF(n);
3293 Py_DECREF(k);
3294 return NULL;
3295}
3296
3297
3298/*[clinic input]
Yash Aggarwal4a686502019-06-01 12:51:27 +05303299math.comb
3300
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003301 n: object
3302 k: object
3303 /
Yash Aggarwal4a686502019-06-01 12:51:27 +05303304
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003305Number of ways to choose k items from n items without repetition and without order.
Yash Aggarwal4a686502019-06-01 12:51:27 +05303306
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003307Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates
3308to zero when k > n.
Yash Aggarwal4a686502019-06-01 12:51:27 +05303309
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003310Also called the binomial coefficient because it is equivalent
3311to the coefficient of k-th term in polynomial expansion of the
3312expression (1 + x)**n.
3313
3314Raises TypeError if either of the arguments are not integers.
3315Raises ValueError if either of the arguments are negative.
Yash Aggarwal4a686502019-06-01 12:51:27 +05303316
3317[clinic start generated code]*/
3318
3319static PyObject *
3320math_comb_impl(PyObject *module, PyObject *n, PyObject *k)
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003321/*[clinic end generated code: output=bd2cec8d854f3493 input=9a05315af2518709]*/
Yash Aggarwal4a686502019-06-01 12:51:27 +05303322{
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003323 PyObject *result = NULL, *factor = NULL, *temp;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303324 int overflow, cmp;
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003325 long long i, factors;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303326
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003327 n = PyNumber_Index(n);
3328 if (n == NULL) {
3329 return NULL;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303330 }
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003331 k = PyNumber_Index(k);
3332 if (k == NULL) {
3333 Py_DECREF(n);
3334 return NULL;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303335 }
3336
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003337 if (Py_SIZE(n) < 0) {
3338 PyErr_SetString(PyExc_ValueError,
3339 "n must be a non-negative integer");
3340 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303341 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003342 if (Py_SIZE(k) < 0) {
3343 PyErr_SetString(PyExc_ValueError,
3344 "k must be a non-negative integer");
3345 goto error;
3346 }
3347
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003348 /* k = min(k, n - k) */
3349 temp = PyNumber_Subtract(n, k);
3350 if (temp == NULL) {
3351 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303352 }
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003353 if (Py_SIZE(temp) < 0) {
3354 Py_DECREF(temp);
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07003355 result = PyLong_FromLong(0);
3356 goto done;
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003357 }
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003358 cmp = PyObject_RichCompareBool(temp, k, Py_LT);
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003359 if (cmp > 0) {
3360 Py_SETREF(k, temp);
Yash Aggarwal4a686502019-06-01 12:51:27 +05303361 }
3362 else {
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003363 Py_DECREF(temp);
3364 if (cmp < 0) {
3365 goto error;
3366 }
Yash Aggarwal4a686502019-06-01 12:51:27 +05303367 }
3368
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003369 factors = PyLong_AsLongLongAndOverflow(k, &overflow);
3370 if (overflow > 0) {
Yash Aggarwal4a686502019-06-01 12:51:27 +05303371 PyErr_Format(PyExc_OverflowError,
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003372 "min(n - k, k) must not exceed %lld",
Yash Aggarwal4a686502019-06-01 12:51:27 +05303373 LLONG_MAX);
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003374 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303375 }
Mark Dickinson45e04112019-06-16 11:06:06 +01003376 if (factors == -1) {
3377 /* k is nonnegative, so a return value of -1 can only indicate error */
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003378 goto error;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303379 }
3380
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003381 if (factors == 0) {
3382 result = PyLong_FromLong(1);
3383 goto done;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303384 }
3385
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003386 result = n;
3387 Py_INCREF(result);
3388 if (factors == 1) {
3389 goto done;
Yash Aggarwal4a686502019-06-01 12:51:27 +05303390 }
3391
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003392 factor = n;
3393 Py_INCREF(factor);
3394 for (i = 1; i < factors; ++i) {
3395 Py_SETREF(factor, PyNumber_Subtract(factor, _PyLong_One));
3396 if (factor == NULL) {
3397 goto error;
3398 }
3399 Py_SETREF(result, PyNumber_Multiply(result, factor));
3400 if (result == NULL) {
3401 goto error;
3402 }
Yash Aggarwal4a686502019-06-01 12:51:27 +05303403
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003404 temp = PyLong_FromUnsignedLongLong((unsigned long long)i + 1);
3405 if (temp == NULL) {
3406 goto error;
3407 }
3408 Py_SETREF(result, PyNumber_FloorDivide(result, temp));
3409 Py_DECREF(temp);
3410 if (result == NULL) {
3411 goto error;
3412 }
3413 }
3414 Py_DECREF(factor);
Yash Aggarwal4a686502019-06-01 12:51:27 +05303415
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03003416done:
3417 Py_DECREF(n);
3418 Py_DECREF(k);
3419 return result;
3420
3421error:
3422 Py_XDECREF(factor);
3423 Py_XDECREF(result);
3424 Py_DECREF(n);
3425 Py_DECREF(k);
Yash Aggarwal4a686502019-06-01 12:51:27 +05303426 return NULL;
3427}
3428
3429
Victor Stinner100fafc2020-01-12 02:15:42 +01003430/*[clinic input]
3431math.nextafter
3432
3433 x: double
3434 y: double
3435 /
3436
3437Return the next floating-point value after x towards y.
3438[clinic start generated code]*/
3439
3440static PyObject *
3441math_nextafter_impl(PyObject *module, double x, double y)
3442/*[clinic end generated code: output=750c8266c1c540ce input=02b2d50cd1d9f9b6]*/
3443{
Victor Stinner85ead4f2020-01-21 11:14:10 +01003444#if defined(_AIX)
3445 if (x == y) {
3446 /* On AIX 7.1, libm nextafter(-0.0, +0.0) returns -0.0.
3447 Bug fixed in bos.adt.libm 7.2.2.0 by APAR IV95512. */
3448 return PyFloat_FromDouble(y);
3449 }
3450#endif
3451 return PyFloat_FromDouble(nextafter(x, y));
Victor Stinner100fafc2020-01-12 02:15:42 +01003452}
3453
3454
Victor Stinner0b2ab212020-01-13 12:44:35 +01003455/*[clinic input]
3456math.ulp -> double
3457
3458 x: double
3459 /
3460
3461Return the value of the least significant bit of the float x.
3462[clinic start generated code]*/
3463
3464static double
3465math_ulp_impl(PyObject *module, double x)
3466/*[clinic end generated code: output=f5207867a9384dd4 input=31f9bfbbe373fcaa]*/
3467{
3468 if (Py_IS_NAN(x)) {
3469 return x;
3470 }
3471 x = fabs(x);
3472 if (Py_IS_INFINITY(x)) {
3473 return x;
3474 }
3475 double inf = m_inf();
3476 double x2 = nextafter(x, inf);
3477 if (Py_IS_INFINITY(x2)) {
3478 /* special case: x is the largest positive representable float */
3479 x2 = nextafter(x, -inf);
3480 return x - x2;
3481 }
3482 return x2 - x;
3483}
3484
Dong-hee Na5be82412020-03-31 23:33:22 +09003485static int
3486math_exec(PyObject *module)
3487{
3488 if (PyModule_AddObject(module, "pi", PyFloat_FromDouble(Py_MATH_PI)) < 0) {
3489 return -1;
3490 }
3491 if (PyModule_AddObject(module, "e", PyFloat_FromDouble(Py_MATH_E)) < 0) {
3492 return -1;
3493 }
3494 // 2pi
3495 if (PyModule_AddObject(module, "tau", PyFloat_FromDouble(Py_MATH_TAU)) < 0) {
3496 return -1;
3497 }
3498 if (PyModule_AddObject(module, "inf", PyFloat_FromDouble(m_inf())) < 0) {
3499 return -1;
3500 }
3501#if !defined(PY_NO_SHORT_FLOAT_REPR) || defined(Py_NAN)
3502 if (PyModule_AddObject(module, "nan", PyFloat_FromDouble(m_nan())) < 0) {
3503 return -1;
3504 }
3505#endif
3506 return 0;
3507}
Victor Stinner0b2ab212020-01-13 12:44:35 +01003508
Barry Warsaw8b43b191996-12-09 22:32:36 +00003509static PyMethodDef math_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003510 {"acos", math_acos, METH_O, math_acos_doc},
3511 {"acosh", math_acosh, METH_O, math_acosh_doc},
3512 {"asin", math_asin, METH_O, math_asin_doc},
3513 {"asinh", math_asinh, METH_O, math_asinh_doc},
3514 {"atan", math_atan, METH_O, math_atan_doc},
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003515 {"atan2", (PyCFunction)(void(*)(void))math_atan2, METH_FASTCALL, math_atan2_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003516 {"atanh", math_atanh, METH_O, math_atanh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003517 MATH_CEIL_METHODDEF
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003518 {"copysign", (PyCFunction)(void(*)(void))math_copysign, METH_FASTCALL, math_copysign_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003519 {"cos", math_cos, METH_O, math_cos_doc},
3520 {"cosh", math_cosh, METH_O, math_cosh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003521 MATH_DEGREES_METHODDEF
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07003522 MATH_DIST_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003523 {"erf", math_erf, METH_O, math_erf_doc},
3524 {"erfc", math_erfc, METH_O, math_erfc_doc},
3525 {"exp", math_exp, METH_O, math_exp_doc},
3526 {"expm1", math_expm1, METH_O, math_expm1_doc},
3527 {"fabs", math_fabs, METH_O, math_fabs_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003528 MATH_FACTORIAL_METHODDEF
3529 MATH_FLOOR_METHODDEF
3530 MATH_FMOD_METHODDEF
3531 MATH_FREXP_METHODDEF
3532 MATH_FSUM_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003533 {"gamma", math_gamma, METH_O, math_gamma_doc},
Serhiy Storchaka559e7f12020-02-23 13:21:29 +02003534 {"gcd", (PyCFunction)(void(*)(void))math_gcd, METH_FASTCALL, math_gcd_doc},
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003535 {"hypot", (PyCFunction)(void(*)(void))math_hypot, METH_FASTCALL, math_hypot_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003536 MATH_ISCLOSE_METHODDEF
3537 MATH_ISFINITE_METHODDEF
3538 MATH_ISINF_METHODDEF
3539 MATH_ISNAN_METHODDEF
Mark Dickinson73934b92019-05-18 12:29:50 +01003540 MATH_ISQRT_METHODDEF
Serhiy Storchaka559e7f12020-02-23 13:21:29 +02003541 {"lcm", (PyCFunction)(void(*)(void))math_lcm, METH_FASTCALL, math_lcm_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003542 MATH_LDEXP_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003543 {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003544 MATH_LOG_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003545 {"log1p", math_log1p, METH_O, math_log1p_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003546 MATH_LOG10_METHODDEF
3547 MATH_LOG2_METHODDEF
3548 MATH_MODF_METHODDEF
3549 MATH_POW_METHODDEF
3550 MATH_RADIANS_METHODDEF
Serhiy Storchakad0d3e992019-01-12 08:26:34 +02003551 {"remainder", (PyCFunction)(void(*)(void))math_remainder, METH_FASTCALL, math_remainder_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003552 {"sin", math_sin, METH_O, math_sin_doc},
3553 {"sinh", math_sinh, METH_O, math_sinh_doc},
3554 {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
3555 {"tan", math_tan, METH_O, math_tan_doc},
3556 {"tanh", math_tanh, METH_O, math_tanh_doc},
Serhiy Storchakac9ea9332017-01-19 18:13:09 +02003557 MATH_TRUNC_METHODDEF
Pablo Galindobc098512019-02-07 07:04:02 +00003558 MATH_PROD_METHODDEF
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03003559 MATH_PERM_METHODDEF
Yash Aggarwal4a686502019-06-01 12:51:27 +05303560 MATH_COMB_METHODDEF
Victor Stinner100fafc2020-01-12 02:15:42 +01003561 MATH_NEXTAFTER_METHODDEF
Victor Stinner0b2ab212020-01-13 12:44:35 +01003562 MATH_ULP_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003563 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003564};
3565
Dong-hee Na5be82412020-03-31 23:33:22 +09003566static PyModuleDef_Slot math_slots[] = {
3567 {Py_mod_exec, math_exec},
3568 {0, NULL}
3569};
Guido van Rossumc6e22901998-12-04 19:26:43 +00003570
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003571PyDoc_STRVAR(module_doc,
Ned Batchelder6faad352019-05-17 05:59:14 -04003572"This module provides access to the mathematical functions\n"
3573"defined by the C standard.");
Guido van Rossumc6e22901998-12-04 19:26:43 +00003574
Martin v. Löwis1a214512008-06-11 05:26:20 +00003575static struct PyModuleDef mathmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003576 PyModuleDef_HEAD_INIT,
Dong-hee Na5be82412020-03-31 23:33:22 +09003577 .m_name = "math",
3578 .m_doc = module_doc,
3579 .m_size = 0,
3580 .m_methods = math_methods,
3581 .m_slots = math_slots,
Martin v. Löwis1a214512008-06-11 05:26:20 +00003582};
3583
Mark Hammondfe51c6d2002-08-02 02:27:13 +00003584PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003585PyInit_math(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003586{
Dong-hee Na5be82412020-03-31 23:33:22 +09003587 return PyModuleDef_Init(&mathmodule);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003588}