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