Debian Codegraph @

Lib/test/test_math.py

raw
1 # Python test set -- math module
2 # XXXX Should not do tests around zero only
3
4 from test.support import verbose, requires_IEEE_754
5 from test import support
6 import unittest
7 import fractions
8 import itertools
9 import decimal
10 import math
11 import os
12 import platform
13 import random
14 import struct
15 import sys
16
17
18 eps = 1E-05
19 NAN = float('nan')
20 INF = float('inf')
21 NINF = float('-inf')
22 FLOAT_MAX = sys.float_info.max
23 FLOAT_MIN = sys.float_info.min
24
25 # detect evidence of double-rounding: fsum is not always correctly
26 # rounded on machines that suffer from double rounding.
27 x, y = 1e16, 2.9999 # use temporary values to defeat peephole optimizer
28 HAVE_DOUBLE_ROUNDING = (x + y == 1e16 + 4)
29
30 # locate file with test values
31 if __name__ == '__main__':
32 file = sys.argv[0]
33 else:
34 file = __file__
35 test_dir = os.path.dirname(file) or os.curdir
36 math_testcases = os.path.join(test_dir, 'mathdata', 'math_testcases.txt')
37 test_file = os.path.join(test_dir, 'mathdata', 'cmath_testcases.txt')
38
39
40 def to_ulps(x):
41 """Convert a non-NaN float x to an integer, in such a way that
42 adjacent floats are converted to adjacent integers. Then
43 abs(ulps(x) - ulps(y)) gives the difference in ulps between two
44 floats.
45
46 The results from this function will only make sense on platforms
47 where native doubles are represented in IEEE 754 binary64 format.
48
49 Note: 0.0 and -0.0 are converted to 0 and -1, respectively.
50 """
51 n = struct.unpack('<q', struct.pack('<d', x))[0]
52 if n < 0:
53 n = ~(n+2**63)
54 return n
55
56
57 # Here's a pure Python version of the math.factorial algorithm, for
58 # documentation and comparison purposes.
59 #
60 # Formula:
61 #
62 # factorial(n) = factorial_odd_part(n) << (n - count_set_bits(n))
63 #
64 # where
65 #
66 # factorial_odd_part(n) = product_{i >= 0} product_{0 < j <= n >> i; j odd} j
67 #
68 # The outer product above is an infinite product, but once i >= n.bit_length,
69 # (n >> i) < 1 and the corresponding term of the product is empty. So only the
70 # finitely many terms for 0 <= i < n.bit_length() contribute anything.
71 #
72 # We iterate downwards from i == n.bit_length() - 1 to i == 0. The inner
73 # product in the formula above starts at 1 for i == n.bit_length(); for each i
74 # < n.bit_length() we get the inner product for i from that for i + 1 by
75 # multiplying by all j in {n >> i+1 < j <= n >> i; j odd}. In Python terms,
76 # this set is range((n >> i+1) + 1 | 1, (n >> i) + 1 | 1, 2).
77
78 def count_set_bits(n):
79 """Number of '1' bits in binary expansion of a nonnnegative integer."""
80 return 1 + count_set_bits(n & n - 1) if n else 0
81
82 def partial_product(start, stop):
83 """Product of integers in range(start, stop, 2), computed recursively.
84 start and stop should both be odd, with start <= stop.
85
86 """
87 numfactors = (stop - start) >> 1
88 if not numfactors:
89 return 1
90 elif numfactors == 1:
91 return start
92 else:
93 mid = (start + numfactors) | 1
94 return partial_product(start, mid) * partial_product(mid, stop)
95
96 def py_factorial(n):
97 """Factorial of nonnegative integer n, via "Binary Split Factorial Formula"
98 described at http://www.luschny.de/math/factorial/binarysplitfact.html
99
100 """
101 inner = outer = 1
102 for i in reversed(range(n.bit_length())):
103 inner *= partial_product((n >> i + 1) + 1 | 1, (n >> i) + 1 | 1)
104 outer *= inner
105 return outer << (n - count_set_bits(n))
106
107 def ulp_abs_check(expected, got, ulp_tol, abs_tol):
108 """Given finite floats `expected` and `got`, check that they're
109 approximately equal to within the given number of ulps or the
110 given absolute tolerance, whichever is bigger.
111
112 Returns None on success and an error message on failure.
113 """
114 ulp_error = abs(to_ulps(expected) - to_ulps(got))
115 abs_error = abs(expected - got)
116
117 # Succeed if either abs_error <= abs_tol or ulp_error <= ulp_tol.
118 if abs_error <= abs_tol or ulp_error <= ulp_tol:
119 return None
120 else:
121 fmt = ("error = {:.3g} ({:d} ulps); "
122 "permitted error = {:.3g} or {:d} ulps")
123 return fmt.format(abs_error, ulp_error, abs_tol, ulp_tol)
124
125 def parse_mtestfile(fname):
126 """Parse a file with test values
127
128 -- starts a comment
129 blank lines, or lines containing only a comment, are ignored
130 other lines are expected to have the form
131 id fn arg -> expected [flag]*
132
133 """
134 with open(fname, encoding="utf-8") as fp:
135 for line in fp:
136 # strip comments, and skip blank lines
137 if '--' in line:
138 line = line[:line.index('--')]
139 if not line.strip():
140 continue
141
142 lhs, rhs = line.split('->')
143 id, fn, arg = lhs.split()
144 rhs_pieces = rhs.split()
145 exp = rhs_pieces[0]
146 flags = rhs_pieces[1:]
147
148 yield (id, fn, float(arg), float(exp), flags)
149
150
151 def parse_testfile(fname):
152 """Parse a file with test values
153
154 Empty lines or lines starting with -- are ignored
155 yields id, fn, arg_real, arg_imag, exp_real, exp_imag
156 """
157 with open(fname, encoding="utf-8") as fp:
158 for line in fp:
159 # skip comment lines and blank lines
160 if line.startswith('--') or not line.strip():
161 continue
162
163 lhs, rhs = line.split('->')
164 id, fn, arg_real, arg_imag = lhs.split()
165 rhs_pieces = rhs.split()
166 exp_real, exp_imag = rhs_pieces[0], rhs_pieces[1]
167 flags = rhs_pieces[2:]
168
169 yield (id, fn,
170 float(arg_real), float(arg_imag),
171 float(exp_real), float(exp_imag),
172 flags)
173
174
175 def result_check(expected, got, ulp_tol=5, abs_tol=0.0):
176 # Common logic of MathTests.(ftest, test_testcases, test_mtestcases)
177 """Compare arguments expected and got, as floats, if either
178 is a float, using a tolerance expressed in multiples of
179 ulp(expected) or absolutely (if given and greater).
180
181 As a convenience, when neither argument is a float, and for
182 non-finite floats, exact equality is demanded. Also, nan==nan
183 as far as this function is concerned.
184
185 Returns None on success and an error message on failure.
186 """
187
188 # Check exactly equal (applies also to strings representing exceptions)
189 if got == expected:
190 if not got and not expected:
191 if math.copysign(1, got) != math.copysign(1, expected):
192 return f"expected {expected}, got {got} (zero has wrong sign)"
193 return None
194
195 failure = "not equal"
196
197 # Turn mixed float and int comparison (e.g. floor()) to all-float
198 if isinstance(expected, float) and isinstance(got, int):
199 got = float(got)
200 elif isinstance(got, float) and isinstance(expected, int):
201 expected = float(expected)
202
203 if isinstance(expected, float) and isinstance(got, float):
204 if math.isnan(expected) and math.isnan(got):
205 # Pass, since both nan
206 failure = None
207 elif math.isinf(expected) or math.isinf(got):
208 # We already know they're not equal, drop through to failure
209 pass
210 else:
211 # Both are finite floats (now). Are they close enough?
212 failure = ulp_abs_check(expected, got, ulp_tol, abs_tol)
213
214 # arguments are not equal, and if numeric, are too far apart
215 if failure is not None:
216 fail_fmt = "expected {!r}, got {!r}"
217 fail_msg = fail_fmt.format(expected, got)
218 fail_msg += ' ({})'.format(failure)
219 return fail_msg
220 else:
221 return None
222
223 class FloatLike:
224 def __init__(self, value):
225 self.value = value
226
227 def __float__(self):
228 return self.value
229
230 class IntSubclass(int):
231 pass
232
233 # Class providing an __index__ method.
234 class MyIndexable(object):
235 def __init__(self, value):
236 self.value = value
237
238 def __index__(self):
239 return self.value
240
241 class BadDescr:
242 def __get__(self, obj, objtype=None):
243 raise ValueError
244
245 class MathTests(unittest.TestCase):
246
247 def ftest(self, name, got, expected, ulp_tol=5, abs_tol=0.0):
248 """Compare arguments expected and got, as floats, if either
249 is a float, using a tolerance expressed in multiples of
250 ulp(expected) or absolutely, whichever is greater.
251
252 As a convenience, when neither argument is a float, and for
253 non-finite floats, exact equality is demanded. Also, nan==nan
254 in this function.
255 """
256 failure = result_check(expected, got, ulp_tol, abs_tol)
257 if failure is not None:
258 self.fail("{}: {}".format(name, failure))
259
260 def testConstants(self):
261 # Ref: Abramowitz & Stegun (Dover, 1965)
262 self.ftest('pi', math.pi, 3.141592653589793238462643)
263 self.ftest('e', math.e, 2.718281828459045235360287)
264 self.assertEqual(math.tau, 2*math.pi)
265
266 def testAcos(self):
267 self.assertRaises(TypeError, math.acos)
268 self.ftest('acos(-1)', math.acos(-1), math.pi)
269 self.ftest('acos(0)', math.acos(0), math.pi/2)
270 self.ftest('acos(1)', math.acos(1), 0)
271 self.assertRaises(ValueError, math.acos, INF)
272 self.assertRaises(ValueError, math.acos, NINF)
273 self.assertRaises(ValueError, math.acos, 1 + eps)
274 self.assertRaises(ValueError, math.acos, -1 - eps)
275 self.assertTrue(math.isnan(math.acos(NAN)))
276
277 def testAcosh(self):
278 self.assertRaises(TypeError, math.acosh)
279 self.ftest('acosh(1)', math.acosh(1), 0)
280 self.ftest('acosh(2)', math.acosh(2), 1.3169578969248168)
281 self.assertRaises(ValueError, math.acosh, 0)
282 self.assertRaises(ValueError, math.acosh, -1)
283 self.assertEqual(math.acosh(INF), INF)
284 self.assertRaises(ValueError, math.acosh, NINF)
285 self.assertTrue(math.isnan(math.acosh(NAN)))
286
287 def testAsin(self):
288 self.assertRaises(TypeError, math.asin)
289 self.ftest('asin(-1)', math.asin(-1), -math.pi/2)
290 self.ftest('asin(0)', math.asin(0), 0)
291 self.ftest('asin(1)', math.asin(1), math.pi/2)
292 self.assertRaises(ValueError, math.asin, INF)
293 self.assertRaises(ValueError, math.asin, NINF)
294 self.assertRaises(ValueError, math.asin, 1 + eps)
295 self.assertRaises(ValueError, math.asin, -1 - eps)
296 self.assertTrue(math.isnan(math.asin(NAN)))
297
298 def testAsinh(self):
299 self.assertRaises(TypeError, math.asinh)
300 self.ftest('asinh(0)', math.asinh(0), 0)
301 self.ftest('asinh(1)', math.asinh(1), 0.88137358701954305)
302 self.ftest('asinh(-1)', math.asinh(-1), -0.88137358701954305)
303 self.assertEqual(math.asinh(INF), INF)
304 self.assertEqual(math.asinh(NINF), NINF)
305 self.assertTrue(math.isnan(math.asinh(NAN)))
306
307 def testAtan(self):
308 self.assertRaises(TypeError, math.atan)
309 self.ftest('atan(-1)', math.atan(-1), -math.pi/4)
310 self.ftest('atan(0)', math.atan(0), 0)
311 self.ftest('atan(1)', math.atan(1), math.pi/4)
312 self.ftest('atan(inf)', math.atan(INF), math.pi/2)
313 self.ftest('atan(-inf)', math.atan(NINF), -math.pi/2)
314 self.assertTrue(math.isnan(math.atan(NAN)))
315
316 def testAtanh(self):
317 self.assertRaises(TypeError, math.atan)
318 self.ftest('atanh(0)', math.atanh(0), 0)
319 self.ftest('atanh(0.5)', math.atanh(0.5), 0.54930614433405489)
320 self.ftest('atanh(-0.5)', math.atanh(-0.5), -0.54930614433405489)
321 self.assertRaises(ValueError, math.atanh, 1)
322 self.assertRaises(ValueError, math.atanh, -1)
323 self.assertRaises(ValueError, math.atanh, INF)
324 self.assertRaises(ValueError, math.atanh, NINF)
325 self.assertTrue(math.isnan(math.atanh(NAN)))
326
327 def testAtan2(self):
328 self.assertRaises(TypeError, math.atan2)
329 self.ftest('atan2(-1, 0)', math.atan2(-1, 0), -math.pi/2)
330 self.ftest('atan2(-1, 1)', math.atan2(-1, 1), -math.pi/4)
331 self.ftest('atan2(0, 1)', math.atan2(0, 1), 0)
332 self.ftest('atan2(1, 1)', math.atan2(1, 1), math.pi/4)
333 self.ftest('atan2(1, 0)', math.atan2(1, 0), math.pi/2)
334 self.ftest('atan2(1, -1)', math.atan2(1, -1), 3*math.pi/4)
335
336 # math.atan2(0, x)
337 self.ftest('atan2(0., -inf)', math.atan2(0., NINF), math.pi)
338 self.ftest('atan2(0., -2.3)', math.atan2(0., -2.3), math.pi)
339 self.ftest('atan2(0., -0.)', math.atan2(0., -0.), math.pi)
340 self.assertEqual(math.atan2(0., 0.), 0.)
341 self.assertEqual(math.atan2(0., 2.3), 0.)
342 self.assertEqual(math.atan2(0., INF), 0.)
343 self.assertTrue(math.isnan(math.atan2(0., NAN)))
344 # math.atan2(-0, x)
345 self.ftest('atan2(-0., -inf)', math.atan2(-0., NINF), -math.pi)
346 self.ftest('atan2(-0., -2.3)', math.atan2(-0., -2.3), -math.pi)
347 self.ftest('atan2(-0., -0.)', math.atan2(-0., -0.), -math.pi)
348 self.assertEqual(math.atan2(-0., 0.), -0.)
349 self.assertEqual(math.atan2(-0., 2.3), -0.)
350 self.assertEqual(math.atan2(-0., INF), -0.)
351 self.assertTrue(math.isnan(math.atan2(-0., NAN)))
352 # math.atan2(INF, x)
353 self.ftest('atan2(inf, -inf)', math.atan2(INF, NINF), math.pi*3/4)
354 self.ftest('atan2(inf, -2.3)', math.atan2(INF, -2.3), math.pi/2)
355 self.ftest('atan2(inf, -0.)', math.atan2(INF, -0.0), math.pi/2)
356 self.ftest('atan2(inf, 0.)', math.atan2(INF, 0.0), math.pi/2)
357 self.ftest('atan2(inf, 2.3)', math.atan2(INF, 2.3), math.pi/2)
358 self.ftest('atan2(inf, inf)', math.atan2(INF, INF), math.pi/4)
359 self.assertTrue(math.isnan(math.atan2(INF, NAN)))
360 # math.atan2(NINF, x)
361 self.ftest('atan2(-inf, -inf)', math.atan2(NINF, NINF), -math.pi*3/4)
362 self.ftest('atan2(-inf, -2.3)', math.atan2(NINF, -2.3), -math.pi/2)
363 self.ftest('atan2(-inf, -0.)', math.atan2(NINF, -0.0), -math.pi/2)
364 self.ftest('atan2(-inf, 0.)', math.atan2(NINF, 0.0), -math.pi/2)
365 self.ftest('atan2(-inf, 2.3)', math.atan2(NINF, 2.3), -math.pi/2)
366 self.ftest('atan2(-inf, inf)', math.atan2(NINF, INF), -math.pi/4)
367 self.assertTrue(math.isnan(math.atan2(NINF, NAN)))
368 # math.atan2(+finite, x)
369 self.ftest('atan2(2.3, -inf)', math.atan2(2.3, NINF), math.pi)
370 self.ftest('atan2(2.3, -0.)', math.atan2(2.3, -0.), math.pi/2)
371 self.ftest('atan2(2.3, 0.)', math.atan2(2.3, 0.), math.pi/2)
372 self.assertEqual(math.atan2(2.3, INF), 0.)
373 self.assertTrue(math.isnan(math.atan2(2.3, NAN)))
374 # math.atan2(-finite, x)
375 self.ftest('atan2(-2.3, -inf)', math.atan2(-2.3, NINF), -math.pi)
376 self.ftest('atan2(-2.3, -0.)', math.atan2(-2.3, -0.), -math.pi/2)
377 self.ftest('atan2(-2.3, 0.)', math.atan2(-2.3, 0.), -math.pi/2)
378 self.assertEqual(math.atan2(-2.3, INF), -0.)
379 self.assertTrue(math.isnan(math.atan2(-2.3, NAN)))
380 # math.atan2(NAN, x)
381 self.assertTrue(math.isnan(math.atan2(NAN, NINF)))
382 self.assertTrue(math.isnan(math.atan2(NAN, -2.3)))
383 self.assertTrue(math.isnan(math.atan2(NAN, -0.)))
384 self.assertTrue(math.isnan(math.atan2(NAN, 0.)))
385 self.assertTrue(math.isnan(math.atan2(NAN, 2.3)))
386 self.assertTrue(math.isnan(math.atan2(NAN, INF)))
387 self.assertTrue(math.isnan(math.atan2(NAN, NAN)))
388
389 def testCbrt(self):
390 self.assertRaises(TypeError, math.cbrt)
391 self.ftest('cbrt(0)', math.cbrt(0), 0)
392 self.ftest('cbrt(1)', math.cbrt(1), 1)
393 self.ftest('cbrt(8)', math.cbrt(8), 2)
394 self.ftest('cbrt(0.0)', math.cbrt(0.0), 0.0)
395 self.ftest('cbrt(-0.0)', math.cbrt(-0.0), -0.0)
396 self.ftest('cbrt(1.2)', math.cbrt(1.2), 1.062658569182611)
397 self.ftest('cbrt(-2.6)', math.cbrt(-2.6), -1.375068867074141)
398 self.ftest('cbrt(27)', math.cbrt(27), 3)
399 self.ftest('cbrt(-1)', math.cbrt(-1), -1)
400 self.ftest('cbrt(-27)', math.cbrt(-27), -3)
401 self.assertEqual(math.cbrt(INF), INF)
402 self.assertEqual(math.cbrt(NINF), NINF)
403 self.assertTrue(math.isnan(math.cbrt(NAN)))
404
405 def testCeil(self):
406 self.assertRaises(TypeError, math.ceil)
407 self.assertEqual(int, type(math.ceil(0.5)))
408 self.assertEqual(math.ceil(0.5), 1)
409 self.assertEqual(math.ceil(1.0), 1)
410 self.assertEqual(math.ceil(1.5), 2)
411 self.assertEqual(math.ceil(-0.5), 0)
412 self.assertEqual(math.ceil(-1.0), -1)
413 self.assertEqual(math.ceil(-1.5), -1)
414 self.assertEqual(math.ceil(0.0), 0)
415 self.assertEqual(math.ceil(-0.0), 0)
416 #self.assertEqual(math.ceil(INF), INF)
417 #self.assertEqual(math.ceil(NINF), NINF)
418 #self.assertTrue(math.isnan(math.ceil(NAN)))
419
420 class TestCeil:
421 def __ceil__(self):
422 return 42
423 class FloatCeil(float):
424 def __ceil__(self):
425 return 42
426 class TestNoCeil:
427 pass
428 class TestBadCeil:
429 __ceil__ = BadDescr()
430 self.assertEqual(math.ceil(TestCeil()), 42)
431 self.assertEqual(math.ceil(FloatCeil()), 42)
432 self.assertEqual(math.ceil(FloatLike(42.5)), 43)
433 self.assertRaises(TypeError, math.ceil, TestNoCeil())
434 self.assertRaises(ValueError, math.ceil, TestBadCeil())
435
436 t = TestNoCeil()
437 t.__ceil__ = lambda *args: args
438 self.assertRaises(TypeError, math.ceil, t)
439 self.assertRaises(TypeError, math.ceil, t, 0)
440
441 self.assertEqual(math.ceil(FloatLike(+1.0)), +1.0)
442 self.assertEqual(math.ceil(FloatLike(-1.0)), -1.0)
443
444 @requires_IEEE_754
445 def testCopysign(self):
446 self.assertEqual(math.copysign(1, 42), 1.0)
447 self.assertEqual(math.copysign(0., 42), 0.0)
448 self.assertEqual(math.copysign(1., -42), -1.0)
449 self.assertEqual(math.copysign(3, 0.), 3.0)
450 self.assertEqual(math.copysign(4., -0.), -4.0)
451
452 self.assertRaises(TypeError, math.copysign)
453 # copysign should let us distinguish signs of zeros
454 self.assertEqual(math.copysign(1., 0.), 1.)
455 self.assertEqual(math.copysign(1., -0.), -1.)
456 self.assertEqual(math.copysign(INF, 0.), INF)
457 self.assertEqual(math.copysign(INF, -0.), NINF)
458 self.assertEqual(math.copysign(NINF, 0.), INF)
459 self.assertEqual(math.copysign(NINF, -0.), NINF)
460 # and of infinities
461 self.assertEqual(math.copysign(1., INF), 1.)
462 self.assertEqual(math.copysign(1., NINF), -1.)
463 self.assertEqual(math.copysign(INF, INF), INF)
464 self.assertEqual(math.copysign(INF, NINF), NINF)
465 self.assertEqual(math.copysign(NINF, INF), INF)
466 self.assertEqual(math.copysign(NINF, NINF), NINF)
467 self.assertTrue(math.isnan(math.copysign(NAN, 1.)))
468 self.assertTrue(math.isnan(math.copysign(NAN, INF)))
469 self.assertTrue(math.isnan(math.copysign(NAN, NINF)))
470 self.assertTrue(math.isnan(math.copysign(NAN, NAN)))
471 # copysign(INF, NAN) may be INF or it may be NINF, since
472 # we don't know whether the sign bit of NAN is set on any
473 # given platform.
474 self.assertTrue(math.isinf(math.copysign(INF, NAN)))
475 # similarly, copysign(2., NAN) could be 2. or -2.
476 self.assertEqual(abs(math.copysign(2., NAN)), 2.)
477
478 def testCos(self):
479 self.assertRaises(TypeError, math.cos)
480 self.ftest('cos(-pi/2)', math.cos(-math.pi/2), 0, abs_tol=math.ulp(1))
481 self.ftest('cos(0)', math.cos(0), 1)
482 self.ftest('cos(pi/2)', math.cos(math.pi/2), 0, abs_tol=math.ulp(1))
483 self.ftest('cos(pi)', math.cos(math.pi), -1)
484 try:
485 self.assertTrue(math.isnan(math.cos(INF)))
486 self.assertTrue(math.isnan(math.cos(NINF)))
487 except ValueError:
488 self.assertRaises(ValueError, math.cos, INF)
489 self.assertRaises(ValueError, math.cos, NINF)
490 self.assertTrue(math.isnan(math.cos(NAN)))
491
492 @unittest.skipIf(sys.platform == 'win32' and platform.machine() in ('ARM', 'ARM64'),
493 "Windows UCRT is off by 2 ULP this test requires accuracy within 1 ULP")
494 def testCosh(self):
495 self.assertRaises(TypeError, math.cosh)
496 self.ftest('cosh(0)', math.cosh(0), 1)
497 self.ftest('cosh(2)-2*cosh(1)**2', math.cosh(2)-2*math.cosh(1)**2, -1) # Thanks to Lambert
498 self.assertEqual(math.cosh(INF), INF)
499 self.assertEqual(math.cosh(NINF), INF)
500 self.assertTrue(math.isnan(math.cosh(NAN)))
501
502 def testDegrees(self):
503 self.assertRaises(TypeError, math.degrees)
504 self.ftest('degrees(pi)', math.degrees(math.pi), 180.0)
505 self.ftest('degrees(pi/2)', math.degrees(math.pi/2), 90.0)
506 self.ftest('degrees(-pi/4)', math.degrees(-math.pi/4), -45.0)
507 self.ftest('degrees(0)', math.degrees(0), 0)
508
509 def testExp(self):
510 self.assertRaises(TypeError, math.exp)
511 self.ftest('exp(-1)', math.exp(-1), 1/math.e)
512 self.ftest('exp(0)', math.exp(0), 1)
513 self.ftest('exp(1)', math.exp(1), math.e)
514 self.assertEqual(math.exp(INF), INF)
515 self.assertEqual(math.exp(NINF), 0.)
516 self.assertTrue(math.isnan(math.exp(NAN)))
517 self.assertRaises(OverflowError, math.exp, 1000000)
518
519 def testExp2(self):
520 self.assertRaises(TypeError, math.exp2)
521 self.ftest('exp2(-1)', math.exp2(-1), 0.5)
522 self.ftest('exp2(0)', math.exp2(0), 1)
523 self.ftest('exp2(1)', math.exp2(1), 2)
524 self.ftest('exp2(2.3)', math.exp2(2.3), 4.924577653379665)
525 self.assertEqual(math.exp2(INF), INF)
526 self.assertEqual(math.exp2(NINF), 0.)
527 self.assertTrue(math.isnan(math.exp2(NAN)))
528 self.assertRaises(OverflowError, math.exp2, 1000000)
529
530 def testFabs(self):
531 self.assertRaises(TypeError, math.fabs)
532 self.ftest('fabs(-1)', math.fabs(-1), 1)
533 self.ftest('fabs(0)', math.fabs(0), 0)
534 self.ftest('fabs(1)', math.fabs(1), 1)
535
536 def testFactorial(self):
537 self.assertEqual(math.factorial(0), 1)
538 total = 1
539 for i in range(1, 1000):
540 total *= i
541 self.assertEqual(math.factorial(i), total)
542 self.assertEqual(math.factorial(i), py_factorial(i))
543 self.assertRaises(ValueError, math.factorial, -1)
544 self.assertRaises(ValueError, math.factorial, -10**100)
545
546 def testFactorialNonIntegers(self):
547 self.assertRaises(TypeError, math.factorial, 5.0)
548 self.assertRaises(TypeError, math.factorial, 5.2)
549 self.assertRaises(TypeError, math.factorial, -1.0)
550 self.assertRaises(TypeError, math.factorial, -1e100)
551 self.assertRaises(TypeError, math.factorial, decimal.Decimal('5'))
552 self.assertRaises(TypeError, math.factorial, decimal.Decimal('5.2'))
553 self.assertRaises(TypeError, math.factorial, "5")
554
555 # Other implementations may place different upper bounds.
556 @support.cpython_only
557 def testFactorialHugeInputs(self):
558 # Currently raises OverflowError for inputs that are too large
559 # to fit into a C long.
560 self.assertRaises(OverflowError, math.factorial, 10**100)
561 self.assertRaises(TypeError, math.factorial, 1e100)
562
563 def testFloor(self):
564 self.assertRaises(TypeError, math.floor)
565 self.assertEqual(int, type(math.floor(0.5)))
566 self.assertEqual(math.floor(0.5), 0)
567 self.assertEqual(math.floor(1.0), 1)
568 self.assertEqual(math.floor(1.5), 1)
569 self.assertEqual(math.floor(-0.5), -1)
570 self.assertEqual(math.floor(-1.0), -1)
571 self.assertEqual(math.floor(-1.5), -2)
572 #self.assertEqual(math.ceil(INF), INF)
573 #self.assertEqual(math.ceil(NINF), NINF)
574 #self.assertTrue(math.isnan(math.floor(NAN)))
575
576 class TestFloor:
577 def __floor__(self):
578 return 42
579 class FloatFloor(float):
580 def __floor__(self):
581 return 42
582 class TestNoFloor:
583 pass
584 class TestBadFloor:
585 __floor__ = BadDescr()
586 self.assertEqual(math.floor(TestFloor()), 42)
587 self.assertEqual(math.floor(FloatFloor()), 42)
588 self.assertEqual(math.floor(FloatLike(41.9)), 41)
589 self.assertRaises(TypeError, math.floor, TestNoFloor())
590 self.assertRaises(ValueError, math.floor, TestBadFloor())
591
592 t = TestNoFloor()
593 t.__floor__ = lambda *args: args
594 self.assertRaises(TypeError, math.floor, t)
595 self.assertRaises(TypeError, math.floor, t, 0)
596
597 self.assertEqual(math.floor(FloatLike(+1.0)), +1.0)
598 self.assertEqual(math.floor(FloatLike(-1.0)), -1.0)
599
600 def testFmod(self):
601 self.assertRaises(TypeError, math.fmod)
602 self.ftest('fmod(10, 1)', math.fmod(10, 1), 0.0)
603 self.ftest('fmod(10, 0.5)', math.fmod(10, 0.5), 0.0)
604 self.ftest('fmod(10, 1.5)', math.fmod(10, 1.5), 1.0)
605 self.ftest('fmod(-10, 1)', math.fmod(-10, 1), -0.0)
606 self.ftest('fmod(-10, 0.5)', math.fmod(-10, 0.5), -0.0)
607 self.ftest('fmod(-10, 1.5)', math.fmod(-10, 1.5), -1.0)
608 self.assertTrue(math.isnan(math.fmod(NAN, 1.)))
609 self.assertTrue(math.isnan(math.fmod(1., NAN)))
610 self.assertTrue(math.isnan(math.fmod(NAN, NAN)))
611 self.assertRaises(ValueError, math.fmod, 1., 0.)
612 self.assertRaises(ValueError, math.fmod, INF, 1.)
613 self.assertRaises(ValueError, math.fmod, NINF, 1.)
614 self.assertRaises(ValueError, math.fmod, INF, 0.)
615 self.assertEqual(math.fmod(3.0, INF), 3.0)
616 self.assertEqual(math.fmod(-3.0, INF), -3.0)
617 self.assertEqual(math.fmod(3.0, NINF), 3.0)
618 self.assertEqual(math.fmod(-3.0, NINF), -3.0)
619 self.assertEqual(math.fmod(0.0, 3.0), 0.0)
620 self.assertEqual(math.fmod(0.0, NINF), 0.0)
621 self.assertRaises(ValueError, math.fmod, INF, INF)
622
623 def testFrexp(self):
624 self.assertRaises(TypeError, math.frexp)
625
626 def testfrexp(name, result, expected):
627 (mant, exp), (emant, eexp) = result, expected
628 if abs(mant-emant) > eps or exp != eexp:
629 self.fail('%s returned %r, expected %r'%\
630 (name, result, expected))
631
632 testfrexp('frexp(-1)', math.frexp(-1), (-0.5, 1))
633 testfrexp('frexp(0)', math.frexp(0), (0, 0))
634 testfrexp('frexp(1)', math.frexp(1), (0.5, 1))
635 testfrexp('frexp(2)', math.frexp(2), (0.5, 2))
636
637 self.assertEqual(math.frexp(INF)[0], INF)
638 self.assertEqual(math.frexp(NINF)[0], NINF)
639 self.assertTrue(math.isnan(math.frexp(NAN)[0]))
640
641 @requires_IEEE_754
642 @unittest.skipIf(HAVE_DOUBLE_ROUNDING,
643 "fsum is not exact on machines with double rounding")
644 def testFsum(self):
645 # math.fsum relies on exact rounding for correct operation.
646 # There's a known problem with IA32 floating-point that causes
647 # inexact rounding in some situations, and will cause the
648 # math.fsum tests below to fail; see issue #2937. On non IEEE
649 # 754 platforms, and on IEEE 754 platforms that exhibit the
650 # problem described in issue #2937, we simply skip the whole
651 # test.
652
653 # Python version of math.fsum, for comparison. Uses a
654 # different algorithm based on frexp, ldexp and integer
655 # arithmetic.
656 from sys import float_info
657 mant_dig = float_info.mant_dig
658 etiny = float_info.min_exp - mant_dig
659
660 def msum(iterable):
661 """Full precision summation. Compute sum(iterable) without any
662 intermediate accumulation of error. Based on the 'lsum' function
663 at https://code.activestate.com/recipes/393090-binary-floating-point-summation-accurate-to-full-p/
664
665 """
666 tmant, texp = 0, 0
667 for x in iterable:
668 mant, exp = math.frexp(x)
669 mant, exp = int(math.ldexp(mant, mant_dig)), exp - mant_dig
670 if texp > exp:
671 tmant <<= texp-exp
672 texp = exp
673 else:
674 mant <<= exp-texp
675 tmant += mant
676 # Round tmant * 2**texp to a float. The original recipe
677 # used float(str(tmant)) * 2.0**texp for this, but that's
678 # a little unsafe because str -> float conversion can't be
679 # relied upon to do correct rounding on all platforms.
680 tail = max(len(bin(abs(tmant)))-2 - mant_dig, etiny - texp)
681 if tail > 0:
682 h = 1 << (tail-1)
683 tmant = tmant // (2*h) + bool(tmant & h and tmant & 3*h-1)
684 texp += tail
685 return math.ldexp(tmant, texp)
686
687 test_values = [
688 ([], 0.0),
689 ([0.0], 0.0),
690 ([1e100, 1.0, -1e100, 1e-100, 1e50, -1.0, -1e50], 1e-100),
691 ([1e100, 1.0, -1e100, 1e-100, 1e50, -1, -1e50], 1e-100),
692 ([2.0**53, -0.5, -2.0**-54], 2.0**53-1.0),
693 ([2.0**53, 1.0, 2.0**-100], 2.0**53+2.0),
694 ([2.0**53+10.0, 1.0, 2.0**-100], 2.0**53+12.0),
695 ([2.0**53-4.0, 0.5, 2.0**-54], 2.0**53-3.0),
696 ([1./n for n in range(1, 1001)],
697 float.fromhex('0x1.df11f45f4e61ap+2')),
698 ([(-1.)**n/n for n in range(1, 1001)],
699 float.fromhex('-0x1.62a2af1bd3624p-1')),
700 ([1e16, 1., 1e-16], 10000000000000002.0),
701 ([1e16-2., 1.-2.**-53, -(1e16-2.), -(1.-2.**-53)], 0.0),
702 # exercise code for resizing partials array
703 ([2.**n - 2.**(n+50) + 2.**(n+52) for n in range(-1074, 972, 2)] +
704 [-2.**1022],
705 float.fromhex('0x1.5555555555555p+970')),
706 ]
707
708 # Telescoping sum, with exact differences (due to Sterbenz)
709 terms = [1.7**i for i in range(1001)]
710 test_values.append((
711 [terms[i+1] - terms[i] for i in range(1000)] + [-terms[1000]],
712 -terms[0]
713 ))
714
715 for i, (vals, expected) in enumerate(test_values):
716 try:
717 actual = math.fsum(vals)
718 except OverflowError:
719 self.fail("test %d failed: got OverflowError, expected %r "
720 "for math.fsum(%.100r)" % (i, expected, vals))
721 except ValueError:
722 self.fail("test %d failed: got ValueError, expected %r "
723 "for math.fsum(%.100r)" % (i, expected, vals))
724 self.assertEqual(actual, expected)
725
726 from random import random, gauss, shuffle
727 for j in range(1000):
728 vals = [7, 1e100, -7, -1e100, -9e-20, 8e-20] * 10
729 s = 0
730 for i in range(200):
731 v = gauss(0, random()) ** 7 - s
732 s += v
733 vals.append(v)
734 shuffle(vals)
735
736 s = msum(vals)
737 self.assertEqual(msum(vals), math.fsum(vals))
738
739 self.assertEqual(math.fsum([1.0, math.inf]), math.inf)
740 self.assertTrue(math.isnan(math.fsum([math.nan, 1.0])))
741 self.assertEqual(math.fsum([1e100, FloatLike(1.0), -1e100, 1e-100,
742 1e50, FloatLike(-1.0), -1e50]), 1e-100)
743 self.assertRaises(OverflowError, math.fsum, [1e+308, 1e+308])
744 self.assertRaises(ValueError, math.fsum, [math.inf, -math.inf])
745 self.assertRaises(TypeError, math.fsum, ['spam'])
746 self.assertRaises(TypeError, math.fsum, 1)
747 self.assertRaises(OverflowError, math.fsum, [10**1000])
748
749 def bad_iter():
750 yield 1.0
751 raise ZeroDivisionError
752
753 self.assertRaises(ZeroDivisionError, math.fsum, bad_iter())
754
755 def testGcd(self):
756 gcd = math.gcd
757 self.assertEqual(gcd(0, 0), 0)
758 self.assertEqual(gcd(1, 0), 1)
759 self.assertEqual(gcd(-1, 0), 1)
760 self.assertEqual(gcd(0, 1), 1)
761 self.assertEqual(gcd(0, -1), 1)
762 self.assertEqual(gcd(7, 1), 1)
763 self.assertEqual(gcd(7, -1), 1)
764 self.assertEqual(gcd(-23, 15), 1)
765 self.assertEqual(gcd(120, 84), 12)
766 self.assertEqual(gcd(84, -120), 12)
767 self.assertEqual(gcd(1216342683557601535506311712,
768 436522681849110124616458784), 32)
769
770 x = 434610456570399902378880679233098819019853229470286994367836600566
771 y = 1064502245825115327754847244914921553977
772 for c in (652560,
773 576559230871654959816130551884856912003141446781646602790216406874):
774 a = x * c
775 b = y * c
776 self.assertEqual(gcd(a, b), c)
777 self.assertEqual(gcd(b, a), c)
778 self.assertEqual(gcd(-a, b), c)
779 self.assertEqual(gcd(b, -a), c)
780 self.assertEqual(gcd(a, -b), c)
781 self.assertEqual(gcd(-b, a), c)
782 self.assertEqual(gcd(-a, -b), c)
783 self.assertEqual(gcd(-b, -a), c)
784
785 self.assertEqual(gcd(), 0)
786 self.assertEqual(gcd(120), 120)
787 self.assertEqual(gcd(-120), 120)
788 self.assertEqual(gcd(120, 84, 102), 6)
789 self.assertEqual(gcd(120, 1, 84), 1)
790
791 self.assertRaises(TypeError, gcd, 120.0)
792 self.assertRaises(TypeError, gcd, 120.0, 84)
793 self.assertRaises(TypeError, gcd, 120, 84.0)
794 self.assertRaises(TypeError, gcd, 120, 1, 84.0)
795 self.assertEqual(gcd(MyIndexable(120), MyIndexable(84)), 12)
796
797 def testHypot(self):
798 from decimal import Decimal
799 from fractions import Fraction
800
801 hypot = math.hypot
802
803 # Test different numbers of arguments (from zero to five)
804 # against a straightforward pure python implementation
805 args = math.e, math.pi, math.sqrt(2.0), math.gamma(3.5), math.sin(2.1)
806 for i in range(len(args)+1):
807 self.assertAlmostEqual(
808 hypot(*args[:i]),
809 math.sqrt(sum(s**2 for s in args[:i]))
810 )
811
812 # Test allowable types (those with __float__)
813 self.assertEqual(hypot(12.0, 5.0), 13.0)
814 self.assertEqual(hypot(12, 5), 13)
815 self.assertEqual(hypot(0.75, -1), 1.25)
816 self.assertEqual(hypot(-1, 0.75), 1.25)
817 self.assertEqual(hypot(0.75, FloatLike(-1.)), 1.25)
818 self.assertEqual(hypot(FloatLike(-1.), 0.75), 1.25)
819 self.assertEqual(hypot(Decimal(12), Decimal(5)), 13)
820 self.assertEqual(hypot(Fraction(12, 32), Fraction(5, 32)), Fraction(13, 32))
821 self.assertEqual(hypot(True, False, True, True, True), 2.0)
822
823 # Test corner cases
824 self.assertEqual(hypot(0.0, 0.0), 0.0) # Max input is zero
825 self.assertEqual(hypot(-10.5), 10.5) # Negative input
826 self.assertEqual(hypot(), 0.0) # Negative input
827 self.assertEqual(1.0,
828 math.copysign(1.0, hypot(-0.0)) # Convert negative zero to positive zero
829 )
830 self.assertEqual( # Handling of moving max to the end
831 hypot(1.5, 1.5, 0.5),
832 hypot(1.5, 0.5, 1.5),
833 )
834
835 # Test handling of bad arguments
836 with self.assertRaises(TypeError): # Reject keyword args
837 hypot(x=1)
838 with self.assertRaises(TypeError): # Reject values without __float__
839 hypot(1.1, 'string', 2.2)
840 int_too_big_for_float = 10 ** (sys.float_info.max_10_exp + 5)
841 with self.assertRaises((ValueError, OverflowError)):
842 hypot(1, int_too_big_for_float)
843
844 # Any infinity gives positive infinity.
845 self.assertEqual(hypot(INF), INF)
846 self.assertEqual(hypot(0, INF), INF)
847 self.assertEqual(hypot(10, INF), INF)
848 self.assertEqual(hypot(-10, INF), INF)
849 self.assertEqual(hypot(NAN, INF), INF)
850 self.assertEqual(hypot(INF, NAN), INF)
851 self.assertEqual(hypot(NINF, NAN), INF)
852 self.assertEqual(hypot(NAN, NINF), INF)
853 self.assertEqual(hypot(-INF, INF), INF)
854 self.assertEqual(hypot(-INF, -INF), INF)
855 self.assertEqual(hypot(10, -INF), INF)
856
857 # If no infinity, any NaN gives a NaN.
858 self.assertTrue(math.isnan(hypot(NAN)))
859 self.assertTrue(math.isnan(hypot(0, NAN)))
860 self.assertTrue(math.isnan(hypot(NAN, 10)))
861 self.assertTrue(math.isnan(hypot(10, NAN)))
862 self.assertTrue(math.isnan(hypot(NAN, NAN)))
863 self.assertTrue(math.isnan(hypot(NAN)))
864
865 # Verify scaling for extremely large values
866 fourthmax = FLOAT_MAX / 4.0
867 for n in range(32):
868 self.assertTrue(math.isclose(hypot(*([fourthmax]*n)),
869 fourthmax * math.sqrt(n)))
870
871 # Verify scaling for extremely small values
872 for exp in range(32):
873 scale = FLOAT_MIN / 2.0 ** exp
874 self.assertEqual(math.hypot(4*scale, 3*scale), 5*scale)
875
876 self.assertRaises(TypeError, math.hypot, *([1.0]*18), 'spam')
877
878 @requires_IEEE_754
879 @unittest.skipIf(HAVE_DOUBLE_ROUNDING,
880 "hypot() loses accuracy on machines with double rounding")
881 def testHypotAccuracy(self):
882 # Verify improved accuracy in cases that were known to be inaccurate.
883 #
884 # The new algorithm's accuracy depends on IEEE 754 arithmetic
885 # guarantees, on having the usual ROUND HALF EVEN rounding mode, on
886 # the system not having double rounding due to extended precision,
887 # and on the compiler maintaining the specified order of operations.
888 #
889 # This test is known to succeed on most of our builds. If it fails
890 # some build, we either need to add another skipIf if the cause is
891 # identifiable; otherwise, we can remove this test entirely.
892
893 hypot = math.hypot
894 Decimal = decimal.Decimal
895 high_precision = decimal.Context(prec=500)
896
897 for hx, hy in [
898 # Cases with a 1 ulp error in Python 3.7 compiled with Clang
899 ('0x1.10e89518dca48p+29', '0x1.1970f7565b7efp+30'),
900 ('0x1.10106eb4b44a2p+29', '0x1.ef0596cdc97f8p+29'),
901 ('0x1.459c058e20bb7p+30', '0x1.993ca009b9178p+29'),
902 ('0x1.378371ae67c0cp+30', '0x1.fbe6619854b4cp+29'),
903 ('0x1.f4cd0574fb97ap+29', '0x1.50fe31669340ep+30'),
904 ('0x1.494b2cdd3d446p+29', '0x1.212a5367b4c7cp+29'),
905 ('0x1.f84e649f1e46dp+29', '0x1.1fa56bef8eec4p+30'),
906 ('0x1.2e817edd3d6fap+30', '0x1.eb0814f1e9602p+29'),
907 ('0x1.0d3a6e3d04245p+29', '0x1.32a62fea52352p+30'),
908 ('0x1.888e19611bfc5p+29', '0x1.52b8e70b24353p+29'),
909
910 # Cases with 2 ulp error in Python 3.8
911 ('0x1.538816d48a13fp+29', '0x1.7967c5ca43e16p+29'),
912 ('0x1.57b47b7234530p+29', '0x1.74e2c7040e772p+29'),
913 ('0x1.821b685e9b168p+30', '0x1.677dc1c1e3dc6p+29'),
914 ('0x1.9e8247f67097bp+29', '0x1.24bd2dc4f4baep+29'),
915 ('0x1.b73b59e0cb5f9p+29', '0x1.da899ab784a97p+28'),
916 ('0x1.94a8d2842a7cfp+30', '0x1.326a51d4d8d8ap+30'),
917 ('0x1.e930b9cd99035p+29', '0x1.5a1030e18dff9p+30'),
918 ('0x1.1592bbb0e4690p+29', '0x1.a9c337b33fb9ap+29'),
919 ('0x1.1243a50751fd4p+29', '0x1.a5a10175622d9p+29'),
920 ('0x1.57a8596e74722p+30', '0x1.42d1af9d04da9p+30'),
921
922 # Cases with 1 ulp error in version fff3c28052e6b0
923 ('0x1.ee7dbd9565899p+29', '0x1.7ab4d6fc6e4b4p+29'),
924 ('0x1.5c6bfbec5c4dcp+30', '0x1.02511184b4970p+30'),
925 ('0x1.59dcebba995cap+30', '0x1.50ca7e7c38854p+29'),
926 ('0x1.768cdd94cf5aap+29', '0x1.9cfdc5571d38ep+29'),
927 ('0x1.dcf137d60262ep+29', '0x1.1101621990b3ep+30'),
928 ('0x1.3a2d006e288b0p+30', '0x1.e9a240914326cp+29'),
929 ('0x1.62a32f7f53c61p+29', '0x1.47eb6cd72684fp+29'),
930 ('0x1.d3bcb60748ef2p+29', '0x1.3f13c4056312cp+30'),
931 ('0x1.282bdb82f17f3p+30', '0x1.640ba4c4eed3ap+30'),
932 ('0x1.89d8c423ea0c6p+29', '0x1.d35dcfe902bc3p+29'),
933 ]:
934 x = float.fromhex(hx)
935 y = float.fromhex(hy)
936 with self.subTest(hx=hx, hy=hy, x=x, y=y):
937 with decimal.localcontext(high_precision):
938 z = float((Decimal(x)**2 + Decimal(y)**2).sqrt())
939 self.assertEqual(hypot(x, y), z)
940
941 def testDist(self):
942 from decimal import Decimal as D
943 from fractions import Fraction as F
944
945 dist = math.dist
946 sqrt = math.sqrt
947
948 # Simple exact cases
949 self.assertEqual(dist((1.0, 2.0, 3.0), (4.0, 2.0, -1.0)), 5.0)
950 self.assertEqual(dist((1, 2, 3), (4, 2, -1)), 5.0)
951
952 # Test different numbers of arguments (from zero to nine)
953 # against a straightforward pure python implementation
954 for i in range(9):
955 for j in range(5):
956 p = tuple(random.uniform(-5, 5) for k in range(i))
957 q = tuple(random.uniform(-5, 5) for k in range(i))
958 self.assertAlmostEqual(
959 dist(p, q),
960 sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
961 )
962
963 # Test non-tuple inputs
964 self.assertEqual(dist([1.0, 2.0, 3.0], [4.0, 2.0, -1.0]), 5.0)
965 self.assertEqual(dist(iter([1.0, 2.0, 3.0]), iter([4.0, 2.0, -1.0])), 5.0)
966
967 # Test allowable types (those with __float__)
968 self.assertEqual(dist((14.0, 1.0), (2.0, -4.0)), 13.0)
969 self.assertEqual(dist((14, 1), (2, -4)), 13)
970 self.assertEqual(dist((FloatLike(14.), 1), (2, -4)), 13)
971 self.assertEqual(dist((11, 1), (FloatLike(-1.), -4)), 13)
972 self.assertEqual(dist((14, FloatLike(-1.)), (2, -6)), 13)
973 self.assertEqual(dist((14, -1), (2, -6)), 13)
974 self.assertEqual(dist((D(14), D(1)), (D(2), D(-4))), D(13))
975 self.assertEqual(dist((F(14, 32), F(1, 32)), (F(2, 32), F(-4, 32))),
976 F(13, 32))
977 self.assertEqual(dist((True, True, False, False, True, True),
978 (True, False, True, False, False, False)),
979 2.0)
980
981 # Test corner cases
982 self.assertEqual(dist((13.25, 12.5, -3.25),
983 (13.25, 12.5, -3.25)),
984 0.0) # Distance with self is zero
985 self.assertEqual(dist((), ()), 0.0) # Zero-dimensional case
986 self.assertEqual(1.0, # Convert negative zero to positive zero
987 math.copysign(1.0, dist((-0.0,), (0.0,)))
988 )
989 self.assertEqual(1.0, # Convert negative zero to positive zero
990 math.copysign(1.0, dist((0.0,), (-0.0,)))
991 )
992 self.assertEqual( # Handling of moving max to the end
993 dist((1.5, 1.5, 0.5), (0, 0, 0)),
994 dist((1.5, 0.5, 1.5), (0, 0, 0))
995 )
996
997 # Verify tuple subclasses are allowed
998 class T(tuple):
999 pass
1000 self.assertEqual(dist(T((1, 2, 3)), ((4, 2, -1))), 5.0)
1001
1002 # Test handling of bad arguments
1003 with self.assertRaises(TypeError): # Reject keyword args
1004 dist(p=(1, 2, 3), q=(4, 5, 6))
1005 with self.assertRaises(TypeError): # Too few args
1006 dist((1, 2, 3))
1007 with self.assertRaises(TypeError): # Too many args
1008 dist((1, 2, 3), (4, 5, 6), (7, 8, 9))
1009 with self.assertRaises(TypeError): # Scalars not allowed
1010 dist(1, 2)
1011 with self.assertRaises(TypeError): # Reject values without __float__
1012 dist((1.1, 'string', 2.2), (1, 2, 3))
1013 with self.assertRaises(ValueError): # Check dimension agree
1014 dist((1, 2, 3, 4), (5, 6, 7))
1015 with self.assertRaises(ValueError): # Check dimension agree
1016 dist((1, 2, 3), (4, 5, 6, 7))
1017 with self.assertRaises(TypeError):
1018 dist((1,)*17 + ("spam",), (1,)*18)
1019 with self.assertRaises(TypeError): # Rejects invalid types
1020 dist("abc", "xyz")
1021 int_too_big_for_float = 10 ** (sys.float_info.max_10_exp + 5)
1022 with self.assertRaises((ValueError, OverflowError)):
1023 dist((1, int_too_big_for_float), (2, 3))
1024 with self.assertRaises((ValueError, OverflowError)):
1025 dist((2, 3), (1, int_too_big_for_float))
1026 with self.assertRaises(TypeError):
1027 dist((1,), 2)
1028 with self.assertRaises(TypeError):
1029 dist([1], 2)
1030
1031 class BadFloat:
1032 __float__ = BadDescr()
1033
1034 with self.assertRaises(ValueError):
1035 dist([1], [BadFloat()])
1036
1037 # Verify that the one dimensional case is equivalent to abs()
1038 for i in range(20):
1039 p, q = random.random(), random.random()
1040 self.assertEqual(dist((p,), (q,)), abs(p - q))
1041
1042 # Test special values
1043 values = [NINF, -10.5, -0.0, 0.0, 10.5, INF, NAN]
1044 for p in itertools.product(values, repeat=3):
1045 for q in itertools.product(values, repeat=3):
1046 diffs = [px - qx for px, qx in zip(p, q)]
1047 if any(map(math.isinf, diffs)):
1048 # Any infinite difference gives positive infinity.
1049 self.assertEqual(dist(p, q), INF)
1050 elif any(map(math.isnan, diffs)):
1051 # If no infinity, any NaN gives a NaN.
1052 self.assertTrue(math.isnan(dist(p, q)))
1053
1054 # Verify scaling for extremely large values
1055 fourthmax = FLOAT_MAX / 4.0
1056 for n in range(32):
1057 p = (fourthmax,) * n
1058 q = (0.0,) * n
1059 self.assertTrue(math.isclose(dist(p, q), fourthmax * math.sqrt(n)))
1060 self.assertTrue(math.isclose(dist(q, p), fourthmax * math.sqrt(n)))
1061
1062 # Verify scaling for extremely small values
1063 for exp in range(32):
1064 scale = FLOAT_MIN / 2.0 ** exp
1065 p = (4*scale, 3*scale)
1066 q = (0.0, 0.0)
1067 self.assertEqual(math.dist(p, q), 5*scale)
1068 self.assertEqual(math.dist(q, p), 5*scale)
1069
1070 def test_math_dist_leak(self):
1071 # gh-98897: Check for error handling does not leak memory
1072 with self.assertRaises(ValueError):
1073 math.dist([1, 2], [3, 4, 5])
1074
1075 def testIsqrt(self):
1076 # Test a variety of inputs, large and small.
1077 test_values = (
1078 list(range(1000))
1079 + list(range(10**6 - 1000, 10**6 + 1000))
1080 + [2**e + i for e in range(60, 200) for i in range(-40, 40)]
1081 + [3**9999, 10**5001]
1082 )
1083
1084 for value in test_values:
1085 with self.subTest(value=value):
1086 s = math.isqrt(value)
1087 self.assertIs(type(s), int)
1088 self.assertLessEqual(s*s, value)
1089 self.assertLess(value, (s+1)*(s+1))
1090
1091 # Negative values
1092 with self.assertRaises(ValueError):
1093 math.isqrt(-1)
1094
1095 # Integer-like things
1096 s = math.isqrt(True)
1097 self.assertIs(type(s), int)
1098 self.assertEqual(s, 1)
1099
1100 s = math.isqrt(False)
1101 self.assertIs(type(s), int)
1102 self.assertEqual(s, 0)
1103
1104 class IntegerLike(object):
1105 def __init__(self, value):
1106 self.value = value
1107
1108 def __index__(self):
1109 return self.value
1110
1111 s = math.isqrt(IntegerLike(1729))
1112 self.assertIs(type(s), int)
1113 self.assertEqual(s, 41)
1114
1115 with self.assertRaises(ValueError):
1116 math.isqrt(IntegerLike(-3))
1117
1118 # Non-integer-like things
1119 bad_values = [
1120 3.5, "a string", decimal.Decimal("3.5"), 3.5j,
1121 100.0, -4.0,
1122 ]
1123 for value in bad_values:
1124 with self.subTest(value=value):
1125 with self.assertRaises(TypeError):
1126 math.isqrt(value)
1127
1128 def test_lcm(self):
1129 lcm = math.lcm
1130 self.assertEqual(lcm(0, 0), 0)
1131 self.assertEqual(lcm(1, 0), 0)
1132 self.assertEqual(lcm(-1, 0), 0)
1133 self.assertEqual(lcm(0, 1), 0)
1134 self.assertEqual(lcm(0, -1), 0)
1135 self.assertEqual(lcm(7, 1), 7)
1136 self.assertEqual(lcm(7, -1), 7)
1137 self.assertEqual(lcm(-23, 15), 345)
1138 self.assertEqual(lcm(120, 84), 840)
1139 self.assertEqual(lcm(84, -120), 840)
1140 self.assertEqual(lcm(1216342683557601535506311712,
1141 436522681849110124616458784),
1142 16592536571065866494401400422922201534178938447014944)
1143
1144 x = 43461045657039990237
1145 y = 10645022458251153277
1146 for c in (652560,
1147 57655923087165495981):
1148 a = x * c
1149 b = y * c
1150 d = x * y * c
1151 self.assertEqual(lcm(a, b), d)
1152 self.assertEqual(lcm(b, a), d)
1153 self.assertEqual(lcm(-a, b), d)
1154 self.assertEqual(lcm(b, -a), d)
1155 self.assertEqual(lcm(a, -b), d)
1156 self.assertEqual(lcm(-b, a), d)
1157 self.assertEqual(lcm(-a, -b), d)
1158 self.assertEqual(lcm(-b, -a), d)
1159
1160 self.assertEqual(lcm(), 1)
1161 self.assertEqual(lcm(120), 120)
1162 self.assertEqual(lcm(-120), 120)
1163 self.assertEqual(lcm(120, 84, 102), 14280)
1164 self.assertEqual(lcm(120, 0, 84), 0)
1165
1166 self.assertRaises(TypeError, lcm, 120.0)
1167 self.assertRaises(TypeError, lcm, 120.0, 84)
1168 self.assertRaises(TypeError, lcm, 120, 84.0)
1169 self.assertRaises(TypeError, lcm, 120, 0, 84.0)
1170 self.assertEqual(lcm(MyIndexable(120), MyIndexable(84)), 840)
1171
1172 def testLdexp(self):
1173 self.assertRaises(TypeError, math.ldexp)
1174 self.assertRaises(TypeError, math.ldexp, 2.0, 1.1)
1175 self.ftest('ldexp(0,1)', math.ldexp(0,1), 0)
1176 self.ftest('ldexp(1,1)', math.ldexp(1,1), 2)
1177 self.ftest('ldexp(1,-1)', math.ldexp(1,-1), 0.5)
1178 self.ftest('ldexp(-1,1)', math.ldexp(-1,1), -2)
1179 self.assertRaises(OverflowError, math.ldexp, 1., 1000000)
1180 self.assertRaises(OverflowError, math.ldexp, -1., 1000000)
1181 self.assertEqual(math.ldexp(1., -1000000), 0.)
1182 self.assertEqual(math.ldexp(-1., -1000000), -0.)
1183 self.assertEqual(math.ldexp(INF, 30), INF)
1184 self.assertEqual(math.ldexp(NINF, -213), NINF)
1185 self.assertTrue(math.isnan(math.ldexp(NAN, 0)))
1186
1187 # large second argument
1188 for n in [10**5, 10**10, 10**20, 10**40]:
1189 self.assertEqual(math.ldexp(INF, -n), INF)
1190 self.assertEqual(math.ldexp(NINF, -n), NINF)
1191 self.assertEqual(math.ldexp(1., -n), 0.)
1192 self.assertEqual(math.ldexp(-1., -n), -0.)
1193 self.assertEqual(math.ldexp(0., -n), 0.)
1194 self.assertEqual(math.ldexp(-0., -n), -0.)
1195 self.assertTrue(math.isnan(math.ldexp(NAN, -n)))
1196
1197 self.assertRaises(OverflowError, math.ldexp, 1., n)
1198 self.assertRaises(OverflowError, math.ldexp, -1., n)
1199 self.assertEqual(math.ldexp(0., n), 0.)
1200 self.assertEqual(math.ldexp(-0., n), -0.)
1201 self.assertEqual(math.ldexp(INF, n), INF)
1202 self.assertEqual(math.ldexp(NINF, n), NINF)
1203 self.assertTrue(math.isnan(math.ldexp(NAN, n)))
1204
1205 @requires_IEEE_754
1206 def testLdexp_denormal(self):
1207 # Denormal output incorrectly rounded (truncated)
1208 # on some Windows.
1209 self.assertEqual(math.ldexp(6993274598585239, -1126), 1e-323)
1210
1211 def testLog(self):
1212 self.assertRaises(TypeError, math.log)
1213 self.assertRaises(TypeError, math.log, 1, 2, 3)
1214 self.ftest('log(1/e)', math.log(1/math.e), -1)
1215 self.ftest('log(1)', math.log(1), 0)
1216 self.ftest('log(e)', math.log(math.e), 1)
1217 self.ftest('log(32,2)', math.log(32,2), 5)
1218 self.ftest('log(10**40, 10)', math.log(10**40, 10), 40)
1219 self.ftest('log(10**40, 10**20)', math.log(10**40, 10**20), 2)
1220 self.ftest('log(10**1000)', math.log(10**1000),
1221 2302.5850929940457)
1222 self.assertRaises(ValueError, math.log, -1.5)
1223 self.assertRaises(ValueError, math.log, -10**1000)
1224 self.assertRaises(ValueError, math.log, 10, -10)
1225 self.assertRaises(ValueError, math.log, NINF)
1226 self.assertEqual(math.log(INF), INF)
1227 self.assertTrue(math.isnan(math.log(NAN)))
1228
1229 def testLog1p(self):
1230 self.assertRaises(TypeError, math.log1p)
1231 for n in [2, 2**90, 2**300]:
1232 self.assertAlmostEqual(math.log1p(n), math.log1p(float(n)))
1233 self.assertRaises(ValueError, math.log1p, -1)
1234 self.assertEqual(math.log1p(INF), INF)
1235
1236 @requires_IEEE_754
1237 def testLog2(self):
1238 self.assertRaises(TypeError, math.log2)
1239
1240 # Check some integer values
1241 self.assertEqual(math.log2(1), 0.0)
1242 self.assertEqual(math.log2(2), 1.0)
1243 self.assertEqual(math.log2(4), 2.0)
1244
1245 # Large integer values
1246 self.assertEqual(math.log2(2**1023), 1023.0)
1247 self.assertEqual(math.log2(2**1024), 1024.0)
1248 self.assertEqual(math.log2(2**2000), 2000.0)
1249
1250 self.assertRaises(ValueError, math.log2, -1.5)
1251 self.assertRaises(ValueError, math.log2, NINF)
1252 self.assertTrue(math.isnan(math.log2(NAN)))
1253
1254 @requires_IEEE_754
1255 # log2() is not accurate enough on Mac OS X Tiger (10.4)
1256 @support.requires_mac_ver(10, 5)
1257 def testLog2Exact(self):
1258 # Check that we get exact equality for log2 of powers of 2.
1259 actual = [math.log2(math.ldexp(1.0, n)) for n in range(-1074, 1024)]
1260 expected = [float(n) for n in range(-1074, 1024)]
1261 self.assertEqual(actual, expected)
1262
1263 def testLog10(self):
1264 self.assertRaises(TypeError, math.log10)
1265 self.ftest('log10(0.1)', math.log10(0.1), -1)
1266 self.ftest('log10(1)', math.log10(1), 0)
1267 self.ftest('log10(10)', math.log10(10), 1)
1268 self.ftest('log10(10**1000)', math.log10(10**1000), 1000.0)
1269 self.assertRaises(ValueError, math.log10, -1.5)
1270 self.assertRaises(ValueError, math.log10, -10**1000)
1271 self.assertRaises(ValueError, math.log10, NINF)
1272 self.assertEqual(math.log(INF), INF)
1273 self.assertTrue(math.isnan(math.log10(NAN)))
1274
1275 def testSumProd(self):
1276 sumprod = math.sumprod
1277 Decimal = decimal.Decimal
1278 Fraction = fractions.Fraction
1279
1280 # Core functionality
1281 self.assertEqual(sumprod(iter([10, 20, 30]), (1, 2, 3)), 140)
1282 self.assertEqual(sumprod([1.5, 2.5], [3.5, 4.5]), 16.5)
1283 self.assertEqual(sumprod([], []), 0)
1284 self.assertEqual(sumprod([-1], [1.]), -1)
1285 self.assertEqual(sumprod([1.], [-1]), -1)
1286
1287 # Type preservation and coercion
1288 for v in [
1289 (10, 20, 30),
1290 (1.5, -2.5),
1291 (Fraction(3, 5), Fraction(4, 5)),
1292 (Decimal(3.5), Decimal(4.5)),
1293 (2.5, 10), # float/int
1294 (2.5, Fraction(3, 5)), # float/fraction
1295 (25, Fraction(3, 5)), # int/fraction
1296 (25, Decimal(4.5)), # int/decimal
1297 ]:
1298 for p, q in [(v, v), (v, v[::-1])]:
1299 with self.subTest(p=p, q=q):
1300 expected = sum(p_i * q_i for p_i, q_i in zip(p, q, strict=True))
1301 actual = sumprod(p, q)
1302 self.assertEqual(expected, actual)
1303 self.assertEqual(type(expected), type(actual))
1304
1305 # Bad arguments
1306 self.assertRaises(TypeError, sumprod) # No args
1307 self.assertRaises(TypeError, sumprod, []) # One arg
1308 self.assertRaises(TypeError, sumprod, [], [], []) # Three args
1309 self.assertRaises(TypeError, sumprod, None, [10]) # Non-iterable
1310 self.assertRaises(TypeError, sumprod, [10], None) # Non-iterable
1311 self.assertRaises(TypeError, sumprod, ['x'], [1.0])
1312
1313 # Uneven lengths
1314 self.assertRaises(ValueError, sumprod, [10, 20], [30])
1315 self.assertRaises(ValueError, sumprod, [10], [20, 30])
1316
1317 # Overflows
1318 self.assertEqual(sumprod([10**20], [1]), 10**20)
1319 self.assertEqual(sumprod([1], [10**20]), 10**20)
1320 self.assertEqual(sumprod([10**10], [10**10]), 10**20)
1321 self.assertEqual(sumprod([10**7]*10**5, [10**7]*10**5), 10**19)
1322 self.assertRaises(OverflowError, sumprod, [10**1000], [1.0])
1323 self.assertRaises(OverflowError, sumprod, [1.0], [10**1000])
1324
1325 # Error in iterator
1326 def raise_after(n):
1327 for i in range(n):
1328 yield i
1329 raise RuntimeError
1330 with self.assertRaises(RuntimeError):
1331 sumprod(range(10), raise_after(5))
1332 with self.assertRaises(RuntimeError):
1333 sumprod(raise_after(5), range(10))
1334
1335 from test.test_iter import BasicIterClass
1336
1337 self.assertEqual(sumprod(BasicIterClass(1), [1]), 0)
1338 self.assertEqual(sumprod([1], BasicIterClass(1)), 0)
1339
1340 # Error in multiplication
1341 class BadMultiply:
1342 def __mul__(self, other):
1343 raise RuntimeError
1344 def __rmul__(self, other):
1345 raise RuntimeError
1346 with self.assertRaises(RuntimeError):
1347 sumprod([10, BadMultiply(), 30], [1, 2, 3])
1348 with self.assertRaises(RuntimeError):
1349 sumprod([1, 2, 3], [10, BadMultiply(), 30])
1350
1351 # Error in addition
1352 with self.assertRaises(TypeError):
1353 sumprod(['abc', 3], [5, 10])
1354 with self.assertRaises(TypeError):
1355 sumprod([5, 10], ['abc', 3])
1356
1357 # Special values should give the same as the pure python recipe
1358 self.assertEqual(sumprod([10.1, math.inf], [20.2, 30.3]), math.inf)
1359 self.assertEqual(sumprod([10.1, math.inf], [math.inf, 30.3]), math.inf)
1360 self.assertEqual(sumprod([10.1, math.inf], [math.inf, math.inf]), math.inf)
1361 self.assertEqual(sumprod([10.1, -math.inf], [20.2, 30.3]), -math.inf)
1362 self.assertTrue(math.isnan(sumprod([10.1, math.inf], [-math.inf, math.inf])))
1363 self.assertTrue(math.isnan(sumprod([10.1, math.nan], [20.2, 30.3])))
1364 self.assertTrue(math.isnan(sumprod([10.1, math.inf], [math.nan, 30.3])))
1365 self.assertTrue(math.isnan(sumprod([10.1, math.inf], [20.3, math.nan])))
1366
1367 # Error cases that arose during development
1368 args = ((-5, -5, 10), (1.5, 4611686018427387904, 2305843009213693952))
1369 self.assertEqual(sumprod(*args), 0.0)
1370
1371
1372 @requires_IEEE_754
1373 @unittest.skipIf(HAVE_DOUBLE_ROUNDING,
1374 "sumprod() accuracy not guaranteed on machines with double rounding")
1375 @support.cpython_only # Other implementations may choose a different algorithm
1376 def test_sumprod_accuracy(self):
1377 sumprod = math.sumprod
1378 self.assertEqual(sumprod([0.1] * 10, [1]*10), 1.0)
1379 self.assertEqual(sumprod([0.1] * 20, [True, False] * 10), 1.0)
1380 self.assertEqual(sumprod([True, False] * 10, [0.1] * 20), 1.0)
1381 self.assertEqual(sumprod([1.0, 10E100, 1.0, -10E100], [1.0]*4), 2.0)
1382
1383 @support.requires_resource('cpu')
1384 def test_sumprod_stress(self):
1385 sumprod = math.sumprod
1386 product = itertools.product
1387 Decimal = decimal.Decimal
1388 Fraction = fractions.Fraction
1389
1390 class Int(int):
1391 def __add__(self, other):
1392 return Int(int(self) + int(other))
1393 def __mul__(self, other):
1394 return Int(int(self) * int(other))
1395 __radd__ = __add__
1396 __rmul__ = __mul__
1397 def __repr__(self):
1398 return f'Int({int(self)})'
1399
1400 class Flt(float):
1401 def __add__(self, other):
1402 return Int(int(self) + int(other))
1403 def __mul__(self, other):
1404 return Int(int(self) * int(other))
1405 __radd__ = __add__
1406 __rmul__ = __mul__
1407 def __repr__(self):
1408 return f'Flt({int(self)})'
1409
1410 def baseline_sumprod(p, q):
1411 """This defines the target behavior including exceptions and special values.
1412 However, it is subject to rounding errors, so float inputs should be exactly
1413 representable with only a few bits.
1414 """
1415 total = 0
1416 for p_i, q_i in zip(p, q, strict=True):
1417 total += p_i * q_i
1418 return total
1419
1420 def run(func, *args):
1421 "Make comparing functions easier. Returns error status, type, and result."
1422 try:
1423 result = func(*args)
1424 except (AssertionError, NameError):
1425 raise
1426 except Exception as e:
1427 return type(e), None, 'None'
1428 return None, type(result), repr(result)
1429
1430 pools = [
1431 (-5, 10, -2**20, 2**31, 2**40, 2**61, 2**62, 2**80, 1.5, Int(7)),
1432 (5.25, -3.5, 4.75, 11.25, 400.5, 0.046875, 0.25, -1.0, -0.078125),
1433 (-19.0*2**500, 11*2**1000, -3*2**1500, 17*2*333,
1434 5.25, -3.25, -3.0*2**(-333), 3, 2**513),
1435 (3.75, 2.5, -1.5, float('inf'), -float('inf'), float('NaN'), 14,
1436 9, 3+4j, Flt(13), 0.0),
1437 (13.25, -4.25, Decimal('10.5'), Decimal('-2.25'), Fraction(13, 8),
1438 Fraction(-11, 16), 4.75 + 0.125j, 97, -41, Int(3)),
1439 (Decimal('6.125'), Decimal('12.375'), Decimal('-2.75'), Decimal(0),
1440 Decimal('Inf'), -Decimal('Inf'), Decimal('NaN'), 12, 13.5),
1441 (-2.0 ** -1000, 11*2**1000, 3, 7, -37*2**32, -2*2**-537, -2*2**-538,
1442 2*2**-513),
1443 (-7 * 2.0 ** -510, 5 * 2.0 ** -520, 17, -19.0, -6.25),
1444 (11.25, -3.75, -0.625, 23.375, True, False, 7, Int(5)),
1445 ]
1446
1447 for pool in pools:
1448 for size in range(4):
1449 for args1 in product(pool, repeat=size):
1450 for args2 in product(pool, repeat=size):
1451 args = (args1, args2)
1452 self.assertEqual(
1453 run(baseline_sumprod, *args),
1454 run(sumprod, *args),
1455 args,
1456 )
1457
1458 @requires_IEEE_754
1459 @unittest.skipIf(HAVE_DOUBLE_ROUNDING,
1460 "sumprod() accuracy not guaranteed on machines with double rounding")
1461 @support.cpython_only # Other implementations may choose a different algorithm
1462 @support.requires_resource('cpu')
1463 def test_sumprod_extended_precision_accuracy(self):
1464 import operator
1465 from fractions import Fraction
1466 from itertools import starmap
1467 from collections import namedtuple
1468 from math import log2, exp2, fabs
1469 from random import choices, uniform, shuffle
1470 from statistics import median
1471
1472 DotExample = namedtuple('DotExample', ('x', 'y', 'target_sumprod', 'condition'))
1473
1474 def DotExact(x, y):
1475 vec1 = map(Fraction, x)
1476 vec2 = map(Fraction, y)
1477 return sum(starmap(operator.mul, zip(vec1, vec2, strict=True)))
1478
1479 def Condition(x, y):
1480 return 2.0 * DotExact(map(abs, x), map(abs, y)) / abs(DotExact(x, y))
1481
1482 def linspace(lo, hi, n):
1483 width = (hi - lo) / (n - 1)
1484 return [lo + width * i for i in range(n)]
1485
1486 def GenDot(n, c):
1487 """ Algorithm 6.1 (GenDot) works as follows. The condition number (5.7) of
1488 the dot product xT y is proportional to the degree of cancellation. In
1489 order to achieve a prescribed cancellation, we generate the first half of
1490 the vectors x and y randomly within a large exponent range. This range is
1491 chosen according to the anticipated condition number. The second half of x
1492 and y is then constructed choosing xi randomly with decreasing exponent,
1493 and calculating yi such that some cancellation occurs. Finally, we permute
1494 the vectors x, y randomly and calculate the achieved condition number.
1495 """
1496
1497 assert n >= 6
1498 n2 = n // 2
1499 x = [0.0] * n
1500 y = [0.0] * n
1501 b = log2(c)
1502
1503 # First half with exponents from 0 to |_b/2_| and random ints in between
1504 e = choices(range(int(b/2)), k=n2)
1505 e[0] = int(b / 2) + 1
1506 e[-1] = 0.0
1507
1508 x[:n2] = [uniform(-1.0, 1.0) * exp2(p) for p in e]
1509 y[:n2] = [uniform(-1.0, 1.0) * exp2(p) for p in e]
1510
1511 # Second half
1512 e = list(map(round, linspace(b/2, 0.0 , n-n2)))
1513 for i in range(n2, n):
1514 x[i] = uniform(-1.0, 1.0) * exp2(e[i - n2])
1515 y[i] = (uniform(-1.0, 1.0) * exp2(e[i - n2]) - DotExact(x, y)) / x[i]
1516
1517 # Shuffle
1518 pairs = list(zip(x, y))
1519 shuffle(pairs)
1520 x, y = zip(*pairs)
1521
1522 return DotExample(x, y, DotExact(x, y), Condition(x, y))
1523
1524 def RelativeError(res, ex):
1525 x, y, target_sumprod, condition = ex
1526 n = DotExact(list(x) + [-res], list(y) + [1])
1527 return fabs(n / target_sumprod)
1528
1529 def Trial(dotfunc, c, n):
1530 ex = GenDot(10, c)
1531 res = dotfunc(ex.x, ex.y)
1532 return RelativeError(res, ex)
1533
1534 times = 1000 # Number of trials
1535 n = 20 # Length of vectors
1536 c = 1e30 # Target condition number
1537
1538 # If the following test fails, it means that the C math library
1539 # implementation of fma() is not compliant with the C99 standard
1540 # and is inaccurate. To solve this problem, make a new build
1541 # with the symbol UNRELIABLE_FMA defined. That will enable a
1542 # slower but accurate code path that avoids the fma() call.
1543 relative_err = median(Trial(math.sumprod, c, n) for i in range(times))
1544 self.assertLess(relative_err, 1e-16)
1545
1546 def testModf(self):
1547 self.assertRaises(TypeError, math.modf)
1548
1549 def testmodf(name, result, expected):
1550 (v1, v2), (e1, e2) = result, expected
1551 if abs(v1-e1) > eps or abs(v2-e2):
1552 self.fail('%s returned %r, expected %r'%\
1553 (name, result, expected))
1554
1555 testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0))
1556 testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0))
1557
1558 self.assertEqual(math.modf(INF), (0.0, INF))
1559 self.assertEqual(math.modf(NINF), (-0.0, NINF))
1560
1561 modf_nan = math.modf(NAN)
1562 self.assertTrue(math.isnan(modf_nan[0]))
1563 self.assertTrue(math.isnan(modf_nan[1]))
1564
1565 def testPow(self):
1566 self.assertRaises(TypeError, math.pow)
1567 self.ftest('pow(0,1)', math.pow(0,1), 0)
1568 self.ftest('pow(1,0)', math.pow(1,0), 1)
1569 self.ftest('pow(2,1)', math.pow(2,1), 2)
1570 self.ftest('pow(2,-1)', math.pow(2,-1), 0.5)
1571 self.assertEqual(math.pow(INF, 1), INF)
1572 self.assertEqual(math.pow(NINF, 1), NINF)
1573 self.assertEqual((math.pow(1, INF)), 1.)
1574 self.assertEqual((math.pow(1, NINF)), 1.)
1575 self.assertTrue(math.isnan(math.pow(NAN, 1)))
1576 self.assertTrue(math.isnan(math.pow(2, NAN)))
1577 self.assertTrue(math.isnan(math.pow(0, NAN)))
1578 self.assertEqual(math.pow(1, NAN), 1)
1579 self.assertRaises(OverflowError, math.pow, 1e+100, 1e+100)
1580
1581 # pow(0., x)
1582 self.assertEqual(math.pow(0., INF), 0.)
1583 self.assertEqual(math.pow(0., 3.), 0.)
1584 self.assertEqual(math.pow(0., 2.3), 0.)
1585 self.assertEqual(math.pow(0., 2.), 0.)
1586 self.assertEqual(math.pow(0., 0.), 1.)
1587 self.assertEqual(math.pow(0., -0.), 1.)
1588 self.assertRaises(ValueError, math.pow, 0., -2.)
1589 self.assertRaises(ValueError, math.pow, 0., -2.3)
1590 self.assertRaises(ValueError, math.pow, 0., -3.)
1591 self.assertEqual(math.pow(0., NINF), INF)
1592 self.assertTrue(math.isnan(math.pow(0., NAN)))
1593
1594 # pow(INF, x)
1595 self.assertEqual(math.pow(INF, INF), INF)
1596 self.assertEqual(math.pow(INF, 3.), INF)
1597 self.assertEqual(math.pow(INF, 2.3), INF)
1598 self.assertEqual(math.pow(INF, 2.), INF)
1599 self.assertEqual(math.pow(INF, 0.), 1.)
1600 self.assertEqual(math.pow(INF, -0.), 1.)
1601 self.assertEqual(math.pow(INF, -2.), 0.)
1602 self.assertEqual(math.pow(INF, -2.3), 0.)
1603 self.assertEqual(math.pow(INF, -3.), 0.)
1604 self.assertEqual(math.pow(INF, NINF), 0.)
1605 self.assertTrue(math.isnan(math.pow(INF, NAN)))
1606
1607 # pow(-0., x)
1608 self.assertEqual(math.pow(-0., INF), 0.)
1609 self.assertEqual(math.pow(-0., 3.), -0.)
1610 self.assertEqual(math.pow(-0., 2.3), 0.)
1611 self.assertEqual(math.pow(-0., 2.), 0.)
1612 self.assertEqual(math.pow(-0., 0.), 1.)
1613 self.assertEqual(math.pow(-0., -0.), 1.)
1614 self.assertRaises(ValueError, math.pow, -0., -2.)
1615 self.assertRaises(ValueError, math.pow, -0., -2.3)
1616 self.assertRaises(ValueError, math.pow, -0., -3.)
1617 self.assertEqual(math.pow(-0., NINF), INF)
1618 self.assertTrue(math.isnan(math.pow(-0., NAN)))
1619
1620 # pow(NINF, x)
1621 self.assertEqual(math.pow(NINF, INF), INF)
1622 self.assertEqual(math.pow(NINF, 3.), NINF)
1623 self.assertEqual(math.pow(NINF, 2.3), INF)
1624 self.assertEqual(math.pow(NINF, 2.), INF)
1625 self.assertEqual(math.pow(NINF, 0.), 1.)
1626 self.assertEqual(math.pow(NINF, -0.), 1.)
1627 self.assertEqual(math.pow(NINF, -2.), 0.)
1628 self.assertEqual(math.pow(NINF, -2.3), 0.)
1629 self.assertEqual(math.pow(NINF, -3.), -0.)
1630 self.assertEqual(math.pow(NINF, NINF), 0.)
1631 self.assertTrue(math.isnan(math.pow(NINF, NAN)))
1632
1633 # pow(-1, x)
1634 self.assertEqual(math.pow(-1., INF), 1.)
1635 self.assertEqual(math.pow(-1., 3.), -1.)
1636 self.assertRaises(ValueError, math.pow, -1., 2.3)
1637 self.assertEqual(math.pow(-1., 2.), 1.)
1638 self.assertEqual(math.pow(-1., 0.), 1.)
1639 self.assertEqual(math.pow(-1., -0.), 1.)
1640 self.assertEqual(math.pow(-1., -2.), 1.)
1641 self.assertRaises(ValueError, math.pow, -1., -2.3)
1642 self.assertEqual(math.pow(-1., -3.), -1.)
1643 self.assertEqual(math.pow(-1., NINF), 1.)
1644 self.assertTrue(math.isnan(math.pow(-1., NAN)))
1645
1646 # pow(1, x)
1647 self.assertEqual(math.pow(1., INF), 1.)
1648 self.assertEqual(math.pow(1., 3.), 1.)
1649 self.assertEqual(math.pow(1., 2.3), 1.)
1650 self.assertEqual(math.pow(1., 2.), 1.)
1651 self.assertEqual(math.pow(1., 0.), 1.)
1652 self.assertEqual(math.pow(1., -0.), 1.)
1653 self.assertEqual(math.pow(1., -2.), 1.)
1654 self.assertEqual(math.pow(1., -2.3), 1.)
1655 self.assertEqual(math.pow(1., -3.), 1.)
1656 self.assertEqual(math.pow(1., NINF), 1.)
1657 self.assertEqual(math.pow(1., NAN), 1.)
1658
1659 # pow(x, 0) should be 1 for any x
1660 self.assertEqual(math.pow(2.3, 0.), 1.)
1661 self.assertEqual(math.pow(-2.3, 0.), 1.)
1662 self.assertEqual(math.pow(NAN, 0.), 1.)
1663 self.assertEqual(math.pow(2.3, -0.), 1.)
1664 self.assertEqual(math.pow(-2.3, -0.), 1.)
1665 self.assertEqual(math.pow(NAN, -0.), 1.)
1666
1667 # pow(x, y) is invalid if x is negative and y is not integral
1668 self.assertRaises(ValueError, math.pow, -1., 2.3)
1669 self.assertRaises(ValueError, math.pow, -15., -3.1)
1670
1671 # pow(x, NINF)
1672 self.assertEqual(math.pow(1.9, NINF), 0.)
1673 self.assertEqual(math.pow(1.1, NINF), 0.)
1674 self.assertEqual(math.pow(0.9, NINF), INF)
1675 self.assertEqual(math.pow(0.1, NINF), INF)
1676 self.assertEqual(math.pow(-0.1, NINF), INF)
1677 self.assertEqual(math.pow(-0.9, NINF), INF)
1678 self.assertEqual(math.pow(-1.1, NINF), 0.)
1679 self.assertEqual(math.pow(-1.9, NINF), 0.)
1680
1681 # pow(x, INF)
1682 self.assertEqual(math.pow(1.9, INF), INF)
1683 self.assertEqual(math.pow(1.1, INF), INF)
1684 self.assertEqual(math.pow(0.9, INF), 0.)
1685 self.assertEqual(math.pow(0.1, INF), 0.)
1686 self.assertEqual(math.pow(-0.1, INF), 0.)
1687 self.assertEqual(math.pow(-0.9, INF), 0.)
1688 self.assertEqual(math.pow(-1.1, INF), INF)
1689 self.assertEqual(math.pow(-1.9, INF), INF)
1690
1691 # pow(x, y) should work for x negative, y an integer
1692 self.ftest('(-2.)**3.', math.pow(-2.0, 3.0), -8.0)
1693 self.ftest('(-2.)**2.', math.pow(-2.0, 2.0), 4.0)
1694 self.ftest('(-2.)**1.', math.pow(-2.0, 1.0), -2.0)
1695 self.ftest('(-2.)**0.', math.pow(-2.0, 0.0), 1.0)
1696 self.ftest('(-2.)**-0.', math.pow(-2.0, -0.0), 1.0)
1697 self.ftest('(-2.)**-1.', math.pow(-2.0, -1.0), -0.5)
1698 self.ftest('(-2.)**-2.', math.pow(-2.0, -2.0), 0.25)
1699 self.ftest('(-2.)**-3.', math.pow(-2.0, -3.0), -0.125)
1700 self.assertRaises(ValueError, math.pow, -2.0, -0.5)
1701 self.assertRaises(ValueError, math.pow, -2.0, 0.5)
1702
1703 # the following tests have been commented out since they don't
1704 # really belong here: the implementation of ** for floats is
1705 # independent of the implementation of math.pow
1706 #self.assertEqual(1**NAN, 1)
1707 #self.assertEqual(1**INF, 1)
1708 #self.assertEqual(1**NINF, 1)
1709 #self.assertEqual(1**0, 1)
1710 #self.assertEqual(1.**NAN, 1)
1711 #self.assertEqual(1.**INF, 1)
1712 #self.assertEqual(1.**NINF, 1)
1713 #self.assertEqual(1.**0, 1)
1714
1715 def testRadians(self):
1716 self.assertRaises(TypeError, math.radians)
1717 self.ftest('radians(180)', math.radians(180), math.pi)
1718 self.ftest('radians(90)', math.radians(90), math.pi/2)
1719 self.ftest('radians(-45)', math.radians(-45), -math.pi/4)
1720 self.ftest('radians(0)', math.radians(0), 0)
1721
1722 @requires_IEEE_754
1723 def testRemainder(self):
1724 from fractions import Fraction
1725
1726 def validate_spec(x, y, r):
1727 """
1728 Check that r matches remainder(x, y) according to the IEEE 754
1729 specification. Assumes that x, y and r are finite and y is nonzero.
1730 """
1731 fx, fy, fr = Fraction(x), Fraction(y), Fraction(r)
1732 # r should not exceed y/2 in absolute value
1733 self.assertLessEqual(abs(fr), abs(fy/2))
1734 # x - r should be an exact integer multiple of y
1735 n = (fx - fr) / fy
1736 self.assertEqual(n, int(n))
1737 if abs(fr) == abs(fy/2):
1738 # If |r| == |y/2|, n should be even.
1739 self.assertEqual(n/2, int(n/2))
1740
1741 # triples (x, y, remainder(x, y)) in hexadecimal form.
1742 testcases = [
1743 # Remainders modulo 1, showing the ties-to-even behaviour.
1744 '-4.0 1 -0.0',
1745 '-3.8 1 0.8',
1746 '-3.0 1 -0.0',
1747 '-2.8 1 -0.8',
1748 '-2.0 1 -0.0',
1749 '-1.8 1 0.8',
1750 '-1.0 1 -0.0',
1751 '-0.8 1 -0.8',
1752 '-0.0 1 -0.0',
1753 ' 0.0 1 0.0',
1754 ' 0.8 1 0.8',
1755 ' 1.0 1 0.0',
1756 ' 1.8 1 -0.8',
1757 ' 2.0 1 0.0',
1758 ' 2.8 1 0.8',
1759 ' 3.0 1 0.0',
1760 ' 3.8 1 -0.8',
1761 ' 4.0 1 0.0',
1762
1763 # Reductions modulo 2*pi
1764 '0x0.0p+0 0x1.921fb54442d18p+2 0x0.0p+0',
1765 '0x1.921fb54442d18p+0 0x1.921fb54442d18p+2 0x1.921fb54442d18p+0',
1766 '0x1.921fb54442d17p+1 0x1.921fb54442d18p+2 0x1.921fb54442d17p+1',
1767 '0x1.921fb54442d18p+1 0x1.921fb54442d18p+2 0x1.921fb54442d18p+1',
1768 '0x1.921fb54442d19p+1 0x1.921fb54442d18p+2 -0x1.921fb54442d17p+1',
1769 '0x1.921fb54442d17p+2 0x1.921fb54442d18p+2 -0x0.0000000000001p+2',
1770 '0x1.921fb54442d18p+2 0x1.921fb54442d18p+2 0x0p0',
1771 '0x1.921fb54442d19p+2 0x1.921fb54442d18p+2 0x0.0000000000001p+2',
1772 '0x1.2d97c7f3321d1p+3 0x1.921fb54442d18p+2 0x1.921fb54442d14p+1',
1773 '0x1.2d97c7f3321d2p+3 0x1.921fb54442d18p+2 -0x1.921fb54442d18p+1',
1774 '0x1.2d97c7f3321d3p+3 0x1.921fb54442d18p+2 -0x1.921fb54442d14p+1',
1775 '0x1.921fb54442d17p+3 0x1.921fb54442d18p+2 -0x0.0000000000001p+3',
1776 '0x1.921fb54442d18p+3 0x1.921fb54442d18p+2 0x0p0',
1777 '0x1.921fb54442d19p+3 0x1.921fb54442d18p+2 0x0.0000000000001p+3',
1778 '0x1.f6a7a2955385dp+3 0x1.921fb54442d18p+2 0x1.921fb54442d14p+1',
1779 '0x1.f6a7a2955385ep+3 0x1.921fb54442d18p+2 0x1.921fb54442d18p+1',
1780 '0x1.f6a7a2955385fp+3 0x1.921fb54442d18p+2 -0x1.921fb54442d14p+1',
1781 '0x1.1475cc9eedf00p+5 0x1.921fb54442d18p+2 0x1.921fb54442d10p+1',
1782 '0x1.1475cc9eedf01p+5 0x1.921fb54442d18p+2 -0x1.921fb54442d10p+1',
1783
1784 # Symmetry with respect to signs.
1785 ' 1 0.c 0.4',
1786 '-1 0.c -0.4',
1787 ' 1 -0.c 0.4',
1788 '-1 -0.c -0.4',
1789 ' 1.4 0.c -0.4',
1790 '-1.4 0.c 0.4',
1791 ' 1.4 -0.c -0.4',
1792 '-1.4 -0.c 0.4',
1793
1794 # Huge modulus, to check that the underlying algorithm doesn't
1795 # rely on 2.0 * modulus being representable.
1796 '0x1.dp+1023 0x1.4p+1023 0x0.9p+1023',
1797 '0x1.ep+1023 0x1.4p+1023 -0x0.ap+1023',
1798 '0x1.fp+1023 0x1.4p+1023 -0x0.9p+1023',
1799 ]
1800
1801 for case in testcases:
1802 with self.subTest(case=case):
1803 x_hex, y_hex, expected_hex = case.split()
1804 x = float.fromhex(x_hex)
1805 y = float.fromhex(y_hex)
1806 expected = float.fromhex(expected_hex)
1807 validate_spec(x, y, expected)
1808 actual = math.remainder(x, y)
1809 # Cheap way of checking that the floats are
1810 # as identical as we need them to be.
1811 self.assertEqual(actual.hex(), expected.hex())
1812
1813 # Test tiny subnormal modulus: there's potential for
1814 # getting the implementation wrong here (for example,
1815 # by assuming that modulus/2 is exactly representable).
1816 tiny = float.fromhex('1p-1074') # min +ve subnormal
1817 for n in range(-25, 25):
1818 if n == 0:
1819 continue
1820 y = n * tiny
1821 for m in range(100):
1822 x = m * tiny
1823 actual = math.remainder(x, y)
1824 validate_spec(x, y, actual)
1825 actual = math.remainder(-x, y)
1826 validate_spec(-x, y, actual)
1827
1828 # Special values.
1829 # NaNs should propagate as usual.
1830 for value in [NAN, 0.0, -0.0, 2.0, -2.3, NINF, INF]:
1831 self.assertIsNaN(math.remainder(NAN, value))
1832 self.assertIsNaN(math.remainder(value, NAN))
1833
1834 # remainder(x, inf) is x, for non-nan non-infinite x.
1835 for value in [-2.3, -0.0, 0.0, 2.3]:
1836 self.assertEqual(math.remainder(value, INF), value)
1837 self.assertEqual(math.remainder(value, NINF), value)
1838
1839 # remainder(x, 0) and remainder(infinity, x) for non-NaN x are invalid
1840 # operations according to IEEE 754-2008 7.2(f), and should raise.
1841 for value in [NINF, -2.3, -0.0, 0.0, 2.3, INF]:
1842 with self.assertRaises(ValueError):
1843 math.remainder(INF, value)
1844 with self.assertRaises(ValueError):
1845 math.remainder(NINF, value)
1846 with self.assertRaises(ValueError):
1847 math.remainder(value, 0.0)
1848 with self.assertRaises(ValueError):
1849 math.remainder(value, -0.0)
1850
1851 def testSin(self):
1852 self.assertRaises(TypeError, math.sin)
1853 self.ftest('sin(0)', math.sin(0), 0)
1854 self.ftest('sin(pi/2)', math.sin(math.pi/2), 1)
1855 self.ftest('sin(-pi/2)', math.sin(-math.pi/2), -1)
1856 try:
1857 self.assertTrue(math.isnan(math.sin(INF)))
1858 self.assertTrue(math.isnan(math.sin(NINF)))
1859 except ValueError:
1860 self.assertRaises(ValueError, math.sin, INF)
1861 self.assertRaises(ValueError, math.sin, NINF)
1862 self.assertTrue(math.isnan(math.sin(NAN)))
1863
1864 def testSinh(self):
1865 self.assertRaises(TypeError, math.sinh)
1866 self.ftest('sinh(0)', math.sinh(0), 0)
1867 self.ftest('sinh(1)**2-cosh(1)**2', math.sinh(1)**2-math.cosh(1)**2, -1)
1868 self.ftest('sinh(1)+sinh(-1)', math.sinh(1)+math.sinh(-1), 0)
1869 self.assertEqual(math.sinh(INF), INF)
1870 self.assertEqual(math.sinh(NINF), NINF)
1871 self.assertTrue(math.isnan(math.sinh(NAN)))
1872
1873 def testSqrt(self):
1874 self.assertRaises(TypeError, math.sqrt)
1875 self.ftest('sqrt(0)', math.sqrt(0), 0)
1876 self.ftest('sqrt(0)', math.sqrt(0.0), 0.0)
1877 self.ftest('sqrt(2.5)', math.sqrt(2.5), 1.5811388300841898)
1878 self.ftest('sqrt(0.25)', math.sqrt(0.25), 0.5)
1879 self.ftest('sqrt(25.25)', math.sqrt(25.25), 5.024937810560445)
1880 self.ftest('sqrt(1)', math.sqrt(1), 1)
1881 self.ftest('sqrt(4)', math.sqrt(4), 2)
1882 self.assertEqual(math.sqrt(INF), INF)
1883 self.assertRaises(ValueError, math.sqrt, -1)
1884 self.assertRaises(ValueError, math.sqrt, NINF)
1885 self.assertTrue(math.isnan(math.sqrt(NAN)))
1886
1887 def testTan(self):
1888 self.assertRaises(TypeError, math.tan)
1889 self.ftest('tan(0)', math.tan(0), 0)
1890 self.ftest('tan(pi/4)', math.tan(math.pi/4), 1)
1891 self.ftest('tan(-pi/4)', math.tan(-math.pi/4), -1)
1892 try:
1893 self.assertTrue(math.isnan(math.tan(INF)))
1894 self.assertTrue(math.isnan(math.tan(NINF)))
1895 except ValueError:
1896 self.assertRaises(ValueError, math.tan, INF)
1897 self.assertRaises(ValueError, math.tan, NINF)
1898 self.assertTrue(math.isnan(math.tan(NAN)))
1899
1900 def testTanh(self):
1901 self.assertRaises(TypeError, math.tanh)
1902 self.ftest('tanh(0)', math.tanh(0), 0)
1903 self.ftest('tanh(1)+tanh(-1)', math.tanh(1)+math.tanh(-1), 0,
1904 abs_tol=math.ulp(1))
1905 self.ftest('tanh(inf)', math.tanh(INF), 1)
1906 self.ftest('tanh(-inf)', math.tanh(NINF), -1)
1907 self.assertTrue(math.isnan(math.tanh(NAN)))
1908
1909 @requires_IEEE_754
1910 def testTanhSign(self):
1911 # check that tanh(-0.) == -0. on IEEE 754 systems
1912 self.assertEqual(math.tanh(-0.), -0.)
1913 self.assertEqual(math.copysign(1., math.tanh(-0.)),
1914 math.copysign(1., -0.))
1915
1916 def test_trunc(self):
1917 self.assertEqual(math.trunc(1), 1)
1918 self.assertEqual(math.trunc(-1), -1)
1919 self.assertEqual(type(math.trunc(1)), int)
1920 self.assertEqual(type(math.trunc(1.5)), int)
1921 self.assertEqual(math.trunc(1.5), 1)
1922 self.assertEqual(math.trunc(-1.5), -1)
1923 self.assertEqual(math.trunc(1.999999), 1)
1924 self.assertEqual(math.trunc(-1.999999), -1)
1925 self.assertEqual(math.trunc(-0.999999), -0)
1926 self.assertEqual(math.trunc(-100.999), -100)
1927
1928 class TestTrunc:
1929 def __trunc__(self):
1930 return 23
1931 class FloatTrunc(float):
1932 def __trunc__(self):
1933 return 23
1934 class TestNoTrunc:
1935 pass
1936 class TestBadTrunc:
1937 __trunc__ = BadDescr()
1938
1939 self.assertEqual(math.trunc(TestTrunc()), 23)
1940 self.assertEqual(math.trunc(FloatTrunc()), 23)
1941
1942 self.assertRaises(TypeError, math.trunc)
1943 self.assertRaises(TypeError, math.trunc, 1, 2)
1944 self.assertRaises(TypeError, math.trunc, FloatLike(23.5))
1945 self.assertRaises(TypeError, math.trunc, TestNoTrunc())
1946 self.assertRaises(ValueError, math.trunc, TestBadTrunc())
1947
1948 def testIsfinite(self):
1949 self.assertTrue(math.isfinite(0.0))
1950 self.assertTrue(math.isfinite(-0.0))
1951 self.assertTrue(math.isfinite(1.0))
1952 self.assertTrue(math.isfinite(-1.0))
1953 self.assertFalse(math.isfinite(float("nan")))
1954 self.assertFalse(math.isfinite(float("inf")))
1955 self.assertFalse(math.isfinite(float("-inf")))
1956
1957 def testIsnan(self):
1958 self.assertTrue(math.isnan(float("nan")))
1959 self.assertTrue(math.isnan(float("-nan")))
1960 self.assertTrue(math.isnan(float("inf") * 0.))
1961 self.assertFalse(math.isnan(float("inf")))
1962 self.assertFalse(math.isnan(0.))
1963 self.assertFalse(math.isnan(1.))
1964
1965 def testIsinf(self):
1966 self.assertTrue(math.isinf(float("inf")))
1967 self.assertTrue(math.isinf(float("-inf")))
1968 self.assertTrue(math.isinf(1E400))
1969 self.assertTrue(math.isinf(-1E400))
1970 self.assertFalse(math.isinf(float("nan")))
1971 self.assertFalse(math.isinf(0.))
1972 self.assertFalse(math.isinf(1.))
1973
1974 def test_nan_constant(self):
1975 # `math.nan` must be a quiet NaN with positive sign bit
1976 self.assertTrue(math.isnan(math.nan))
1977 self.assertEqual(math.copysign(1., math.nan), 1.)
1978
1979 def test_inf_constant(self):
1980 self.assertTrue(math.isinf(math.inf))
1981 self.assertGreater(math.inf, 0.0)
1982 self.assertEqual(math.inf, float("inf"))
1983 self.assertEqual(-math.inf, float("-inf"))
1984
1985 # RED_FLAG 16-Oct-2000 Tim
1986 # While 2.0 is more consistent about exceptions than previous releases, it
1987 # still fails this part of the test on some platforms. For now, we only
1988 # *run* test_exceptions() in verbose mode, so that this isn't normally
1989 # tested.
1990 @unittest.skipUnless(verbose, 'requires verbose mode')
1991 def test_exceptions(self):
1992 try:
1993 x = math.exp(-1000000000)
1994 except:
1995 # mathmodule.c is failing to weed out underflows from libm, or
1996 # we've got an fp format with huge dynamic range
1997 self.fail("underflowing exp() should not have raised "
1998 "an exception")
1999 if x != 0:
2000 self.fail("underflowing exp() should have returned 0")
2001
2002 # If this fails, probably using a strict IEEE-754 conforming libm, and x
2003 # is +Inf afterwards. But Python wants overflows detected by default.
2004 try:
2005 x = math.exp(1000000000)
2006 except OverflowError:
2007 pass
2008 else:
2009 self.fail("overflowing exp() didn't trigger OverflowError")
2010
2011 # If this fails, it could be a puzzle. One odd possibility is that
2012 # mathmodule.c's macros are getting confused while comparing
2013 # Inf (HUGE_VAL) to a NaN, and artificially setting errno to ERANGE
2014 # as a result (and so raising OverflowError instead).
2015 try:
2016 x = math.sqrt(-1.0)
2017 except ValueError:
2018 pass
2019 else:
2020 self.fail("sqrt(-1) didn't raise ValueError")
2021
2022 @requires_IEEE_754
2023 def test_testfile(self):
2024 # Some tests need to be skipped on ancient OS X versions.
2025 # See issue #27953.
2026 SKIP_ON_TIGER = {'tan0064'}
2027
2028 osx_version = None
2029 if sys.platform == 'darwin':
2030 version_txt = platform.mac_ver()[0]
2031 try:
2032 osx_version = tuple(map(int, version_txt.split('.')))
2033 except ValueError:
2034 pass
2035
2036 fail_fmt = "{}: {}({!r}): {}"
2037
2038 failures = []
2039 for id, fn, ar, ai, er, ei, flags in parse_testfile(test_file):
2040 # Skip if either the input or result is complex
2041 if ai != 0.0 or ei != 0.0:
2042 continue
2043 if fn in ['rect', 'polar']:
2044 # no real versions of rect, polar
2045 continue
2046 # Skip certain tests on OS X 10.4.
2047 if osx_version is not None and osx_version < (10, 5):
2048 if id in SKIP_ON_TIGER:
2049 continue
2050
2051 func = getattr(math, fn)
2052
2053 if 'invalid' in flags or 'divide-by-zero' in flags:
2054 er = 'ValueError'
2055 elif 'overflow' in flags:
2056 er = 'OverflowError'
2057
2058 try:
2059 result = func(ar)
2060 except ValueError:
2061 result = 'ValueError'
2062 except OverflowError:
2063 result = 'OverflowError'
2064
2065 # C99+ says for math.h's sqrt: If the argument is +∞ or ±0, it is
2066 # returned, unmodified. On another hand, for csqrt: If z is ±0+0i,
2067 # the result is +0+0i. Lets correct zero sign of er to follow
2068 # first convention.
2069 if id in ['sqrt0002', 'sqrt0003', 'sqrt1001', 'sqrt1023']:
2070 er = math.copysign(er, ar)
2071
2072 # Default tolerances
2073 ulp_tol, abs_tol = 5, 0.0
2074
2075 failure = result_check(er, result, ulp_tol, abs_tol)
2076 if failure is None:
2077 continue
2078
2079 msg = fail_fmt.format(id, fn, ar, failure)
2080 failures.append(msg)
2081
2082 if failures:
2083 self.fail('Failures in test_testfile:\n ' +
2084 '\n '.join(failures))
2085
2086 @requires_IEEE_754
2087 def test_mtestfile(self):
2088 fail_fmt = "{}: {}({!r}): {}"
2089
2090 failures = []
2091 for id, fn, arg, expected, flags in parse_mtestfile(math_testcases):
2092 func = getattr(math, fn)
2093
2094 if 'invalid' in flags or 'divide-by-zero' in flags:
2095 expected = 'ValueError'
2096 elif 'overflow' in flags:
2097 expected = 'OverflowError'
2098
2099 try:
2100 got = func(arg)
2101 except ValueError:
2102 got = 'ValueError'
2103 except OverflowError:
2104 got = 'OverflowError'
2105
2106 # Default tolerances
2107 ulp_tol, abs_tol = 5, 0.0
2108
2109 # Exceptions to the defaults
2110 if fn == 'gamma':
2111 # Experimental results on one platform gave
2112 # an accuracy of <= 10 ulps across the entire float
2113 # domain. We weaken that to require 20 ulp accuracy.
2114 ulp_tol = 20
2115
2116 elif fn == 'lgamma':
2117 # we use a weaker accuracy test for lgamma;
2118 # lgamma only achieves an absolute error of
2119 # a few multiples of the machine accuracy, in
2120 # general.
2121 abs_tol = 1e-15
2122
2123 elif fn == 'erfc' and arg >= 0.0:
2124 # erfc has less-than-ideal accuracy for large
2125 # arguments (x ~ 25 or so), mainly due to the
2126 # error involved in computing exp(-x*x).
2127 #
2128 # Observed between CPython and mpmath at 25 dp:
2129 # x < 0 : err <= 2 ulp
2130 # 0 <= x < 1 : err <= 10 ulp
2131 # 1 <= x < 10 : err <= 100 ulp
2132 # 10 <= x < 20 : err <= 300 ulp
2133 # 20 <= x : < 600 ulp
2134 #
2135 if arg < 1.0:
2136 ulp_tol = 10
2137 elif arg < 10.0:
2138 ulp_tol = 100
2139 else:
2140 ulp_tol = 1000
2141
2142 failure = result_check(expected, got, ulp_tol, abs_tol)
2143 if failure is None:
2144 continue
2145
2146 msg = fail_fmt.format(id, fn, arg, failure)
2147 failures.append(msg)
2148
2149 if failures:
2150 self.fail('Failures in test_mtestfile:\n ' +
2151 '\n '.join(failures))
2152
2153 def test_prod(self):
2154 from fractions import Fraction as F
2155
2156 prod = math.prod
2157 self.assertEqual(prod([]), 1)
2158 self.assertEqual(prod([], start=5), 5)
2159 self.assertEqual(prod(list(range(2,8))), 5040)
2160 self.assertEqual(prod(iter(list(range(2,8)))), 5040)
2161 self.assertEqual(prod(range(1, 10), start=10), 3628800)
2162
2163 self.assertEqual(prod([1, 2, 3, 4, 5]), 120)
2164 self.assertEqual(prod([1.0, 2.0, 3.0, 4.0, 5.0]), 120.0)
2165 self.assertEqual(prod([1, 2, 3, 4.0, 5.0]), 120.0)
2166 self.assertEqual(prod([1.0, 2.0, 3.0, 4, 5]), 120.0)
2167 self.assertEqual(prod([1., F(3, 2)]), 1.5)
2168
2169 # Error in multiplication
2170 class BadMultiply:
2171 def __rmul__(self, other):
2172 raise RuntimeError
2173 with self.assertRaises(RuntimeError):
2174 prod([10., BadMultiply()])
2175
2176 # Test overflow in fast-path for integers
2177 self.assertEqual(prod([1, 1, 2**32, 1, 1]), 2**32)
2178 # Test overflow in fast-path for floats
2179 self.assertEqual(prod([1.0, 1.0, 2**32, 1, 1]), float(2**32))
2180
2181 self.assertRaises(TypeError, prod)
2182 self.assertRaises(TypeError, prod, 42)
2183 self.assertRaises(TypeError, prod, ['a', 'b', 'c'])
2184 self.assertRaises(TypeError, prod, ['a', 'b', 'c'], start='')
2185 self.assertRaises(TypeError, prod, [b'a', b'c'], start=b'')
2186 values = [bytearray(b'a'), bytearray(b'b')]
2187 self.assertRaises(TypeError, prod, values, start=bytearray(b''))
2188 self.assertRaises(TypeError, prod, [[1], [2], [3]])
2189 self.assertRaises(TypeError, prod, [{2:3}])
2190 self.assertRaises(TypeError, prod, [{2:3}]*2, start={2:3})
2191 self.assertRaises(TypeError, prod, [[1], [2], [3]], start=[])
2192
2193 # Some odd cases
2194 self.assertEqual(prod([2, 3], start='ab'), 'abababababab')
2195 self.assertEqual(prod([2, 3], start=[1, 2]), [1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2])
2196 self.assertEqual(prod([], start={2: 3}), {2:3})
2197
2198 with self.assertRaises(TypeError):
2199 prod([10, 20], 1) # start is a keyword-only argument
2200
2201 self.assertEqual(prod([0, 1, 2, 3]), 0)
2202 self.assertEqual(prod([1, 0, 2, 3]), 0)
2203 self.assertEqual(prod([1, 2, 3, 0]), 0)
2204
2205 def _naive_prod(iterable, start=1):
2206 for elem in iterable:
2207 start *= elem
2208 return start
2209
2210 # Big integers
2211
2212 iterable = range(1, 10000)
2213 self.assertEqual(prod(iterable), _naive_prod(iterable))
2214 iterable = range(-10000, -1)
2215 self.assertEqual(prod(iterable), _naive_prod(iterable))
2216 iterable = range(-1000, 1000)
2217 self.assertEqual(prod(iterable), 0)
2218
2219 # Big floats
2220
2221 iterable = [float(x) for x in range(1, 1000)]
2222 self.assertEqual(prod(iterable), _naive_prod(iterable))
2223 iterable = [float(x) for x in range(-1000, -1)]
2224 self.assertEqual(prod(iterable), _naive_prod(iterable))
2225 iterable = [float(x) for x in range(-1000, 1000)]
2226 self.assertIsNaN(prod(iterable))
2227
2228 # Float tests
2229
2230 self.assertIsNaN(prod([1, 2, 3, float("nan"), 2, 3]))
2231 self.assertIsNaN(prod([1, 0, float("nan"), 2, 3]))
2232 self.assertIsNaN(prod([1, float("nan"), 0, 3]))
2233 self.assertIsNaN(prod([1, float("inf"), float("nan"),3]))
2234 self.assertIsNaN(prod([1, float("-inf"), float("nan"),3]))
2235 self.assertIsNaN(prod([1, float("nan"), float("inf"),3]))
2236 self.assertIsNaN(prod([1, float("nan"), float("-inf"),3]))
2237
2238 self.assertEqual(prod([1, 2, 3, float('inf'),-3,4]), float('-inf'))
2239 self.assertEqual(prod([1, 2, 3, float('-inf'),-3,4]), float('inf'))
2240
2241 self.assertIsNaN(prod([1,2,0,float('inf'), -3, 4]))
2242 self.assertIsNaN(prod([1,2,0,float('-inf'), -3, 4]))
2243 self.assertIsNaN(prod([1, 2, 3, float('inf'), -3, 0, 3]))
2244 self.assertIsNaN(prod([1, 2, 3, float('-inf'), -3, 0, 2]))
2245
2246 # Type preservation
2247
2248 self.assertEqual(type(prod([1, 2, 3, 4, 5, 6])), int)
2249 self.assertEqual(type(prod([1, 2.0, 3, 4, 5, 6])), float)
2250 self.assertEqual(type(prod(range(1, 10000))), int)
2251 self.assertEqual(type(prod(range(1, 10000), start=1.0)), float)
2252 self.assertEqual(type(prod([1, decimal.Decimal(2.0), 3, 4, 5, 6])),
2253 decimal.Decimal)
2254
2255 def testPerm(self):
2256 perm = math.perm
2257 factorial = math.factorial
2258 # Test if factorial definition is satisfied
2259 for n in range(500):
2260 for k in (range(n + 1) if n < 100 else range(30) if n < 200 else range(10)):
2261 self.assertEqual(perm(n, k),
2262 factorial(n) // factorial(n - k))
2263
2264 # Test for Pascal's identity
2265 for n in range(1, 100):
2266 for k in range(1, n):
2267 self.assertEqual(perm(n, k), perm(n - 1, k - 1) * k + perm(n - 1, k))
2268
2269 # Test corner cases
2270 for n in range(1, 100):
2271 self.assertEqual(perm(n, 0), 1)
2272 self.assertEqual(perm(n, 1), n)
2273 self.assertEqual(perm(n, n), factorial(n))
2274
2275 # Test one argument form
2276 for n in range(20):
2277 self.assertEqual(perm(n), factorial(n))
2278 self.assertEqual(perm(n, None), factorial(n))
2279
2280 # Raises TypeError if any argument is non-integer or argument count is
2281 # not 1 or 2
2282 self.assertRaises(TypeError, perm, 10, 1.0)
2283 self.assertRaises(TypeError, perm, 10, decimal.Decimal(1.0))
2284 self.assertRaises(TypeError, perm, 10, "1")
2285 self.assertRaises(TypeError, perm, 10.0, 1)
2286 self.assertRaises(TypeError, perm, decimal.Decimal(10.0), 1)
2287 self.assertRaises(TypeError, perm, "10", 1)
2288
2289 self.assertRaises(TypeError, perm)
2290 self.assertRaises(TypeError, perm, 10, 1, 3)
2291 self.assertRaises(TypeError, perm)
2292
2293 # Raises Value error if not k or n are negative numbers
2294 self.assertRaises(ValueError, perm, -1, 1)
2295 self.assertRaises(ValueError, perm, -2**1000, 1)
2296 self.assertRaises(ValueError, perm, 1, -1)
2297 self.assertRaises(ValueError, perm, 1, -2**1000)
2298
2299 # Returns zero if k is greater than n
2300 self.assertEqual(perm(1, 2), 0)
2301 self.assertEqual(perm(1, 2**1000), 0)
2302
2303 n = 2**1000
2304 self.assertEqual(perm(n, 0), 1)
2305 self.assertEqual(perm(n, 1), n)
2306 self.assertEqual(perm(n, 2), n * (n-1))
2307 if support.check_impl_detail(cpython=True):
2308 self.assertRaises(OverflowError, perm, n, n)
2309
2310 for n, k in (True, True), (True, False), (False, False):
2311 self.assertEqual(perm(n, k), 1)
2312 self.assertIs(type(perm(n, k)), int)
2313 self.assertEqual(perm(IntSubclass(5), IntSubclass(2)), 20)
2314 self.assertEqual(perm(MyIndexable(5), MyIndexable(2)), 20)
2315 for k in range(3):
2316 self.assertIs(type(perm(IntSubclass(5), IntSubclass(k))), int)
2317 self.assertIs(type(perm(MyIndexable(5), MyIndexable(k))), int)
2318
2319 def testComb(self):
2320 comb = math.comb
2321 factorial = math.factorial
2322 # Test if factorial definition is satisfied
2323 for n in range(500):
2324 for k in (range(n + 1) if n < 100 else range(30) if n < 200 else range(10)):
2325 self.assertEqual(comb(n, k), factorial(n)
2326 // (factorial(k) * factorial(n - k)))
2327
2328 # Test for Pascal's identity
2329 for n in range(1, 100):
2330 for k in range(1, n):
2331 self.assertEqual(comb(n, k), comb(n - 1, k - 1) + comb(n - 1, k))
2332
2333 # Test corner cases
2334 for n in range(100):
2335 self.assertEqual(comb(n, 0), 1)
2336 self.assertEqual(comb(n, n), 1)
2337
2338 for n in range(1, 100):
2339 self.assertEqual(comb(n, 1), n)
2340 self.assertEqual(comb(n, n - 1), n)
2341
2342 # Test Symmetry
2343 for n in range(100):
2344 for k in range(n // 2):
2345 self.assertEqual(comb(n, k), comb(n, n - k))
2346
2347 # Raises TypeError if any argument is non-integer or argument count is
2348 # not 2
2349 self.assertRaises(TypeError, comb, 10, 1.0)
2350 self.assertRaises(TypeError, comb, 10, decimal.Decimal(1.0))
2351 self.assertRaises(TypeError, comb, 10, "1")
2352 self.assertRaises(TypeError, comb, 10.0, 1)
2353 self.assertRaises(TypeError, comb, decimal.Decimal(10.0), 1)
2354 self.assertRaises(TypeError, comb, "10", 1)
2355
2356 self.assertRaises(TypeError, comb, 10)
2357 self.assertRaises(TypeError, comb, 10, 1, 3)
2358 self.assertRaises(TypeError, comb)
2359
2360 # Raises Value error if not k or n are negative numbers
2361 self.assertRaises(ValueError, comb, -1, 1)
2362 self.assertRaises(ValueError, comb, -2**1000, 1)
2363 self.assertRaises(ValueError, comb, 1, -1)
2364 self.assertRaises(ValueError, comb, 1, -2**1000)
2365
2366 # Returns zero if k is greater than n
2367 self.assertEqual(comb(1, 2), 0)
2368 self.assertEqual(comb(1, 2**1000), 0)
2369
2370 n = 2**1000
2371 self.assertEqual(comb(n, 0), 1)
2372 self.assertEqual(comb(n, 1), n)
2373 self.assertEqual(comb(n, 2), n * (n-1) // 2)
2374 self.assertEqual(comb(n, n), 1)
2375 self.assertEqual(comb(n, n-1), n)
2376 self.assertEqual(comb(n, n-2), n * (n-1) // 2)
2377 if support.check_impl_detail(cpython=True):
2378 self.assertRaises(OverflowError, comb, n, n//2)
2379
2380 for n, k in (True, True), (True, False), (False, False):
2381 self.assertEqual(comb(n, k), 1)
2382 self.assertIs(type(comb(n, k)), int)
2383 self.assertEqual(comb(IntSubclass(5), IntSubclass(2)), 10)
2384 self.assertEqual(comb(MyIndexable(5), MyIndexable(2)), 10)
2385 for k in range(3):
2386 self.assertIs(type(comb(IntSubclass(5), IntSubclass(k))), int)
2387 self.assertIs(type(comb(MyIndexable(5), MyIndexable(k))), int)
2388
2389 @requires_IEEE_754
2390 def test_nextafter(self):
2391 # around 2^52 and 2^63
2392 self.assertEqual(math.nextafter(4503599627370496.0, -INF),
2393 4503599627370495.5)
2394 self.assertEqual(math.nextafter(4503599627370496.0, INF),
2395 4503599627370497.0)
2396 self.assertEqual(math.nextafter(9223372036854775808.0, 0.0),
2397 9223372036854774784.0)
2398 self.assertEqual(math.nextafter(-9223372036854775808.0, 0.0),
2399 -9223372036854774784.0)
2400
2401 # around 1.0
2402 self.assertEqual(math.nextafter(1.0, -INF),
2403 float.fromhex('0x1.fffffffffffffp-1'))
2404 self.assertEqual(math.nextafter(1.0, INF),
2405 float.fromhex('0x1.0000000000001p+0'))
2406 self.assertEqual(math.nextafter(1.0, -INF, steps=1),
2407 float.fromhex('0x1.fffffffffffffp-1'))
2408 self.assertEqual(math.nextafter(1.0, INF, steps=1),
2409 float.fromhex('0x1.0000000000001p+0'))
2410 self.assertEqual(math.nextafter(1.0, -INF, steps=3),
2411 float.fromhex('0x1.ffffffffffffdp-1'))
2412 self.assertEqual(math.nextafter(1.0, INF, steps=3),
2413 float.fromhex('0x1.0000000000003p+0'))
2414
2415 # x == y: y is returned
2416 for steps in range(1, 5):
2417 self.assertEqual(math.nextafter(2.0, 2.0, steps=steps), 2.0)
2418 self.assertEqualSign(math.nextafter(-0.0, +0.0, steps=steps), +0.0)
2419 self.assertEqualSign(math.nextafter(+0.0, -0.0, steps=steps), -0.0)
2420
2421 # around 0.0
2422 smallest_subnormal = sys.float_info.min * sys.float_info.epsilon
2423 self.assertEqual(math.nextafter(+0.0, INF), smallest_subnormal)
2424 self.assertEqual(math.nextafter(-0.0, INF), smallest_subnormal)
2425 self.assertEqual(math.nextafter(+0.0, -INF), -smallest_subnormal)
2426 self.assertEqual(math.nextafter(-0.0, -INF), -smallest_subnormal)
2427 self.assertEqualSign(math.nextafter(smallest_subnormal, +0.0), +0.0)
2428 self.assertEqualSign(math.nextafter(-smallest_subnormal, +0.0), -0.0)
2429 self.assertEqualSign(math.nextafter(smallest_subnormal, -0.0), +0.0)
2430 self.assertEqualSign(math.nextafter(-smallest_subnormal, -0.0), -0.0)
2431
2432 # around infinity
2433 largest_normal = sys.float_info.max
2434 self.assertEqual(math.nextafter(INF, 0.0), largest_normal)
2435 self.assertEqual(math.nextafter(-INF, 0.0), -largest_normal)
2436 self.assertEqual(math.nextafter(largest_normal, INF), INF)
2437 self.assertEqual(math.nextafter(-largest_normal, -INF), -INF)
2438
2439 # NaN
2440 self.assertIsNaN(math.nextafter(NAN, 1.0))
2441 self.assertIsNaN(math.nextafter(1.0, NAN))
2442 self.assertIsNaN(math.nextafter(NAN, NAN))
2443
2444 self.assertEqual(1.0, math.nextafter(1.0, INF, steps=0))
2445 with self.assertRaises(ValueError):
2446 math.nextafter(1.0, INF, steps=-1)
2447
2448
2449 @requires_IEEE_754
2450 def test_ulp(self):
2451 self.assertEqual(math.ulp(1.0), sys.float_info.epsilon)
2452 # use int ** int rather than float ** int to not rely on pow() accuracy
2453 self.assertEqual(math.ulp(2 ** 52), 1.0)
2454 self.assertEqual(math.ulp(2 ** 53), 2.0)
2455 self.assertEqual(math.ulp(2 ** 64), 4096.0)
2456
2457 # min and max
2458 self.assertEqual(math.ulp(0.0),
2459 sys.float_info.min * sys.float_info.epsilon)
2460 self.assertEqual(math.ulp(FLOAT_MAX),
2461 FLOAT_MAX - math.nextafter(FLOAT_MAX, -INF))
2462
2463 # special cases
2464 self.assertEqual(math.ulp(INF), INF)
2465 self.assertIsNaN(math.ulp(math.nan))
2466
2467 # negative number: ulp(-x) == ulp(x)
2468 for x in (0.0, 1.0, 2 ** 52, 2 ** 64, INF):
2469 with self.subTest(x=x):
2470 self.assertEqual(math.ulp(-x), math.ulp(x))
2471
2472 def test_issue39871(self):
2473 # A SystemError should not be raised if the first arg to atan2(),
2474 # copysign(), or remainder() cannot be converted to a float.
2475 class F:
2476 def __float__(self):
2477 self.converted = True
2478 1/0
2479 for func in math.atan2, math.copysign, math.remainder:
2480 y = F()
2481 with self.assertRaises(TypeError):
2482 func("not a number", y)
2483
2484 # There should not have been any attempt to convert the second
2485 # argument to a float.
2486 self.assertFalse(getattr(y, "converted", False))
2487
2488 def test_input_exceptions(self):
2489 self.assertRaises(TypeError, math.exp, "spam")
2490 self.assertRaises(TypeError, math.erf, "spam")
2491 self.assertRaises(TypeError, math.atan2, "spam", 1.0)
2492 self.assertRaises(TypeError, math.atan2, 1.0, "spam")
2493 self.assertRaises(TypeError, math.atan2, 1.0)
2494 self.assertRaises(TypeError, math.atan2, 1.0, 2.0, 3.0)
2495
2496 # Custom assertions.
2497
2498 def assertIsNaN(self, value):
2499 if not math.isnan(value):
2500 self.fail("Expected a NaN, got {!r}.".format(value))
2501
2502 def assertEqualSign(self, x, y):
2503 """Similar to assertEqual(), but compare also the sign with copysign().
2504
2505 Function useful to compare signed zeros.
2506 """
2507 self.assertEqual(x, y)
2508 self.assertEqual(math.copysign(1.0, x), math.copysign(1.0, y))
2509
2510
2511 class IsCloseTests(unittest.TestCase):
2512 isclose = math.isclose # subclasses should override this
2513
2514 def assertIsClose(self, a, b, *args, **kwargs):
2515 self.assertTrue(self.isclose(a, b, *args, **kwargs),
2516 msg="%s and %s should be close!" % (a, b))
2517
2518 def assertIsNotClose(self, a, b, *args, **kwargs):
2519 self.assertFalse(self.isclose(a, b, *args, **kwargs),
2520 msg="%s and %s should not be close!" % (a, b))
2521
2522 def assertAllClose(self, examples, *args, **kwargs):
2523 for a, b in examples:
2524 self.assertIsClose(a, b, *args, **kwargs)
2525
2526 def assertAllNotClose(self, examples, *args, **kwargs):
2527 for a, b in examples:
2528 self.assertIsNotClose(a, b, *args, **kwargs)
2529
2530 def test_negative_tolerances(self):
2531 # ValueError should be raised if either tolerance is less than zero
2532 with self.assertRaises(ValueError):
2533 self.assertIsClose(1, 1, rel_tol=-1e-100)
2534 with self.assertRaises(ValueError):
2535 self.assertIsClose(1, 1, rel_tol=1e-100, abs_tol=-1e10)
2536
2537 def test_identical(self):
2538 # identical values must test as close
2539 identical_examples = [(2.0, 2.0),
2540 (0.1e200, 0.1e200),
2541 (1.123e-300, 1.123e-300),
2542 (12345, 12345.0),
2543 (0.0, -0.0),
2544 (345678, 345678)]
2545 self.assertAllClose(identical_examples, rel_tol=0.0, abs_tol=0.0)
2546
2547 def test_eight_decimal_places(self):
2548 # examples that are close to 1e-8, but not 1e-9
2549 eight_decimal_places_examples = [(1e8, 1e8 + 1),
2550 (-1e-8, -1.000000009e-8),
2551 (1.12345678, 1.12345679)]
2552 self.assertAllClose(eight_decimal_places_examples, rel_tol=1e-8)
2553 self.assertAllNotClose(eight_decimal_places_examples, rel_tol=1e-9)
2554
2555 def test_near_zero(self):
2556 # values close to zero
2557 near_zero_examples = [(1e-9, 0.0),
2558 (-1e-9, 0.0),
2559 (-1e-150, 0.0)]
2560 # these should not be close to any rel_tol
2561 self.assertAllNotClose(near_zero_examples, rel_tol=0.9)
2562 # these should be close to abs_tol=1e-8
2563 self.assertAllClose(near_zero_examples, abs_tol=1e-8)
2564
2565 def test_identical_infinite(self):
2566 # these are close regardless of tolerance -- i.e. they are equal
2567 self.assertIsClose(INF, INF)
2568 self.assertIsClose(INF, INF, abs_tol=0.0)
2569 self.assertIsClose(NINF, NINF)
2570 self.assertIsClose(NINF, NINF, abs_tol=0.0)
2571
2572 def test_inf_ninf_nan(self):
2573 # these should never be close (following IEEE 754 rules for equality)
2574 not_close_examples = [(NAN, NAN),
2575 (NAN, 1e-100),
2576 (1e-100, NAN),
2577 (INF, NAN),
2578 (NAN, INF),
2579 (INF, NINF),
2580 (INF, 1.0),
2581 (1.0, INF),
2582 (INF, 1e308),
2583 (1e308, INF)]
2584 # use largest reasonable tolerance
2585 self.assertAllNotClose(not_close_examples, abs_tol=0.999999999999999)
2586
2587 def test_zero_tolerance(self):
2588 # test with zero tolerance
2589 zero_tolerance_close_examples = [(1.0, 1.0),
2590 (-3.4, -3.4),
2591 (-1e-300, -1e-300)]
2592 self.assertAllClose(zero_tolerance_close_examples, rel_tol=0.0)
2593
2594 zero_tolerance_not_close_examples = [(1.0, 1.000000000000001),
2595 (0.99999999999999, 1.0),
2596 (1.0e200, .999999999999999e200)]
2597 self.assertAllNotClose(zero_tolerance_not_close_examples, rel_tol=0.0)
2598
2599 def test_asymmetry(self):
2600 # test the asymmetry example from PEP 485
2601 self.assertAllClose([(9, 10), (10, 9)], rel_tol=0.1)
2602
2603 def test_integers(self):
2604 # test with integer values
2605 integer_examples = [(100000001, 100000000),
2606 (123456789, 123456788)]
2607
2608 self.assertAllClose(integer_examples, rel_tol=1e-8)
2609 self.assertAllNotClose(integer_examples, rel_tol=1e-9)
2610
2611 def test_decimals(self):
2612 # test with Decimal values
2613 from decimal import Decimal
2614
2615 decimal_examples = [(Decimal('1.00000001'), Decimal('1.0')),
2616 (Decimal('1.00000001e-20'), Decimal('1.0e-20')),
2617 (Decimal('1.00000001e-100'), Decimal('1.0e-100')),
2618 (Decimal('1.00000001e20'), Decimal('1.0e20'))]
2619 self.assertAllClose(decimal_examples, rel_tol=1e-8)
2620 self.assertAllNotClose(decimal_examples, rel_tol=1e-9)
2621
2622 def test_fractions(self):
2623 # test with Fraction values
2624 from fractions import Fraction
2625
2626 fraction_examples = [
2627 (Fraction(1, 100000000) + 1, Fraction(1)),
2628 (Fraction(100000001), Fraction(100000000)),
2629 (Fraction(10**8 + 1, 10**28), Fraction(1, 10**20))]
2630 self.assertAllClose(fraction_examples, rel_tol=1e-8)
2631 self.assertAllNotClose(fraction_examples, rel_tol=1e-9)
2632
2633
2634 class FMATests(unittest.TestCase):
2635 """ Tests for math.fma. """
2636
2637 def test_fma_nan_results(self):
2638 # Selected representative values.
2639 values = [
2640 -math.inf, -1e300, -2.3, -1e-300, -0.0,
2641 0.0, 1e-300, 2.3, 1e300, math.inf, math.nan
2642 ]
2643
2644 # If any input is a NaN, the result should be a NaN, too.
2645 for a, b in itertools.product(values, repeat=2):
2646 with self.subTest(a=a, b=b):
2647 self.assertIsNaN(math.fma(math.nan, a, b))
2648 self.assertIsNaN(math.fma(a, math.nan, b))
2649 self.assertIsNaN(math.fma(a, b, math.nan))
2650
2651 def test_fma_infinities(self):
2652 # Cases involving infinite inputs or results.
2653 positives = [1e-300, 2.3, 1e300, math.inf]
2654 finites = [-1e300, -2.3, -1e-300, -0.0, 0.0, 1e-300, 2.3, 1e300]
2655 non_nans = [-math.inf, -2.3, -0.0, 0.0, 2.3, math.inf]
2656
2657 # ValueError due to inf * 0 computation.
2658 for c in non_nans:
2659 for infinity in [math.inf, -math.inf]:
2660 for zero in [0.0, -0.0]:
2661 with self.subTest(c=c, infinity=infinity, zero=zero):
2662 with self.assertRaises(ValueError):
2663 math.fma(infinity, zero, c)
2664 with self.assertRaises(ValueError):
2665 math.fma(zero, infinity, c)
2666
2667 # ValueError when a*b and c both infinite of opposite signs.
2668 for b in positives:
2669 with self.subTest(b=b):
2670 with self.assertRaises(ValueError):
2671 math.fma(math.inf, b, -math.inf)
2672 with self.assertRaises(ValueError):
2673 math.fma(math.inf, -b, math.inf)
2674 with self.assertRaises(ValueError):
2675 math.fma(-math.inf, -b, -math.inf)
2676 with self.assertRaises(ValueError):
2677 math.fma(-math.inf, b, math.inf)
2678 with self.assertRaises(ValueError):
2679 math.fma(b, math.inf, -math.inf)
2680 with self.assertRaises(ValueError):
2681 math.fma(-b, math.inf, math.inf)
2682 with self.assertRaises(ValueError):
2683 math.fma(-b, -math.inf, -math.inf)
2684 with self.assertRaises(ValueError):
2685 math.fma(b, -math.inf, math.inf)
2686
2687 # Infinite result when a*b and c both infinite of the same sign.
2688 for b in positives:
2689 with self.subTest(b=b):
2690 self.assertEqual(math.fma(math.inf, b, math.inf), math.inf)
2691 self.assertEqual(math.fma(math.inf, -b, -math.inf), -math.inf)
2692 self.assertEqual(math.fma(-math.inf, -b, math.inf), math.inf)
2693 self.assertEqual(math.fma(-math.inf, b, -math.inf), -math.inf)
2694 self.assertEqual(math.fma(b, math.inf, math.inf), math.inf)
2695 self.assertEqual(math.fma(-b, math.inf, -math.inf), -math.inf)
2696 self.assertEqual(math.fma(-b, -math.inf, math.inf), math.inf)
2697 self.assertEqual(math.fma(b, -math.inf, -math.inf), -math.inf)
2698
2699 # Infinite result when a*b finite, c infinite.
2700 for a, b in itertools.product(finites, finites):
2701 with self.subTest(b=b):
2702 self.assertEqual(math.fma(a, b, math.inf), math.inf)
2703 self.assertEqual(math.fma(a, b, -math.inf), -math.inf)
2704
2705 # Infinite result when a*b infinite, c finite.
2706 for b, c in itertools.product(positives, finites):
2707 with self.subTest(b=b, c=c):
2708 self.assertEqual(math.fma(math.inf, b, c), math.inf)
2709 self.assertEqual(math.fma(-math.inf, b, c), -math.inf)
2710 self.assertEqual(math.fma(-math.inf, -b, c), math.inf)
2711 self.assertEqual(math.fma(math.inf, -b, c), -math.inf)
2712
2713 self.assertEqual(math.fma(b, math.inf, c), math.inf)
2714 self.assertEqual(math.fma(b, -math.inf, c), -math.inf)
2715 self.assertEqual(math.fma(-b, -math.inf, c), math.inf)
2716 self.assertEqual(math.fma(-b, math.inf, c), -math.inf)
2717
2718 # gh-73468: On some platforms, libc fma() doesn't implement IEE 754-2008
2719 # properly: it doesn't use the right sign when the result is zero.
2720 @unittest.skipIf(
2721 sys.platform.startswith(("freebsd", "wasi", "netbsd", "emscripten"))
2722 or (sys.platform == "android" and platform.machine() == "x86_64")
2723 or support.linked_to_musl(), # gh-131032
2724 f"this platform doesn't implement IEE 754-2008 properly")
2725 def test_fma_zero_result(self):
2726 nonnegative_finites = [0.0, 1e-300, 2.3, 1e300]
2727
2728 # Zero results from exact zero inputs.
2729 for b in nonnegative_finites:
2730 with self.subTest(b=b):
2731 self.assertIsPositiveZero(math.fma(0.0, b, 0.0))
2732 self.assertIsPositiveZero(math.fma(0.0, b, -0.0))
2733 self.assertIsNegativeZero(math.fma(0.0, -b, -0.0))
2734 self.assertIsPositiveZero(math.fma(0.0, -b, 0.0))
2735 self.assertIsPositiveZero(math.fma(-0.0, -b, 0.0))
2736 self.assertIsPositiveZero(math.fma(-0.0, -b, -0.0))
2737 self.assertIsNegativeZero(math.fma(-0.0, b, -0.0))
2738 self.assertIsPositiveZero(math.fma(-0.0, b, 0.0))
2739
2740 self.assertIsPositiveZero(math.fma(b, 0.0, 0.0))
2741 self.assertIsPositiveZero(math.fma(b, 0.0, -0.0))
2742 self.assertIsNegativeZero(math.fma(-b, 0.0, -0.0))
2743 self.assertIsPositiveZero(math.fma(-b, 0.0, 0.0))
2744 self.assertIsPositiveZero(math.fma(-b, -0.0, 0.0))
2745 self.assertIsPositiveZero(math.fma(-b, -0.0, -0.0))
2746 self.assertIsNegativeZero(math.fma(b, -0.0, -0.0))
2747 self.assertIsPositiveZero(math.fma(b, -0.0, 0.0))
2748
2749 # Exact zero result from nonzero inputs.
2750 self.assertIsPositiveZero(math.fma(2.0, 2.0, -4.0))
2751 self.assertIsPositiveZero(math.fma(2.0, -2.0, 4.0))
2752 self.assertIsPositiveZero(math.fma(-2.0, -2.0, -4.0))
2753 self.assertIsPositiveZero(math.fma(-2.0, 2.0, 4.0))
2754
2755 # Underflow to zero.
2756 tiny = 1e-300
2757 self.assertIsPositiveZero(math.fma(tiny, tiny, 0.0))
2758 self.assertIsNegativeZero(math.fma(tiny, -tiny, 0.0))
2759 self.assertIsPositiveZero(math.fma(-tiny, -tiny, 0.0))
2760 self.assertIsNegativeZero(math.fma(-tiny, tiny, 0.0))
2761 self.assertIsPositiveZero(math.fma(tiny, tiny, -0.0))
2762 self.assertIsNegativeZero(math.fma(tiny, -tiny, -0.0))
2763 self.assertIsPositiveZero(math.fma(-tiny, -tiny, -0.0))
2764 self.assertIsNegativeZero(math.fma(-tiny, tiny, -0.0))
2765
2766 # Corner case where rounding the multiplication would
2767 # give the wrong result.
2768 x = float.fromhex('0x1p-500')
2769 y = float.fromhex('0x1p-550')
2770 z = float.fromhex('0x1p-1000')
2771 self.assertIsNegativeZero(math.fma(x-y, x+y, -z))
2772 self.assertIsPositiveZero(math.fma(y-x, x+y, z))
2773 self.assertIsNegativeZero(math.fma(y-x, -(x+y), -z))
2774 self.assertIsPositiveZero(math.fma(x-y, -(x+y), z))
2775
2776 def test_fma_overflow(self):
2777 a = b = float.fromhex('0x1p512')
2778 c = float.fromhex('0x1p1023')
2779 # Overflow from multiplication.
2780 with self.assertRaises(OverflowError):
2781 math.fma(a, b, 0.0)
2782 self.assertEqual(math.fma(a, b/2.0, 0.0), c)
2783 # Overflow from the addition.
2784 with self.assertRaises(OverflowError):
2785 math.fma(a, b/2.0, c)
2786 # No overflow, even though a*b overflows a float.
2787 self.assertEqual(math.fma(a, b, -c), c)
2788
2789 # Extreme case: a * b is exactly at the overflow boundary, so the
2790 # tiniest offset makes a difference between overflow and a finite
2791 # result.
2792 a = float.fromhex('0x1.ffffffc000000p+511')
2793 b = float.fromhex('0x1.0000002000000p+512')
2794 c = float.fromhex('0x0.0000000000001p-1022')
2795 with self.assertRaises(OverflowError):
2796 math.fma(a, b, 0.0)
2797 with self.assertRaises(OverflowError):
2798 math.fma(a, b, c)
2799 self.assertEqual(math.fma(a, b, -c),
2800 float.fromhex('0x1.fffffffffffffp+1023'))
2801
2802 # Another extreme case: here a*b is about as large as possible subject
2803 # to math.fma(a, b, c) being finite.
2804 a = float.fromhex('0x1.ae565943785f9p+512')
2805 b = float.fromhex('0x1.3094665de9db8p+512')
2806 c = float.fromhex('0x1.fffffffffffffp+1023')
2807 self.assertEqual(math.fma(a, b, -c), c)
2808
2809 def test_fma_single_round(self):
2810 a = float.fromhex('0x1p-50')
2811 self.assertEqual(math.fma(a - 1.0, a + 1.0, 1.0), a*a)
2812
2813 def test_random(self):
2814 # A collection of randomly generated inputs for which the naive FMA
2815 # (with two rounds) gives a different result from a singly-rounded FMA.
2816
2817 # tuples (a, b, c, expected)
2818 test_values = [
2819 ('0x1.694adde428b44p-1', '0x1.371b0d64caed7p-1',
2820 '0x1.f347e7b8deab8p-4', '0x1.19f10da56c8adp-1'),
2821 ('0x1.605401ccc6ad6p-2', '0x1.ce3a40bf56640p-2',
2822 '0x1.96e3bf7bf2e20p-2', '0x1.1af6d8aa83101p-1'),
2823 ('0x1.e5abd653a67d4p-2', '0x1.a2e400209b3e6p-1',
2824 '0x1.a90051422ce13p-1', '0x1.37d68cc8c0fbbp+0'),
2825 ('0x1.f94e8efd54700p-2', '0x1.123065c812cebp-1',
2826 '0x1.458f86fb6ccd0p-1', '0x1.ccdcee26a3ff3p-1'),
2827 ('0x1.bd926f1eedc96p-1', '0x1.eee9ca68c5740p-1',
2828 '0x1.960c703eb3298p-2', '0x1.3cdcfb4fdb007p+0'),
2829 ('0x1.27348350fbccdp-1', '0x1.3b073914a53f1p-1',
2830 '0x1.e300da5c2b4cbp-1', '0x1.4c51e9a3c4e29p+0'),
2831 ('0x1.2774f00b3497bp-1', '0x1.7038ec336bff0p-2',
2832 '0x1.2f6f2ccc3576bp-1', '0x1.99ad9f9c2688bp-1'),
2833 ('0x1.51d5a99300e5cp-1', '0x1.5cd74abd445a1p-1',
2834 '0x1.8880ab0bbe530p-1', '0x1.3756f96b91129p+0'),
2835 ('0x1.73cb965b821b8p-2', '0x1.218fd3d8d5371p-1',
2836 '0x1.d1ea966a1f758p-2', '0x1.5217b8fd90119p-1'),
2837 ('0x1.4aa98e890b046p-1', '0x1.954d85dff1041p-1',
2838 '0x1.122b59317ebdfp-1', '0x1.0bf644b340cc5p+0'),
2839 ('0x1.e28f29e44750fp-1', '0x1.4bcc4fdcd18fep-1',
2840 '0x1.fd47f81298259p-1', '0x1.9b000afbc9995p+0'),
2841 ('0x1.d2e850717fe78p-3', '0x1.1dd7531c303afp-1',
2842 '0x1.e0869746a2fc2p-2', '0x1.316df6eb26439p-1'),
2843 ('0x1.cf89c75ee6fbap-2', '0x1.b23decdc66825p-1',
2844 '0x1.3d1fe76ac6168p-1', '0x1.00d8ea4c12abbp+0'),
2845 ('0x1.3265ae6f05572p-2', '0x1.16d7ec285f7a2p-1',
2846 '0x1.0b8405b3827fbp-1', '0x1.5ef33c118a001p-1'),
2847 ('0x1.c4d1bf55ec1a5p-1', '0x1.bc59618459e12p-2',
2848 '0x1.ce5b73dc1773dp-1', '0x1.496cf6164f99bp+0'),
2849 ('0x1.d350026ac3946p-1', '0x1.9a234e149a68cp-2',
2850 '0x1.f5467b1911fd6p-2', '0x1.b5cee3225caa5p-1'),
2851 ]
2852 for a_hex, b_hex, c_hex, expected_hex in test_values:
2853 with self.subTest(a_hex=a_hex, b_hex=b_hex, c_hex=c_hex,
2854 expected_hex=expected_hex):
2855 a = float.fromhex(a_hex)
2856 b = float.fromhex(b_hex)
2857 c = float.fromhex(c_hex)
2858 expected = float.fromhex(expected_hex)
2859 self.assertEqual(math.fma(a, b, c), expected)
2860 self.assertEqual(math.fma(b, a, c), expected)
2861
2862 # Custom assertions.
2863 def assertIsNaN(self, value):
2864 self.assertTrue(
2865 math.isnan(value),
2866 msg="Expected a NaN, got {!r}".format(value)
2867 )
2868
2869 def assertIsPositiveZero(self, value):
2870 self.assertTrue(
2871 value == 0 and math.copysign(1, value) > 0,
2872 msg="Expected a positive zero, got {!r}".format(value)
2873 )
2874
2875 def assertIsNegativeZero(self, value):
2876 self.assertTrue(
2877 value == 0 and math.copysign(1, value) < 0,
2878 msg="Expected a negative zero, got {!r}".format(value)
2879 )
2880
2881
2882 def load_tests(loader, tests, pattern):
2883 from doctest import DocFileSuite
2884 tests.addTest(DocFileSuite(os.path.join("mathdata", "ieee754.txt")))
2885 return tests
2886
2887 if __name__ == '__main__':
2888 unittest.main()