Debian Codegraph @

lib-python/3/test/test_math.py

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