Debian Codegraph @

pypy/module/math/app_math.py

raw symbols SCIP
1 import sys
2 try:
3 from _operator import index
4 except ImportError:
5 pass # for tests only
6
7 def factorial(n, /):
8 """factorial(n, /) -> int
9
10 Find n!. Raise a ValueError if n is negative or non-integral."""
11 if '__index__' not in dir(n):
12 raise TypeError("'%s' object cannot be interpreted as an integer" % type(n).__name__)
13 if n > sys.maxsize:
14 raise OverflowError("Too large for a factorial")
15
16 if n <= 100:
17 if n < 0:
18 raise ValueError("n must be a non-negative integer")
19 res = 1
20 for i in range(2, n + 1):
21 res *= i
22 return res
23
24 # Experimentally this gap seems good
25 gap = max(100, n >> 7)
26 def _fac_odd(low, high):
27 if low + gap >= high:
28 t = 1
29 for i in range(low, high, 2):
30 t *= i
31 return t
32
33 mid = ((low + high) >> 1) | 1
34 return _fac_odd(low, mid) * _fac_odd(mid, high)
35
36 def _fac1(x):
37 if x <= 2:
38 return 1, 1, x - 1
39 x2 = x >> 1
40 f, g, shift = _fac1(x2)
41 g *= _fac_odd((x2 + 1) | 1, x + 1)
42 return (f * g, g, shift + x2)
43
44 res, _, shift = _fac1(n)
45 return res << shift
46
47
48 def remainder(x, y):
49 """Difference between x and the closest integer multiple of y.
50
51 Return x - n*y where n*y is the closest integer multiple of y.
52 In the case where x is exactly halfway between two multiples of
53 y, the nearest even value of n is used. The result is always exact."""
54
55 from math import copysign, fabs, fmod, isfinite, isinf, isnan, nan
56
57 try:
58 x = float(x)
59 except ValueError:
60 raise TypeError("must be real number, not %s" % (type(x).__name__, ))
61 y = float(y)
62
63 # Deal with most common case first.
64 if isfinite(x) and isfinite(y):
65 if y == 0.0:
66 # return nan
67 # Merging the logic from math_2 in CPython's mathmodule.c
68 # nan returned and x and y both not nan -> domain error
69 raise ValueError("math domain error")
70
71 absx = fabs(x)
72 absy = fabs(y)
73 m = fmod(absx, absy)
74
75 # Warning: some subtlety here. What we *want* to know at this point is
76 # whether the remainder m is less than, equal to, or greater than half
77 # of absy. However, we can't do that comparison directly because we
78 # can't be sure that 0.5*absy is representable (the mutiplication
79 # might incur precision loss due to underflow). So instead we compare
80 # m with the complement c = absy - m: m < 0.5*absy if and only if m <
81 # c, and so on. The catch is that absy - m might also not be
82 # representable, but it turns out that it doesn't matter:
83 # - if m > 0.5*absy then absy - m is exactly representable, by
84 # Sterbenz's lemma, so m > c
85 # - if m == 0.5*absy then again absy - m is exactly representable
86 # and m == c
87 # - if m < 0.5*absy then either (i) 0.5*absy is exactly representable,
88 # in which case 0.5*absy < absy - m, so 0.5*absy <= c and hence m <
89 # c, or (ii) absy is tiny, either subnormal or in the lowest normal
90 # binade. Then absy - m is exactly representable and again m < c.
91
92 c = absy - m
93 if m < c:
94 r = m
95 elif m > c:
96 r = -c
97 else:
98 # Here absx is exactly halfway between two multiples of absy,
99 # and we need to choose the even multiple. x now has the form
100 # absx = n * absy + m
101 # for some integer n (recalling that m = 0.5*absy at this point).
102 # If n is even we want to return m; if n is odd, we need to
103 # return -m.
104 # So
105 # 0.5 * (absx - m) = (n/2) * absy
106 # and now reducing modulo absy gives us:
107 # | m, if n is odd
108 # fmod(0.5 * (absx - m), absy) = |
109 # | 0, if n is even
110 # Now m - 2.0 * fmod(...) gives the desired result: m
111 # if n is even, -m if m is odd.
112 # Note that all steps in fmod(0.5 * (absx - m), absy)
113 # will be computed exactly, with no rounding error
114 # introduced.
115 assert m == c
116 r = m - 2.0 * fmod(0.5 * (absx - m), absy)
117 return copysign(1.0, x) * r
118
119 # Special values.
120 if isnan(x):
121 return x
122 if isnan(y):
123 return y
124 if isinf(x):
125 # return nan
126 # Merging the logic from math_2 in CPython's mathmodule.c
127 # nan returned and x and y both not nan -> domain error
128 raise ValueError("math domain error")
129 assert isinf(y)
130 return x
131
132
133 def isqrt(n, /):
134 """
135 Return the integer part of the square root of the input.
136 """
137 n = index(n)
138
139 if n < 0:
140 raise ValueError("isqrt() argument must be nonnegative")
141 if n == 0:
142 return 0
143
144 c = (n.bit_length() - 1) // 2
145 a = 1
146 d = 0
147 for s in reversed(range(c.bit_length())):
148 # Loop invariant: (a-1)**2 < (n >> 2*(c - d)) < (a+1)**2
149 e = d
150 d = c >> s
151 a = (a << d - e - 1) + (n >> 2*c - e - d + 1) // a
152
153 return a - (a*a > n)
154
155 def prod(iterable, /, *, start=1):
156 """
157 Calculate the product of all the elements in the input iterable.
158
159 The default start value for the product is 1.
160
161 When the iterable is empty, return the start value. This function is
162 intended specifically for use with numeric values and may reject
163 non-numeric types.
164 """
165 res = start
166 for x in iterable:
167 res = res * x
168 return res
169
170 def comb(n, k, /):
171 """
172 Number of ways to choose k items from n items without repetition and without order.
173
174 Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates
175 to zero when k > n.
176
177 Also called the binomial coefficient because it is equivalent
178 to the coefficient of k-th term in polynomial expansion of the
179 expression (1 + x)**n.
180
181 Raises TypeError if either of the arguments are not integers.
182 Raises ValueError if either of the arguments are negative.
183 """
184 n = index(n)
185 k = index(k)
186
187 if n < 0:
188 raise ValueError("n must be a non-negative integer")
189 if k < 0:
190 raise ValueError("k must be a non-negative integer")
191 if k > n:
192 return 0
193
194 k = min(k, n-k)
195 if k == 0:
196 return 1
197
198 num, den = n, 1
199 for i in range(1, k):
200 num *= n - i
201 den *= i + 1
202 # reduce the fraction occasionally, but not after every multiplication
203 if i & 15 == 0:
204 num //= den
205 den = 1
206
207 return num // den
208
209 def perm(n, k=None, /):
210 """
211 Number of ways to choose k items from n items without repetition and with order.
212
213 Evaluates to n! / (n - k)! when k <= n and evaluates
214 to zero when k > n.
215
216 If k is not specified or is None, then k defaults to n
217 and the function returns n!.
218
219 Raises TypeError if either of the arguments are not integers.
220 Raises ValueError if either of the arguments are negative.
221 """
222
223 n = index(n)
224 if k is None:
225 k = n
226 else:
227 k = index(k)
228
229 if n < 0:
230 raise ValueError("n must be a non-negative integer")
231 if k < 0:
232 raise ValueError("k must be a non-negative integer")
233 if k > n:
234 return 0
235
236 if k <= 100:
237 res = 1
238 for x in range(n, n - k, -1):
239 res *= x
240 return res
241
242 gap = max(100, k >> 7)
243 def _prod_range(low, high):
244 if low + gap >= high:
245 t = 1
246 for i in range(low, high):
247 t *= i
248 return t
249
250 mid = (low + high) >> 1
251 return _prod_range(low, mid) * _prod_range(mid, high)
252
253 return _prod_range(n - k + 1, n + 1)
254
255
256 def lcm(*integers):
257 import math
258 if not integers:
259 return 1
260 if len(integers) == 1:
261 return abs(index(integers[0]))
262 if len(integers) == 2:
263 a, b = integers
264 a, b = index(a), index(b)
265 if a == 0 or b == 0:
266 return 0
267 return abs(a // math.gcd(a, b) * b)
268 res = index(integers[0])
269 if res == 0:
270 return res
271 for i in range(1, len(integers)):
272 v = index(integers[i])
273 if v == 0:
274 return 0
275 res = abs(res // math.gcd(res, v) * v)
276 return res