-
-
Notifications
You must be signed in to change notification settings - Fork 30.6k
/
mathmodule.c
4185 lines (3607 loc) · 129 KB
/
mathmodule.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Math module -- standard C math library functions, pi and e */
/* Here are some comments from Tim Peters, extracted from the
discussion attached to http://bugs.python.org/issue1640. They
describe the general aims of the math module with respect to
special values, IEEE-754 floating-point exceptions, and Python
exceptions.
These are the "spirit of 754" rules:
1. If the mathematical result is a real number, but of magnitude too
large to approximate by a machine float, overflow is signaled and the
result is an infinity (with the appropriate sign).
2. If the mathematical result is a real number, but of magnitude too
small to approximate by a machine float, underflow is signaled and the
result is a zero (with the appropriate sign).
3. At a singularity (a value x such that the limit of f(y) as y
approaches x exists and is an infinity), "divide by zero" is signaled
and the result is an infinity (with the appropriate sign). This is
complicated a little by that the left-side and right-side limits may
not be the same; e.g., 1/x approaches +inf or -inf as x approaches 0
from the positive or negative directions. In that specific case, the
sign of the zero determines the result of 1/0.
4. At a point where a function has no defined result in the extended
reals (i.e., the reals plus an infinity or two), invalid operation is
signaled and a NaN is returned.
And these are what Python has historically /tried/ to do (but not
always successfully, as platform libm behavior varies a lot):
For #1, raise OverflowError.
For #2, return a zero (with the appropriate sign if that happens by
accident ;-)).
For #3 and #4, raise ValueError. It may have made sense to raise
Python's ZeroDivisionError in #3, but historically that's only been
raised for division by zero and mod by zero.
*/
/*
In general, on an IEEE-754 platform the aim is to follow the C99
standard, including Annex 'F', whenever possible. Where the
standard recommends raising the 'divide-by-zero' or 'invalid'
floating-point exceptions, Python should raise a ValueError. Where
the standard recommends raising 'overflow', Python should raise an
OverflowError. In all other circumstances a value should be
returned.
*/
#ifndef Py_BUILD_CORE_BUILTIN
# define Py_BUILD_CORE_MODULE 1
#endif
#include "Python.h"
#include "pycore_abstract.h" // _PyNumber_Index()
#include "pycore_bitutils.h" // _Py_bit_length()
#include "pycore_call.h" // _PyObject_CallNoArgs()
#include "pycore_long.h" // _PyLong_GetZero()
#include "pycore_moduleobject.h" // _PyModule_GetState()
#include "pycore_object.h" // _PyObject_LookupSpecial()
#include "pycore_pymath.h" // _PY_SHORT_FLOAT_REPR
/* For DBL_EPSILON in _math.h */
#include <float.h>
/* For _Py_log1p with workarounds for buggy handling of zeros. */
#include "_math.h"
#include <stdbool.h>
#include "clinic/mathmodule.c.h"
/*[clinic input]
module math
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=76bc7002685dd942]*/
typedef struct {
PyObject *str___ceil__;
PyObject *str___floor__;
PyObject *str___trunc__;
} math_module_state;
static inline math_module_state*
get_math_module_state(PyObject *module)
{
void *state = _PyModule_GetState(module);
assert(state != NULL);
return (math_module_state *)state;
}
/*
Double and triple length extended precision algorithms from:
Accurate Sum and Dot Product
by Takeshi Ogita, Siegfried M. Rump, and Shin’Ichi Oishi
https://doi.org/10.1137/030601818
https://www.tuhh.de/ti3/paper/rump/OgRuOi05.pdf
*/
typedef struct{ double hi; double lo; } DoubleLength;
static DoubleLength
dl_fast_sum(double a, double b)
{
/* Algorithm 1.1. Compensated summation of two floating-point numbers. */
assert(fabs(a) >= fabs(b));
double x = a + b;
double y = (a - x) + b;
return (DoubleLength) {x, y};
}
static DoubleLength
dl_sum(double a, double b)
{
/* Algorithm 3.1 Error-free transformation of the sum */
double x = a + b;
double z = x - a;
double y = (a - (x - z)) + (b - z);
return (DoubleLength) {x, y};
}
#ifndef UNRELIABLE_FMA
static DoubleLength
dl_mul(double x, double y)
{
/* Algorithm 3.5. Error-free transformation of a product */
double z = x * y;
double zz = fma(x, y, -z);
return (DoubleLength) {z, zz};
}
#else
/*
The default implementation of dl_mul() depends on the C math library
having an accurate fma() function as required by § 7.12.13.1 of the
C99 standard.
The UNRELIABLE_FMA option is provided as a slower but accurate
alternative for builds where the fma() function is found wanting.
The speed penalty may be modest (17% slower on an Apple M1 Max),
so don't hesitate to enable this build option.
The algorithms are from the T. J. Dekker paper:
A Floating-Point Technique for Extending the Available Precision
https://csclub.uwaterloo.ca/~pbarfuss/dekker1971.pdf
*/
static DoubleLength
dl_split(double x) {
// Dekker (5.5) and (5.6).
double t = x * 134217729.0; // Veltkamp constant = 2.0 ** 27 + 1
double hi = t - (t - x);
double lo = x - hi;
return (DoubleLength) {hi, lo};
}
static DoubleLength
dl_mul(double x, double y)
{
// Dekker (5.12) and mul12()
DoubleLength xx = dl_split(x);
DoubleLength yy = dl_split(y);
double p = xx.hi * yy.hi;
double q = xx.hi * yy.lo + xx.lo * yy.hi;
double z = p + q;
double zz = p - z + q + xx.lo * yy.lo;
return (DoubleLength) {z, zz};
}
#endif
typedef struct { double hi; double lo; double tiny; } TripleLength;
static const TripleLength tl_zero = {0.0, 0.0, 0.0};
static TripleLength
tl_fma(double x, double y, TripleLength total)
{
/* Algorithm 5.10 with SumKVert for K=3 */
DoubleLength pr = dl_mul(x, y);
DoubleLength sm = dl_sum(total.hi, pr.hi);
DoubleLength r1 = dl_sum(total.lo, pr.lo);
DoubleLength r2 = dl_sum(r1.hi, sm.lo);
return (TripleLength) {sm.hi, r2.hi, total.tiny + r1.lo + r2.lo};
}
static double
tl_to_d(TripleLength total)
{
DoubleLength last = dl_sum(total.lo, total.hi);
return total.tiny + last.lo + last.hi;
}
/*
sin(pi*x), giving accurate results for all finite x (especially x
integral or close to an integer). This is here for use in the
reflection formula for the gamma function. It conforms to IEEE
754-2008 for finite arguments, but not for infinities or nans.
*/
static const double pi = 3.141592653589793238462643383279502884197;
static const double logpi = 1.144729885849400174143427351353058711647;
/* Version of PyFloat_AsDouble() with in-line fast paths
for exact floats and integers. Gives a substantial
speed improvement for extracting float arguments.
*/
#define ASSIGN_DOUBLE(target_var, obj, error_label) \
if (PyFloat_CheckExact(obj)) { \
target_var = PyFloat_AS_DOUBLE(obj); \
} \
else if (PyLong_CheckExact(obj)) { \
target_var = PyLong_AsDouble(obj); \
if (target_var == -1.0 && PyErr_Occurred()) { \
goto error_label; \
} \
} \
else { \
target_var = PyFloat_AsDouble(obj); \
if (target_var == -1.0 && PyErr_Occurred()) { \
goto error_label; \
} \
}
static double
m_sinpi(double x)
{
double y, r;
int n;
/* this function should only ever be called for finite arguments */
assert(isfinite(x));
y = fmod(fabs(x), 2.0);
n = (int)round(2.0*y);
assert(0 <= n && n <= 4);
switch (n) {
case 0:
r = sin(pi*y);
break;
case 1:
r = cos(pi*(y-0.5));
break;
case 2:
/* N.B. -sin(pi*(y-1.0)) is *not* equivalent: it would give
-0.0 instead of 0.0 when y == 1.0. */
r = sin(pi*(1.0-y));
break;
case 3:
r = -cos(pi*(y-1.5));
break;
case 4:
r = sin(pi*(y-2.0));
break;
default:
Py_UNREACHABLE();
}
return copysign(1.0, x)*r;
}
/* Implementation of the real gamma function. Kept here to work around
issues (see e.g. gh-70309) with quality of libm's tgamma/lgamma implementations
on various platforms (Windows, MacOS). In extensive but non-exhaustive
random tests, this function proved accurate to within <= 10 ulps across the
entire float domain. Note that accuracy may depend on the quality of the
system math functions, the pow function in particular. Special cases
follow C99 annex F. The parameters and method are tailored to platforms
whose double format is the IEEE 754 binary64 format.
Method: for x > 0.0 we use the Lanczos approximation with parameters N=13
and g=6.024680040776729583740234375; these parameters are amongst those
used by the Boost library. Following Boost (again), we re-express the
Lanczos sum as a rational function, and compute it that way. The
coefficients below were computed independently using MPFR, and have been
double-checked against the coefficients in the Boost source code.
For x < 0.0 we use the reflection formula.
There's one minor tweak that deserves explanation: Lanczos' formula for
Gamma(x) involves computing pow(x+g-0.5, x-0.5) / exp(x+g-0.5). For many x
values, x+g-0.5 can be represented exactly. However, in cases where it
can't be represented exactly the small error in x+g-0.5 can be magnified
significantly by the pow and exp calls, especially for large x. A cheap
correction is to multiply by (1 + e*g/(x+g-0.5)), where e is the error
involved in the computation of x+g-0.5 (that is, e = computed value of
x+g-0.5 - exact value of x+g-0.5). Here's the proof:
Correction factor
-----------------
Write x+g-0.5 = y-e, where y is exactly representable as an IEEE 754
double, and e is tiny. Then:
pow(x+g-0.5,x-0.5)/exp(x+g-0.5) = pow(y-e, x-0.5)/exp(y-e)
= pow(y, x-0.5)/exp(y) * C,
where the correction_factor C is given by
C = pow(1-e/y, x-0.5) * exp(e)
Since e is tiny, pow(1-e/y, x-0.5) ~ 1-(x-0.5)*e/y, and exp(x) ~ 1+e, so:
C ~ (1-(x-0.5)*e/y) * (1+e) ~ 1 + e*(y-(x-0.5))/y
But y-(x-0.5) = g+e, and g+e ~ g. So we get C ~ 1 + e*g/y, and
pow(x+g-0.5,x-0.5)/exp(x+g-0.5) ~ pow(y, x-0.5)/exp(y) * (1 + e*g/y),
Note that for accuracy, when computing r*C it's better to do
r + e*g/y*r;
than
r * (1 + e*g/y);
since the addition in the latter throws away most of the bits of
information in e*g/y.
*/
#define LANCZOS_N 13
static const double lanczos_g = 6.024680040776729583740234375;
static const double lanczos_g_minus_half = 5.524680040776729583740234375;
static const double lanczos_num_coeffs[LANCZOS_N] = {
23531376880.410759688572007674451636754734846804940,
42919803642.649098768957899047001988850926355848959,
35711959237.355668049440185451547166705960488635843,
17921034426.037209699919755754458931112671403265390,
6039542586.3520280050642916443072979210699388420708,
1439720407.3117216736632230727949123939715485786772,
248874557.86205415651146038641322942321632125127801,
31426415.585400194380614231628318205362874684987640,
2876370.6289353724412254090516208496135991145378768,
186056.26539522349504029498971604569928220784236328,
8071.6720023658162106380029022722506138218516325024,
210.82427775157934587250973392071336271166969580291,
2.5066282746310002701649081771338373386264310793408
};
/* denominator is x*(x+1)*...*(x+LANCZOS_N-2) */
static const double lanczos_den_coeffs[LANCZOS_N] = {
0.0, 39916800.0, 120543840.0, 150917976.0, 105258076.0, 45995730.0,
13339535.0, 2637558.0, 357423.0, 32670.0, 1925.0, 66.0, 1.0};
/* gamma values for small positive integers, 1 though NGAMMA_INTEGRAL */
#define NGAMMA_INTEGRAL 23
static const double gamma_integral[NGAMMA_INTEGRAL] = {
1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0,
3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0,
1307674368000.0, 20922789888000.0, 355687428096000.0,
6402373705728000.0, 121645100408832000.0, 2432902008176640000.0,
51090942171709440000.0, 1124000727777607680000.0,
};
/* Lanczos' sum L_g(x), for positive x */
static double
lanczos_sum(double x)
{
double num = 0.0, den = 0.0;
int i;
assert(x > 0.0);
/* evaluate the rational function lanczos_sum(x). For large
x, the obvious algorithm risks overflow, so we instead
rescale the denominator and numerator of the rational
function by x**(1-LANCZOS_N) and treat this as a
rational function in 1/x. This also reduces the error for
larger x values. The choice of cutoff point (5.0 below) is
somewhat arbitrary; in tests, smaller cutoff values than
this resulted in lower accuracy. */
if (x < 5.0) {
for (i = LANCZOS_N; --i >= 0; ) {
num = num * x + lanczos_num_coeffs[i];
den = den * x + lanczos_den_coeffs[i];
}
}
else {
for (i = 0; i < LANCZOS_N; i++) {
num = num / x + lanczos_num_coeffs[i];
den = den / x + lanczos_den_coeffs[i];
}
}
return num/den;
}
static double
m_tgamma(double x)
{
double absx, r, y, z, sqrtpow;
/* special cases */
if (!isfinite(x)) {
if (isnan(x) || x > 0.0)
return x; /* tgamma(nan) = nan, tgamma(inf) = inf */
else {
errno = EDOM;
return Py_NAN; /* tgamma(-inf) = nan, invalid */
}
}
if (x == 0.0) {
errno = EDOM;
/* tgamma(+-0.0) = +-inf, divide-by-zero */
return copysign(Py_INFINITY, x);
}
/* integer arguments */
if (x == floor(x)) {
if (x < 0.0) {
errno = EDOM; /* tgamma(n) = nan, invalid for */
return Py_NAN; /* negative integers n */
}
if (x <= NGAMMA_INTEGRAL)
return gamma_integral[(int)x - 1];
}
absx = fabs(x);
/* tiny arguments: tgamma(x) ~ 1/x for x near 0 */
if (absx < 1e-20) {
r = 1.0/x;
if (isinf(r))
errno = ERANGE;
return r;
}
/* large arguments: assuming IEEE 754 doubles, tgamma(x) overflows for
x > 200, and underflows to +-0.0 for x < -200, not a negative
integer. */
if (absx > 200.0) {
if (x < 0.0) {
return 0.0/m_sinpi(x);
}
else {
errno = ERANGE;
return Py_INFINITY;
}
}
y = absx + lanczos_g_minus_half;
/* compute error in sum */
if (absx > lanczos_g_minus_half) {
/* note: the correction can be foiled by an optimizing
compiler that (incorrectly) thinks that an expression like
a + b - a - b can be optimized to 0.0. This shouldn't
happen in a standards-conforming compiler. */
double q = y - absx;
z = q - lanczos_g_minus_half;
}
else {
double q = y - lanczos_g_minus_half;
z = q - absx;
}
z = z * lanczos_g / y;
if (x < 0.0) {
r = -pi / m_sinpi(absx) / absx * exp(y) / lanczos_sum(absx);
r -= z * r;
if (absx < 140.0) {
r /= pow(y, absx - 0.5);
}
else {
sqrtpow = pow(y, absx / 2.0 - 0.25);
r /= sqrtpow;
r /= sqrtpow;
}
}
else {
r = lanczos_sum(absx) / exp(y);
r += z * r;
if (absx < 140.0) {
r *= pow(y, absx - 0.5);
}
else {
sqrtpow = pow(y, absx / 2.0 - 0.25);
r *= sqrtpow;
r *= sqrtpow;
}
}
if (isinf(r))
errno = ERANGE;
return r;
}
/*
lgamma: natural log of the absolute value of the Gamma function.
For large arguments, Lanczos' formula works extremely well here.
*/
static double
m_lgamma(double x)
{
double r;
double absx;
/* special cases */
if (!isfinite(x)) {
if (isnan(x))
return x; /* lgamma(nan) = nan */
else
return Py_INFINITY; /* lgamma(+-inf) = +inf */
}
/* integer arguments */
if (x == floor(x) && x <= 2.0) {
if (x <= 0.0) {
errno = EDOM; /* lgamma(n) = inf, divide-by-zero for */
return Py_INFINITY; /* integers n <= 0 */
}
else {
return 0.0; /* lgamma(1) = lgamma(2) = 0.0 */
}
}
absx = fabs(x);
/* tiny arguments: lgamma(x) ~ -log(fabs(x)) for small x */
if (absx < 1e-20)
return -log(absx);
/* Lanczos' formula. We could save a fraction of a ulp in accuracy by
having a second set of numerator coefficients for lanczos_sum that
absorbed the exp(-lanczos_g) term, and throwing out the lanczos_g
subtraction below; it's probably not worth it. */
r = log(lanczos_sum(absx)) - lanczos_g;
r += (absx - 0.5) * (log(absx + lanczos_g - 0.5) - 1);
if (x < 0.0)
/* Use reflection formula to get value for negative x. */
r = logpi - log(fabs(m_sinpi(absx))) - log(absx) - r;
if (isinf(r))
errno = ERANGE;
return r;
}
/* IEEE 754-style remainder operation: x - n*y where n*y is the nearest
multiple of y to x, taking n even in the case of a tie. Assuming an IEEE 754
binary floating-point format, the result is always exact. */
static double
m_remainder(double x, double y)
{
/* Deal with most common case first. */
if (isfinite(x) && isfinite(y)) {
double absx, absy, c, m, r;
if (y == 0.0) {
return Py_NAN;
}
absx = fabs(x);
absy = fabs(y);
m = fmod(absx, absy);
/*
Warning: some subtlety here. What we *want* to know at this point is
whether the remainder m is less than, equal to, or greater than half
of absy. However, we can't do that comparison directly because we
can't be sure that 0.5*absy is representable (the multiplication
might incur precision loss due to underflow). So instead we compare
m with the complement c = absy - m: m < 0.5*absy if and only if m <
c, and so on. The catch is that absy - m might also not be
representable, but it turns out that it doesn't matter:
- if m > 0.5*absy then absy - m is exactly representable, by
Sterbenz's lemma, so m > c
- if m == 0.5*absy then again absy - m is exactly representable
and m == c
- if m < 0.5*absy then either (i) 0.5*absy is exactly representable,
in which case 0.5*absy < absy - m, so 0.5*absy <= c and hence m <
c, or (ii) absy is tiny, either subnormal or in the lowest normal
binade. Then absy - m is exactly representable and again m < c.
*/
c = absy - m;
if (m < c) {
r = m;
}
else if (m > c) {
r = -c;
}
else {
/*
Here absx is exactly halfway between two multiples of absy,
and we need to choose the even multiple. x now has the form
absx = n * absy + m
for some integer n (recalling that m = 0.5*absy at this point).
If n is even we want to return m; if n is odd, we need to
return -m.
So
0.5 * (absx - m) = (n/2) * absy
and now reducing modulo absy gives us:
| m, if n is odd
fmod(0.5 * (absx - m), absy) = |
| 0, if n is even
Now m - 2.0 * fmod(...) gives the desired result: m
if n is even, -m if m is odd.
Note that all steps in fmod(0.5 * (absx - m), absy)
will be computed exactly, with no rounding error
introduced.
*/
assert(m == c);
r = m - 2.0 * fmod(0.5 * (absx - m), absy);
}
return copysign(1.0, x) * r;
}
/* Special values. */
if (isnan(x)) {
return x;
}
if (isnan(y)) {
return y;
}
if (isinf(x)) {
return Py_NAN;
}
assert(isinf(y));
return x;
}
/*
Various platforms (Solaris, OpenBSD) do nonstandard things for log(0),
log(-ve), log(NaN). Here are wrappers for log and log10 that deal with
special values directly, passing positive non-special values through to
the system log/log10.
*/
static double
m_log(double x)
{
if (isfinite(x)) {
if (x > 0.0)
return log(x);
errno = EDOM;
if (x == 0.0)
return -Py_INFINITY; /* log(0) = -inf */
else
return Py_NAN; /* log(-ve) = nan */
}
else if (isnan(x))
return x; /* log(nan) = nan */
else if (x > 0.0)
return x; /* log(inf) = inf */
else {
errno = EDOM;
return Py_NAN; /* log(-inf) = nan */
}
}
/*
log2: log to base 2.
Uses an algorithm that should:
(a) produce exact results for powers of 2, and
(b) give a monotonic log2 (for positive finite floats),
assuming that the system log is monotonic.
*/
static double
m_log2(double x)
{
if (!isfinite(x)) {
if (isnan(x))
return x; /* log2(nan) = nan */
else if (x > 0.0)
return x; /* log2(+inf) = +inf */
else {
errno = EDOM;
return Py_NAN; /* log2(-inf) = nan, invalid-operation */
}
}
if (x > 0.0) {
return log2(x);
}
else if (x == 0.0) {
errno = EDOM;
return -Py_INFINITY; /* log2(0) = -inf, divide-by-zero */
}
else {
errno = EDOM;
return Py_NAN; /* log2(-inf) = nan, invalid-operation */
}
}
static double
m_log10(double x)
{
if (isfinite(x)) {
if (x > 0.0)
return log10(x);
errno = EDOM;
if (x == 0.0)
return -Py_INFINITY; /* log10(0) = -inf */
else
return Py_NAN; /* log10(-ve) = nan */
}
else if (isnan(x))
return x; /* log10(nan) = nan */
else if (x > 0.0)
return x; /* log10(inf) = inf */
else {
errno = EDOM;
return Py_NAN; /* log10(-inf) = nan */
}
}
/*[clinic input]
math.gcd
*integers as args: array
Greatest Common Divisor.
[clinic start generated code]*/
static PyObject *
math_gcd_impl(PyObject *module, PyObject * const *args,
Py_ssize_t args_length)
/*[clinic end generated code: output=a26c95907374ffb4 input=ded7f0ea3850c05c]*/
{
// Fast-path for the common case: gcd(int, int)
if (args_length == 2 && PyLong_CheckExact(args[0]) && PyLong_CheckExact(args[1]))
{
return _PyLong_GCD(args[0], args[1]);
}
if (args_length == 0) {
return PyLong_FromLong(0);
}
PyObject *res = PyNumber_Index(args[0]);
if (res == NULL) {
return NULL;
}
if (args_length == 1) {
Py_SETREF(res, PyNumber_Absolute(res));
return res;
}
PyObject *one = _PyLong_GetOne(); // borrowed ref
for (Py_ssize_t i = 1; i < args_length; i++) {
PyObject *x = _PyNumber_Index(args[i]);
if (x == NULL) {
Py_DECREF(res);
return NULL;
}
if (res == one) {
/* Fast path: just check arguments.
It is okay to use identity comparison here. */
Py_DECREF(x);
continue;
}
Py_SETREF(res, _PyLong_GCD(res, x));
Py_DECREF(x);
if (res == NULL) {
return NULL;
}
}
return res;
}
static PyObject *
long_lcm(PyObject *a, PyObject *b)
{
PyObject *g, *m, *f, *ab;
if (_PyLong_IsZero((PyLongObject *)a) || _PyLong_IsZero((PyLongObject *)b)) {
return PyLong_FromLong(0);
}
g = _PyLong_GCD(a, b);
if (g == NULL) {
return NULL;
}
f = PyNumber_FloorDivide(a, g);
Py_DECREF(g);
if (f == NULL) {
return NULL;
}
m = PyNumber_Multiply(f, b);
Py_DECREF(f);
if (m == NULL) {
return NULL;
}
ab = PyNumber_Absolute(m);
Py_DECREF(m);
return ab;
}
/*[clinic input]
math.lcm
*integers as args: array
Least Common Multiple.
[clinic start generated code]*/
static PyObject *
math_lcm_impl(PyObject *module, PyObject * const *args,
Py_ssize_t args_length)
/*[clinic end generated code: output=c8a59a5c2e55c816 input=3e4f4b7cdf948a98]*/
{
PyObject *res, *x;
Py_ssize_t i;
if (args_length == 0) {
return PyLong_FromLong(1);
}
res = PyNumber_Index(args[0]);
if (res == NULL) {
return NULL;
}
if (args_length == 1) {
Py_SETREF(res, PyNumber_Absolute(res));
return res;
}
PyObject *zero = _PyLong_GetZero(); // borrowed ref
for (i = 1; i < args_length; i++) {
x = PyNumber_Index(args[i]);
if (x == NULL) {
Py_DECREF(res);
return NULL;
}
if (res == zero) {
/* Fast path: just check arguments.
It is okay to use identity comparison here. */
Py_DECREF(x);
continue;
}
Py_SETREF(res, long_lcm(res, x));
Py_DECREF(x);
if (res == NULL) {
return NULL;
}
}
return res;
}
/* Call is_error when errno != 0, and where x is the result libm
* returned. is_error will usually set up an exception and return
* true (1), but may return false (0) without setting up an exception.
*/
static int
is_error(double x)
{
int result = 1; /* presumption of guilt */
assert(errno); /* non-zero errno is a precondition for calling */
if (errno == EDOM)
PyErr_SetString(PyExc_ValueError, "math domain error");
else if (errno == ERANGE) {
/* ANSI C generally requires libm functions to set ERANGE
* on overflow, but also generally *allows* them to set
* ERANGE on underflow too. There's no consistency about
* the latter across platforms.
* Alas, C99 never requires that errno be set.
* Here we suppress the underflow errors (libm functions
* should return a zero on underflow, and +- HUGE_VAL on
* overflow, so testing the result for zero suffices to
* distinguish the cases).
*
* On some platforms (Ubuntu/ia64) it seems that errno can be
* set to ERANGE for subnormal results that do *not* underflow
* to zero. So to be safe, we'll ignore ERANGE whenever the
* function result is less than 1.5 in absolute value.
*
* bpo-46018: Changed to 1.5 to ensure underflows in expm1()
* are correctly detected, since the function may underflow
* toward -1.0 rather than 0.0.
*/
if (fabs(x) < 1.5)
result = 0;
else
PyErr_SetString(PyExc_OverflowError,
"math range error");
}
else
/* Unexpected math error */
PyErr_SetFromErrno(PyExc_ValueError);
return result;
}
/*
math_1 is used to wrap a libm function f that takes a double
argument and returns a double.
The error reporting follows these rules, which are designed to do
the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
platforms.
- a NaN result from non-NaN inputs causes ValueError to be raised
- an infinite result from finite inputs causes OverflowError to be
raised if can_overflow is 1, or raises ValueError if can_overflow
is 0.
- if the result is finite and errno == EDOM then ValueError is
raised
- if the result is finite and nonzero and errno == ERANGE then
OverflowError is raised
The last rule is used to catch overflow on platforms which follow
C89 but for which HUGE_VAL is not an infinity.
For the majority of one-argument functions these rules are enough
to ensure that Python's functions behave as specified in 'Annex F'
of the C99 standard, with the 'invalid' and 'divide-by-zero'
floating-point exceptions mapping to Python's ValueError and the
'overflow' floating-point exception mapping to OverflowError.
math_1 only works for functions that don't have singularities *and*
the possibility of overflow; fortunately, that covers everything we
care about right now.
*/
static PyObject *
math_1(PyObject *arg, double (*func) (double), int can_overflow)
{
double x, r;
x = PyFloat_AsDouble(arg);
if (x == -1.0 && PyErr_Occurred())
return NULL;
errno = 0;
r = (*func)(x);
if (isnan(r) && !isnan(x)) {
PyErr_SetString(PyExc_ValueError,
"math domain error"); /* invalid arg */
return NULL;
}
if (isinf(r) && isfinite(x)) {
if (can_overflow)
PyErr_SetString(PyExc_OverflowError,
"math range error"); /* overflow */
else
PyErr_SetString(PyExc_ValueError,
"math domain error"); /* singularity */
return NULL;
}
if (isfinite(r) && errno && is_error(r))
/* this branch unnecessary on most platforms */
return NULL;
return PyFloat_FromDouble(r);
}
/* variant of math_1, to be used when the function being wrapped is known to
set errno properly (that is, errno = EDOM for invalid or divide-by-zero,
errno = ERANGE for overflow). */
static PyObject *
math_1a(PyObject *arg, double (*func) (double))
{
double x, r;
x = PyFloat_AsDouble(arg);
if (x == -1.0 && PyErr_Occurred())
return NULL;
errno = 0;
r = (*func)(x);
if (errno && is_error(r))
return NULL;
return PyFloat_FromDouble(r);
}
/*
math_2 is used to wrap a libm function f that takes two double
arguments and returns a double.
The error reporting follows these rules, which are designed to do
the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
platforms.
- a NaN result from non-NaN inputs causes ValueError to be raised
- an infinite result from finite inputs causes OverflowError to be
raised.
- if the result is finite and errno == EDOM then ValueError is
raised
- if the result is finite and nonzero and errno == ERANGE then
OverflowError is raised
The last rule is used to catch overflow on platforms which follow
C89 but for which HUGE_VAL is not an infinity.
For most two-argument functions (copysign, fmod, hypot, atan2)
these rules are enough to ensure that Python's functions behave as
specified in 'Annex F' of the C99 standard, with the 'invalid' and
'divide-by-zero' floating-point exceptions mapping to Python's