Debian Codegraph @

pypy/module/math/test/test_math.py

raw symbols SCIP
1 import py
2 import sys
3 from pypy.interpreter.function import Function
4 from pypy.interpreter.gateway import BuiltinCode
5 from pypy.module.math.test import test_direct
6 from rpython.rlib.rfloat import INFINITY, NAN
7
8 class AppTestMath:
9 spaceconfig = {
10 "usemodules": ['math', 'struct', 'itertools', 'time', 'binascii'],
11 }
12
13 def setup_class(cls):
14 from rpython.rtyper.lltypesystem.module.test import math_cases
15 filename = math_cases.__file__
16 if filename.endswith('.pyc'):
17 filename = filename[:-1]
18 space = cls.space
19 cls.w_math_cases = space.wrap(filename)
20 cls.w_maxint = space.wrap(sys.maxint)
21
22 @classmethod
23 def make_callable_wrapper(cls, func):
24 def f(space, w_x):
25 return space.wrap(func(space.unwrap(w_x)))
26 return Function(cls.space, BuiltinCode(f))
27
28 def w_ftest(self, actual, expected):
29 assert abs(actual - expected) < 10E-5
30
31 def w_cases(self):
32 with open(self.math_cases) as f:
33 mod = compile(f.read(), "math_cases.py", "exec")
34 ns = {}
35 eval(mod, ns)
36 TESTCASES = ns['MathTests'].TESTCASES
37 INFINITY = ns['INFINITY']
38 NAN = ns['NAN']
39
40 for fnname, args, expected in TESTCASES:
41 # marked as OverflowError to match 2.x/ll_math in
42 # test_direct, but this is a ValueError on 3.x
43 if (fnname, args, expected) == ('log1p', (-1.0,), OverflowError):
44 expected = ValueError
45 # 3.x ceil/floor differ from 2.x
46 if fnname in ('ceil', 'floor'):
47 if args[0] in (INFINITY, -INFINITY):
48 expected = OverflowError
49 elif args[0] is NAN:
50 expected = ValueError
51
52 yield fnname, args, expected
53
54 def test_all_cases(self):
55 import math
56 for fnname, args, expected in self.cases():
57 fn = getattr(math, fnname)
58 print(fn, args, expected)
59 try:
60 got = fn(*args)
61 except ValueError:
62 assert expected == ValueError
63 except OverflowError:
64 assert expected == OverflowError
65 else:
66 if type(expected) is type(Exception):
67 ok = False
68 elif callable(expected):
69 ok = expected(got)
70 else:
71 gotsign = expectedsign = 1
72 if got < 0.0: gotsign = -gotsign
73 if expected < 0.0: expectedsign = -expectedsign
74 ok = got == expected and gotsign == expectedsign
75 if not ok:
76 raise AssertionError("%s(%s): got %s" % (
77 fnname, ', '.join(map(str, args)), got))
78
79 def test_ldexp(self):
80 import math
81 assert math.ldexp(float("inf"), -10**20) == float("inf")
82
83 def test_fsum(self):
84 import math
85
86 # detect evidence of double-rounding: fsum is not always correctly
87 # rounded on machines that suffer from double rounding.
88 # It is a known problem with IA32 floating-point arithmetic.
89 # It should work fine e.g. with x86-64.
90 x, y = 1e16, 2.9999 # use temporary values to defeat peephole optimizer
91 HAVE_DOUBLE_ROUNDING = (x + y == 1e16 + 4)
92 if HAVE_DOUBLE_ROUNDING:
93 skip("fsum is not exact on machines with double rounding")
94
95 test_values = [
96 ([], 0.0),
97 ([0.0], 0.0),
98 ([1e100, 1.0, -1e100, 1e-100, 1e50, -1.0, -1e50], 1e-100),
99 ([2.0**53, -0.5, -2.0**-54], 2.0**53-1.0),
100 ([2.0**53, 1.0, 2.0**-100], 2.0**53+2.0),
101 ([2.0**53+10.0, 1.0, 2.0**-100], 2.0**53+12.0),
102 ([2.0**53-4.0, 0.5, 2.0**-54], 2.0**53-3.0),
103 ([1./n for n in range(1, 1001)],
104 float.fromhex('0x1.df11f45f4e61ap+2')),
105 ([(-1.)**n/n for n in range(1, 1001)],
106 float.fromhex('-0x1.62a2af1bd3624p-1')),
107 ([1.7**(i+1)-1.7**i for i in range(1000)] + [-1.7**1000], -1.0),
108 ([1e16, 1., 1e-16], 10000000000000002.0),
109 ([1e16-2., 1.-2.**-53, -(1e16-2.), -(1.-2.**-53)], 0.0),
110 # exercise code for resizing partials array
111 ([2.**n - 2.**(n+50) + 2.**(n+52) for n in range(-1074, 972, 2)] +
112 [-2.**1022],
113 float.fromhex('0x1.5555555555555p+970')),
114 # infinity and nans
115 ([float("inf")], float("inf")),
116 ([float("-inf")], float("-inf")),
117 ([float("nan")], float("nan")),
118 ]
119
120 for i, (vals, expected) in enumerate(test_values):
121 try:
122 actual = math.fsum(vals)
123 except OverflowError:
124 py.test.fail("test %d failed: got OverflowError, expected %r "
125 "for math.fsum(%.100r)" % (i, expected, vals))
126 except ValueError:
127 py.test.fail("test %d failed: got ValueError, expected %r "
128 "for math.fsum(%.100r)" % (i, expected, vals))
129 assert actual == expected or (
130 math.isnan(actual) and math.isnan(expected))
131
132 def test_factorial(self):
133 import math, sys
134 assert math.factorial(0) == 1
135 assert math.factorial(1) == 1
136 assert math.factorial(2) == 2
137 assert math.factorial(5) == 120
138 raises(TypeError, math.factorial, 5.0)
139 raises(ValueError, math.factorial, -1)
140 raises(TypeError, math.factorial, -1.0)
141 raises(TypeError, math.factorial, 1.1)
142 raises(OverflowError, math.factorial, sys.maxsize+1)
143
144 def test_log1p(self):
145 import math
146 self.ftest(math.log1p(1/math.e-1), -1)
147 self.ftest(math.log1p(0), 0)
148 self.ftest(math.log1p(math.e-1), 1)
149 self.ftest(math.log1p(1), math.log(2))
150 raises(ValueError, math.log1p, -1)
151 raises(ValueError, math.log1p, -100)
152
153 def test_log2(self):
154 import math
155 self.ftest(math.log2(0.125), -3)
156 self.ftest(math.log2(0.5), -1)
157 self.ftest(math.log2(4), 2)
158
159 def test_log10(self):
160 import math
161 self.ftest(math.log10(0.1), -1)
162 self.ftest(math.log10(10), 1)
163 self.ftest(math.log10(100), 2)
164 self.ftest(math.log10(0.01), -2)
165
166 def test_log_largevalue(self):
167 import math
168 assert math.log2(2**1234) == 1234.0
169
170 def test_acosh(self):
171 import math
172 self.ftest(math.acosh(1), 0)
173 self.ftest(math.acosh(2), 1.3169578969248168)
174 assert math.isinf(math.asinh(float("inf")))
175 raises(ValueError, math.acosh, 0)
176
177 def test_asinh(self):
178 import math
179 self.ftest(math.asinh(0), 0)
180 self.ftest(math.asinh(1), 0.88137358701954305)
181 self.ftest(math.asinh(-1), -0.88137358701954305)
182 assert math.isinf(math.asinh(float("inf")))
183
184 def test_atanh(self):
185 import math
186 self.ftest(math.atanh(0), 0)
187 self.ftest(math.atanh(0.5), 0.54930614433405489)
188 self.ftest(math.atanh(-0.5), -0.54930614433405489)
189 raises(ValueError, math.atanh, 1.)
190 assert math.isnan(math.atanh(float("nan")))
191
192 def test_trunc(self):
193 import math
194 assert math.trunc(1.9) == 1.0
195 raises((AttributeError, TypeError), math.trunc, 1.9j)
196 class foo(object):
197 def __trunc__(self):
198 return "truncated"
199 assert math.trunc(foo()) == "truncated"
200
201 def test_copysign_nan(self):
202 skip('sign of nan is undefined')
203 import math
204 assert math.copysign(1.0, float('-nan')) == -1.0
205
206 def test_special_methods(self):
207 import math
208 class Z:
209 pass
210 for i, name in enumerate(('ceil', 'floor', 'trunc')):
211 setattr(Z, '__{}__'.format(name), lambda self: i)
212 func = getattr(math, name)
213 assert func(Z()) == i
214
215 def test_int_results(self):
216 import math
217 for func in math.ceil, math.floor:
218 assert type(func(0.5)) is int
219 raises(OverflowError, func, float('inf'))
220 raises(ValueError, func, float('nan'))
221
222 def test_ceil(self):
223 # adapted from the cpython test case
224 import math
225 raises(TypeError, math.ceil)
226 assert type(math.ceil(0.4)) is int
227 assert math.ceil(0.5) == 1
228 assert math.ceil(1.0) == 1
229 assert math.ceil(1.5) == 2
230 assert math.ceil(-0.5) == 0
231 assert math.ceil(-1.0) == -1
232 assert math.ceil(-1.5) == -1
233
234 class TestCeil:
235 def __ceil__(self):
236 return 42
237 class TestNoCeil:
238 pass
239 assert math.ceil(TestCeil()) == 42
240 raises(TypeError, math.ceil, TestNoCeil())
241
242 t = TestNoCeil()
243 t.__ceil__ = lambda *args: args
244 raises(TypeError, math.ceil, t)
245 raises(TypeError, math.ceil, t, 0)
246
247 # observed in a cpython interactive shell
248 raises(OverflowError, math.ceil, float("inf"))
249 raises(OverflowError, math.ceil, float("-inf"))
250 raises(ValueError, math.ceil, float("nan"))
251
252 class StrangeCeil:
253 def __ceil__(self):
254 return "this is a string"
255
256 assert math.ceil(StrangeCeil()) == "this is a string"
257
258 class CustomFloat:
259 def __float__(self):
260 return 99.9
261
262 assert math.ceil(CustomFloat()) == 100
263
264 def test_floor(self):
265 # adapted from the cpython test case
266 import math
267 raises(TypeError, math.floor)
268 assert type(math.floor(0.4)) is int
269 assert math.floor(0.5) == 0
270 assert math.floor(1.0) == 1
271 assert math.floor(1.5) == 1
272 assert math.floor(-0.5) == -1
273 assert math.floor(-1.0) == -1
274 assert math.floor(-1.5) == -2
275 assert math.floor(1.23e167) == int(1.23e167)
276 assert math.floor(-1.23e167) == int(-1.23e167)
277
278 class TestFloor:
279 def __floor__(self):
280 return 42
281 class TestNoFloor:
282 pass
283 assert math.floor(TestFloor()) == 42
284 raises(TypeError, math.floor, TestNoFloor())
285
286 t = TestNoFloor()
287 t.__floor__ = lambda *args: args
288 raises(TypeError, math.floor, t)
289 raises(TypeError, math.floor, t, 0)
290
291 # observed in a cpython interactive shell
292 raises(OverflowError, math.floor, float("inf"))
293 raises(OverflowError, math.floor, float("-inf"))
294 raises(ValueError, math.floor, float("nan"))
295
296 class StrangeCeil:
297 def __floor__(self):
298 return "this is a string"
299
300 assert math.floor(StrangeCeil()) == "this is a string"
301
302 assert math.floor(1.23e167) - 1.23e167 == 0.0
303
304 class CustomFloat:
305 def __float__(self):
306 return 99.9
307
308 assert math.floor(CustomFloat()) == 99
309
310 def test_erf(self):
311 import math
312 assert math.erf(100.0) == 1.0
313 assert math.erf(-1000.0) == -1.0
314 assert math.erf(float("inf")) == 1.0
315 assert math.erf(float("-inf")) == -1.0
316 assert math.isnan(math.erf(float("nan")))
317 # proper tests are in rpython/rlib/test/test_rfloat
318 assert round(math.erf(1.0), 9) == 0.842700793
319
320 def test_erfc(self):
321 import math
322 assert math.erfc(0.0) == 1.0
323 assert math.erfc(-0.0) == 1.0
324 assert math.erfc(float("inf")) == 0.0
325 assert math.erfc(float("-inf")) == 2.0
326 assert math.isnan(math.erf(float("nan")))
327 assert math.erfc(1e-308) == 1.0
328
329 def test_gamma(self):
330 import math
331 assert raises(ValueError, math.gamma, 0.0)
332 assert math.gamma(5.0) == 24.0
333 assert math.gamma(6.0) == 120.0
334 assert raises(ValueError, math.gamma, -1)
335 assert math.gamma(0.5) == math.pi ** 0.5
336
337 def test_lgamma(self):
338 import math
339 math.lgamma(1.0) == 0.0
340 math.lgamma(2.0) == 0.0
341 # proper tests are in rpython/rlib/test/test_rfloat
342 assert round(math.lgamma(5.0), 9) == round(math.log(24.0), 9)
343 assert round(math.lgamma(6.0), 9) == round(math.log(120.0), 9)
344 assert raises(ValueError, math.gamma, -1)
345 assert round(math.lgamma(0.5), 9) == round(math.log(math.pi ** 0.5), 9)
346
347 def test_isclose(self):
348 import math
349 assert math.isclose(0, 1) is False
350 assert math.isclose(0, 0.0) is True
351 assert math.isclose(1000.1, 1000.2, abs_tol=0.2) is True
352 assert math.isclose(1000.1, 1000.2, rel_tol=1e-3) is True
353 assert math.isclose(1000.1, 1000.2, abs_tol=0.02) is False
354 assert math.isclose(1000.1, 1000.2, rel_tol=1e-5) is False
355 assert math.isclose(float("inf"), float("inf")) is True
356 assert math.isclose(float("-inf"), float("-inf")) is True
357 assert math.isclose(float("inf"), float("-inf")) is False
358 assert math.isclose(float("-inf"), float("inf")) is False
359 assert math.isclose(float("-inf"), 12.34) is False
360 assert math.isclose(float("-inf"), float("nan")) is False
361 assert math.isclose(float("nan"), 12.34) is False
362 assert math.isclose(float("nan"), float("nan")) is False
363 #
364 raises(TypeError, math.isclose, 0, 1, rel_tol=None)
365 raises(TypeError, math.isclose, 0, 1, abs_tol=None)
366
367 def test_gcd(self):
368 import math
369 assert math.gcd(-4, -10) == 2
370 assert math.gcd(0, -10) == 10
371 assert math.gcd(0, 0) == 0
372 raises(TypeError, math.gcd, 0, 0.0)
373 raises(TypeError, math.gcd, 0.0)
374 assert math.gcd(-3**10*5**20*11**8, 2**5*3**5*7**20) == 3**5
375 assert math.gcd(64, 200) == 8
376
377 assert math.gcd(-self.maxint-1, 3) == 1
378 assert math.gcd(-self.maxint-1, -self.maxint-1) == self.maxint+1
379 assert math.gcd() == 0
380 assert math.gcd(2, 4, 6, 8) == 2
381 assert math.gcd(36) == 36
382 assert math.gcd(-36) == 36
383
384 def test_lcm(self):
385 import math
386 assert math.lcm() == 1
387 assert math.lcm(-5) == 5
388 assert math.lcm(5) == 5
389 assert math.lcm(6, 10) == 30
390 assert math.lcm(6, 10, 14) == 210
391 assert math.lcm(0, 0) == 0
392 assert math.lcm(0, 1) == 0
393 assert math.lcm(1, 0) == 0
394 assert math.lcm(3, 5, 7, 0) == 0
395 raises(TypeError, math.lcm, 12.0)
396
397 def test_inf_nan(self):
398 import math
399 assert math.isinf(math.inf)
400 assert math.inf > -math.inf
401 assert math.isnan(math.nan)
402
403 def test_pi_tau(self):
404 import math
405 assert math.tau == math.pi * 2.0
406
407 def test_remainder(self):
408 import math
409 assert math.remainder(3, math.pi) == 3 - math.pi
410 assert math.remainder(-3, math.pi) == math.pi - 3
411 assert math.remainder(3, -math.pi) == 3 - math.pi
412 assert math.remainder(4, math.pi) == 4 - math.pi
413 assert math.remainder(6, math.pi) == 6 - 2 * math.pi
414 assert math.remainder(3, math.inf) == 3
415 assert math.remainder(3, -math.inf) == 3
416 assert math.isnan(math.remainder(3, math.nan))
417 assert math.isnan(math.remainder(math.nan, 3))
418 raises(ValueError, math.remainder, 3, 0)
419 raises(ValueError, math.remainder, math.inf, 3)
420 raises(TypeError, math.remainder, "abc", 1)
421
422 def test_isqrt(self):
423 import math
424 x = math.isqrt(9)
425 assert x == 3
426 assert type(x) is int
427
428 test_values = list(range(10)) + [1 << 100 - 1]
429
430 for value in test_values:
431 s = math.isqrt(value)
432 assert type(s) is int
433 assert s*s <= value
434 assert value < (s+1)*(s+1)
435
436 with raises(ValueError):
437 math.isqrt(-1)
438
439 def test_pow_zero_ninf(self):
440 import math
441 assert math.pow(0.0, -float('inf')) == float('inf')
442 assert math.pow(-0.0, -float('inf')) == float('inf')
443
444 def test_exp2(self):
445 import math
446 from math import exp2
447 for i in range(-100, 100):
448 assert exp2(float(i)) == 2.0 ** i
449 assert exp2(float('inf')) == float('inf')
450 assert exp2(-float('inf')) == 0.0
451 assert math.isnan(exp2(-float('nan')))
452 with raises(OverflowError):
453 exp2(10000000)
454
455 def test_cbrt(self):
456 import math
457 from math import cbrt
458 assert cbrt(0.0) == 0.0
459 assert cbrt(1.0) == 1.0
460 assert cbrt(8.0) == 2.0
461 assert cbrt(0.0) == 0.0
462 assert cbrt(-1.0) == -1.0
463 assert cbrt(float('inf')) == float('inf')
464 assert cbrt(-float('inf')) == -float('inf')
465 assert math.isnan(cbrt(float('nan')))
466