1 import unittest 2 from test import test_support 3 4 from random import random 5 from math import atan2, isnan, copysign 6 7 INF = float("inf") 8 NAN = float("nan") 9 # These tests ensure that complex math does the right thing 10 11 class ComplexTest(unittest.TestCase): 12 13 def assertAlmostEqual(self, a, b): 14 if isinstance(a, complex): 15 if isinstance(b, complex): 16 unittest.TestCase.assertAlmostEqual(self, a.real, b.real) 17 unittest.TestCase.assertAlmostEqual(self, a.imag, b.imag) 18 else: 19 unittest.TestCase.assertAlmostEqual(self, a.real, b) 20 unittest.TestCase.assertAlmostEqual(self, a.imag, 0.) 21 else: 22 if isinstance(b, complex): 23 unittest.TestCase.assertAlmostEqual(self, a, b.real) 24 unittest.TestCase.assertAlmostEqual(self, 0., b.imag) 25 else: 26 unittest.TestCase.assertAlmostEqual(self, a, b) 27 28 def assertCloseAbs(self, x, y, eps=1e-9): 29 """Return true iff floats x and y "are close\"""" 30 # put the one with larger magnitude second 31 if abs(x) > abs(y): 32 x, y = y, x 33 if y == 0: 34 return abs(x) < eps 35 if x == 0: 36 return abs(y) < eps 37 # check that relative difference < eps 38 self.assertTrue(abs((x-y)/y) < eps) 39 40 def assertFloatsAreIdentical(self, x, y): 41 """assert that floats x and y are identical, in the sense that: 42 (1) both x and y are nans, or 43 (2) both x and y are infinities, with the same sign, or 44 (3) both x and y are zeros, with the same sign, or 45 (4) x and y are both finite and nonzero, and x == y 46 47 """ 48 msg = 'floats {!r} and {!r} are not identical' 49 50 if isnan(x) or isnan(y): 51 if isnan(x) and isnan(y): 52 return 53 elif x == y: 54 if x != 0.0: 55 return 56 # both zero; check that signs match 57 elif copysign(1.0, x) == copysign(1.0, y): 58 return 59 else: 60 msg += ': zeros have different signs' 61 self.fail(msg.format(x, y)) 62 63 def assertClose(self, x, y, eps=1e-9): 64 """Return true iff complexes x and y "are close\"""" 65 self.assertCloseAbs(x.real, y.real, eps) 66 self.assertCloseAbs(x.imag, y.imag, eps) 67 68 def check_div(self, x, y): 69 """Compute complex z=x*y, and check that z/x==y and z/y==x.""" 70 z = x * y 71 if x != 0: 72 q = z / x 73 self.assertClose(q, y) 74 q = z.__div__(x) 75 self.assertClose(q, y) 76 q = z.__truediv__(x) 77 self.assertClose(q, y) 78 if y != 0: 79 q = z / y 80 self.assertClose(q, x) 81 q = z.__div__(y) 82 self.assertClose(q, x) 83 q = z.__truediv__(y) 84 self.assertClose(q, x) 85 86 def test_div(self): 87 simple_real = [float(i) for i in xrange(-5, 6)] 88 simple_complex = [complex(x, y) for x in simple_real for y in simple_real] 89 for x in simple_complex: 90 for y in simple_complex: 91 self.check_div(x, y) 92 93 # A naive complex division algorithm (such as in 2.0) is very prone to 94 # nonsense errors for these (overflows and underflows). 95 self.check_div(complex(1e200, 1e200), 1+0j) 96 self.check_div(complex(1e-200, 1e-200), 1+0j) 97 98 # Just for fun. 99 for i in xrange(100): 100 self.check_div(complex(random(), random()), 101 complex(random(), random())) 102 103 self.assertRaises(ZeroDivisionError, complex.__div__, 1+1j, 0+0j) 104 # FIXME: The following currently crashes on Alpha 105 # self.assertRaises(OverflowError, pow, 1e200+1j, 1e200+1j) 106 107 def test_truediv(self): 108 self.assertAlmostEqual(complex.__truediv__(2+0j, 1+1j), 1-1j) 109 self.assertRaises(ZeroDivisionError, complex.__truediv__, 1+1j, 0+0j) 110 111 def test_floordiv(self): 112 self.assertAlmostEqual(complex.__floordiv__(3+0j, 1.5+0j), 2) 113 self.assertRaises(ZeroDivisionError, complex.__floordiv__, 3+0j, 0+0j) 114 115 def test_coerce(self): 116 self.assertRaises(OverflowError, complex.__coerce__, 1+1j, 1L<<10000) 117 118 def test_no_implicit_coerce(self): 119 # Python 2.7 removed implicit coercion from the complex type 120 class A(object): 121 def __coerce__(self, other): 122 raise RuntimeError 123 __hash__ = None 124 def __cmp__(self, other): 125 return -1 126 127 a = A() 128 self.assertRaises(TypeError, lambda: a + 2.0j) 129 self.assertTrue(a < 2.0j) 130 131 def test_richcompare(self): 132 self.assertEqual(complex.__eq__(1+1j, 1L<<10000), False) 133 self.assertEqual(complex.__lt__(1+1j, None), NotImplemented) 134 self.assertIs(complex.__eq__(1+1j, 1+1j), True) 135 self.assertIs(complex.__eq__(1+1j, 2+2j), False) 136 self.assertIs(complex.__ne__(1+1j, 1+1j), False) 137 self.assertIs(complex.__ne__(1+1j, 2+2j), True) 138 self.assertRaises(TypeError, complex.__lt__, 1+1j, 2+2j) 139 self.assertRaises(TypeError, complex.__le__, 1+1j, 2+2j) 140 self.assertRaises(TypeError, complex.__gt__, 1+1j, 2+2j) 141 self.assertRaises(TypeError, complex.__ge__, 1+1j, 2+2j) 142 143 def test_richcompare_boundaries(self): 144 def check(n, deltas, is_equal, imag = 0.0): 145 for delta in deltas: 146 i = n + delta 147 z = complex(i, imag) 148 self.assertIs(complex.__eq__(z, i), is_equal(delta)) 149 self.assertIs(complex.__ne__(z, i), not is_equal(delta)) 150 # For IEEE-754 doubles the following should hold: 151 # x in [2 ** (52 + i), 2 ** (53 + i + 1)] -> x mod 2 ** i == 0 152 # where the interval is representable, of course. 153 for i in range(1, 10): 154 pow = 52 + i 155 mult = 2 ** i 156 check(2 ** pow, range(1, 101), lambda delta: delta % mult == 0) 157 check(2 ** pow, range(1, 101), lambda delta: False, float(i)) 158 check(2 ** 53, range(-100, 0), lambda delta: True) 159 160 def test_mod(self): 161 self.assertRaises(ZeroDivisionError, (1+1j).__mod__, 0+0j) 162 163 a = 3.33+4.43j 164 try: 165 a % 0 166 except ZeroDivisionError: 167 pass 168 else: 169 self.fail("modulo parama can't be 0") 170 171 def test_divmod(self): 172 self.assertRaises(ZeroDivisionError, divmod, 1+1j, 0+0j) 173 174 def test_pow(self): 175 self.assertAlmostEqual(pow(1+1j, 0+0j), 1.0) 176 self.assertAlmostEqual(pow(0+0j, 2+0j), 0.0) 177 self.assertRaises(ZeroDivisionError, pow, 0+0j, 1j) 178 self.assertAlmostEqual(pow(1j, -1), 1/1j) 179 self.assertAlmostEqual(pow(1j, 200), 1) 180 self.assertRaises(ValueError, pow, 1+1j, 1+1j, 1+1j) 181 182 a = 3.33+4.43j 183 self.assertEqual(a ** 0j, 1) 184 self.assertEqual(a ** 0.+0.j, 1) 185 186 self.assertEqual(3j ** 0j, 1) 187 self.assertEqual(3j ** 0, 1) 188 189 try: 190 0j ** a 191 except ZeroDivisionError: 192 pass 193 else: 194 self.fail("should fail 0.0 to negative or complex power") 195 196 try: 197 0j ** (3-2j) 198 except ZeroDivisionError: 199 pass 200 else: 201 self.fail("should fail 0.0 to negative or complex power") 202 203 # The following is used to exercise certain code paths 204 self.assertEqual(a ** 105, a ** 105) 205 self.assertEqual(a ** -105, a ** -105) 206 self.assertEqual(a ** -30, a ** -30) 207 208 self.assertEqual(0.0j ** 0, 1) 209 210 b = 5.1+2.3j 211 self.assertRaises(ValueError, pow, a, b, 0) 212 213 def test_boolcontext(self): 214 for i in xrange(100): 215 self.assertTrue(complex(random() + 1e-6, random() + 1e-6)) 216 self.assertTrue(not complex(0.0, 0.0)) 217 218 def test_conjugate(self): 219 self.assertClose(complex(5.3, 9.8).conjugate(), 5.3-9.8j) 220 221 def test_constructor(self): 222 class OS: 223 def __init__(self, value): self.value = value 224 def __complex__(self): return self.value 225 class NS(object): 226 def __init__(self, value): self.value = value 227 def __complex__(self): return self.value 228 self.assertEqual(complex(OS(1+10j)), 1+10j) 229 self.assertEqual(complex(NS(1+10j)), 1+10j) 230 self.assertRaises(TypeError, complex, OS(None)) 231 self.assertRaises(TypeError, complex, NS(None)) 232 233 self.assertAlmostEqual(complex("1+10j"), 1+10j) 234 self.assertAlmostEqual(complex(10), 10+0j) 235 self.assertAlmostEqual(complex(10.0), 10+0j) 236 self.assertAlmostEqual(complex(10L), 10+0j) 237 self.assertAlmostEqual(complex(10+0j), 10+0j) 238 self.assertAlmostEqual(complex(1,10), 1+10j) 239 self.assertAlmostEqual(complex(1,10L), 1+10j) 240 self.assertAlmostEqual(complex(1,10.0), 1+10j) 241 self.assertAlmostEqual(complex(1L,10), 1+10j) 242 self.assertAlmostEqual(complex(1L,10L), 1+10j) 243 self.assertAlmostEqual(complex(1L,10.0), 1+10j) 244 self.assertAlmostEqual(complex(1.0,10), 1+10j) 245 self.assertAlmostEqual(complex(1.0,10L), 1+10j) 246 self.assertAlmostEqual(complex(1.0,10.0), 1+10j) 247 self.assertAlmostEqual(complex(3.14+0j), 3.14+0j) 248 self.assertAlmostEqual(complex(3.14), 3.14+0j) 249 self.assertAlmostEqual(complex(314), 314.0+0j) 250 self.assertAlmostEqual(complex(314L), 314.0+0j) 251 self.assertAlmostEqual(complex(3.14+0j, 0j), 3.14+0j) 252 self.assertAlmostEqual(complex(3.14, 0.0), 3.14+0j) 253 self.assertAlmostEqual(complex(314, 0), 314.0+0j) 254 self.assertAlmostEqual(complex(314L, 0L), 314.0+0j) 255 self.assertAlmostEqual(complex(0j, 3.14j), -3.14+0j) 256 self.assertAlmostEqual(complex(0.0, 3.14j), -3.14+0j) 257 self.assertAlmostEqual(complex(0j, 3.14), 3.14j) 258 self.assertAlmostEqual(complex(0.0, 3.14), 3.14j) 259 self.assertAlmostEqual(complex("1"), 1+0j) 260 self.assertAlmostEqual(complex("1j"), 1j) 261 self.assertAlmostEqual(complex(), 0) 262 self.assertAlmostEqual(complex("-1"), -1) 263 self.assertAlmostEqual(complex("+1"), +1) 264 self.assertAlmostEqual(complex("(1+2j)"), 1+2j) 265 self.assertAlmostEqual(complex("(1.3+2.2j)"), 1.3+2.2j) 266 self.assertAlmostEqual(complex("3.14+1J"), 3.14+1j) 267 self.assertAlmostEqual(complex(" ( +3.14-6J )"), 3.14-6j) 268 self.assertAlmostEqual(complex(" ( +3.14-J )"), 3.14-1j) 269 self.assertAlmostEqual(complex(" ( +3.14+j )"), 3.14+1j) 270 self.assertAlmostEqual(complex("J"), 1j) 271 self.assertAlmostEqual(complex("( j )"), 1j) 272 self.assertAlmostEqual(complex("+J"), 1j) 273 self.assertAlmostEqual(complex("( -j)"), -1j) 274 self.assertAlmostEqual(complex('1e-500'), 0.0 + 0.0j) 275 self.assertAlmostEqual(complex('-1e-500j'), 0.0 - 0.0j) 276 self.assertAlmostEqual(complex('-1e-500+1e-500j'), -0.0 + 0.0j) 277 278 class complex2(complex): pass 279 self.assertAlmostEqual(complex(complex2(1+1j)), 1+1j) 280 self.assertAlmostEqual(complex(real=17, imag=23), 17+23j) 281 self.assertAlmostEqual(complex(real=17+23j), 17+23j) 282 self.assertAlmostEqual(complex(real=17+23j, imag=23), 17+46j) 283 self.assertAlmostEqual(complex(real=1+2j, imag=3+4j), -3+5j) 284 285 # check that the sign of a zero in the real or imaginary part 286 # is preserved when constructing from two floats. (These checks 287 # are harmless on systems without support for signed zeros.) 288 def split_zeros(x): 289 """Function that produces different results for 0. and -0.""" 290 return atan2(x, -1.) 291 292 self.assertEqual(split_zeros(complex(1., 0.).imag), split_zeros(0.)) 293 self.assertEqual(split_zeros(complex(1., -0.).imag), split_zeros(-0.)) 294 self.assertEqual(split_zeros(complex(0., 1.).real), split_zeros(0.)) 295 self.assertEqual(split_zeros(complex(-0., 1.).real), split_zeros(-0.)) 296 297 c = 3.14 + 1j 298 self.assertTrue(complex(c) is c) 299 del c 300 301 self.assertRaises(TypeError, complex, "1", "1") 302 self.assertRaises(TypeError, complex, 1, "1") 303 304 if test_support.have_unicode: 305 self.assertEqual(complex(unicode(" 3.14+J ")), 3.14+1j) 306 307 # SF bug 543840: complex(string) accepts strings with \0 308 # Fixed in 2.3. 309 self.assertRaises(ValueError, complex, '1+1j\0j') 310 311 self.assertRaises(TypeError, int, 5+3j) 312 self.assertRaises(TypeError, long, 5+3j) 313 self.assertRaises(TypeError, float, 5+3j) 314 self.assertRaises(ValueError, complex, "") 315 self.assertRaises(TypeError, complex, None) 316 self.assertRaises(ValueError, complex, "\0") 317 self.assertRaises(ValueError, complex, "3\09") 318 self.assertRaises(TypeError, complex, "1", "2") 319 self.assertRaises(TypeError, complex, "1", 42) 320 self.assertRaises(TypeError, complex, 1, "2") 321 self.assertRaises(ValueError, complex, "1+") 322 self.assertRaises(ValueError, complex, "1+1j+1j") 323 self.assertRaises(ValueError, complex, "--") 324 self.assertRaises(ValueError, complex, "(1+2j") 325 self.assertRaises(ValueError, complex, "1+2j)") 326 self.assertRaises(ValueError, complex, "1+(2j)") 327 self.assertRaises(ValueError, complex, "(1+2j)123") 328 if test_support.have_unicode: 329 self.assertRaises(ValueError, complex, unicode("x")) 330 self.assertRaises(ValueError, complex, "1j+2") 331 self.assertRaises(ValueError, complex, "1e1ej") 332 self.assertRaises(ValueError, complex, "1e++1ej") 333 self.assertRaises(ValueError, complex, ")1+2j(") 334 # the following three are accepted by Python 2.6 335 self.assertRaises(ValueError, complex, "1..1j") 336 self.assertRaises(ValueError, complex, "1.11.1j") 337 self.assertRaises(ValueError, complex, "1e1.1j") 338 339 if test_support.have_unicode: 340 # check that complex accepts long unicode strings 341 self.assertEqual(type(complex(unicode("1"*500))), complex) 342 343 class EvilExc(Exception): 344 pass 345 346 class evilcomplex: 347 def __complex__(self): 348 raise EvilExc 349 350 self.assertRaises(EvilExc, complex, evilcomplex()) 351 352 class float2: 353 def __init__(self, value): 354 self.value = value 355 def __float__(self): 356 return self.value 357 358 self.assertAlmostEqual(complex(float2(42.)), 42) 359 self.assertAlmostEqual(complex(real=float2(17.), imag=float2(23.)), 17+23j) 360 self.assertRaises(TypeError, complex, float2(None)) 361 362 class complex0(complex): 363 """Test usage of __complex__() when inheriting from 'complex'""" 364 def __complex__(self): 365 return 42j 366 367 class complex1(complex): 368 """Test usage of __complex__() with a __new__() method""" 369 def __new__(self, value=0j): 370 return complex.__new__(self, 2*value) 371 def __complex__(self): 372 return self 373 374 class complex2(complex): 375 """Make sure that __complex__() calls fail if anything other than a 376 complex is returned""" 377 def __complex__(self): 378 return None 379 380 self.assertAlmostEqual(complex(complex0(1j)), 42j) 381 self.assertAlmostEqual(complex(complex1(1j)), 2j) 382 self.assertRaises(TypeError, complex, complex2(1j)) 383 384 def test_subclass(self): 385 class xcomplex(complex): 386 def __add__(self,other): 387 return xcomplex(complex(self) + other) 388 __radd__ = __add__ 389 390 def __sub__(self,other): 391 return xcomplex(complex(self) + other) 392 __rsub__ = __sub__ 393 394 def __mul__(self,other): 395 return xcomplex(complex(self) * other) 396 __rmul__ = __mul__ 397 398 def __div__(self,other): 399 return xcomplex(complex(self) / other) 400 401 def __rdiv__(self,other): 402 return xcomplex(other / complex(self)) 403 404 __truediv__ = __div__ 405 __rtruediv__ = __rdiv__ 406 407 def __floordiv__(self,other): 408 return xcomplex(complex(self) // other) 409 410 def __rfloordiv__(self,other): 411 return xcomplex(other // complex(self)) 412 413 def __pow__(self,other): 414 return xcomplex(complex(self) ** other) 415 416 def __rpow__(self,other): 417 return xcomplex(other ** complex(self) ) 418 419 def __mod__(self,other): 420 return xcomplex(complex(self) % other) 421 422 def __rmod__(self,other): 423 return xcomplex(other % complex(self)) 424 425 infix_binops = ('+', '-', '*', '**', '%', '//', '/') 426 xcomplex_values = (xcomplex(1), xcomplex(123.0), 427 xcomplex(-10+2j), xcomplex(3+187j), 428 xcomplex(3-78j)) 429 test_values = (1, 123.0, 10-19j, xcomplex(1+2j), 430 xcomplex(1+87j), xcomplex(10+90j)) 431 432 for op in infix_binops: 433 for x in xcomplex_values: 434 for y in test_values: 435 a = 'x %s y' % op 436 b = 'y %s x' % op 437 self.assertTrue(type(eval(a)) is type(eval(b)) is xcomplex) 438 439 def test_hash(self): 440 for x in xrange(-30, 30): 441 self.assertEqual(hash(x), hash(complex(x, 0))) 442 x /= 3.0 # now check against floating point 443 self.assertEqual(hash(x), hash(complex(x, 0.))) 444 445 def test_abs(self): 446 nums = [complex(x/3., y/7.) for x in xrange(-9,9) for y in xrange(-9,9)] 447 for num in nums: 448 self.assertAlmostEqual((num.real**2 + num.imag**2) ** 0.5, abs(num)) 449 450 def test_repr(self): 451 self.assertEqual(repr(1+6j), '(1+6j)') 452 self.assertEqual(repr(1-6j), '(1-6j)') 453 454 self.assertNotEqual(repr(-(1+0j)), '(-1+-0j)') 455 456 self.assertEqual(1-6j,complex(repr(1-6j))) 457 self.assertEqual(1+6j,complex(repr(1+6j))) 458 self.assertEqual(-6j,complex(repr(-6j))) 459 self.assertEqual(6j,complex(repr(6j))) 460 461 self.assertEqual(repr(complex(1., INF)), "(1+infj)") 462 self.assertEqual(repr(complex(1., -INF)), "(1-infj)") 463 self.assertEqual(repr(complex(INF, 1)), "(inf+1j)") 464 self.assertEqual(repr(complex(-INF, INF)), "(-inf+infj)") 465 self.assertEqual(repr(complex(NAN, 1)), "(nan+1j)") 466 self.assertEqual(repr(complex(1, NAN)), "(1+nanj)") 467 self.assertEqual(repr(complex(NAN, NAN)), "(nan+nanj)") 468 469 self.assertEqual(repr(complex(0, INF)), "infj") 470 self.assertEqual(repr(complex(0, -INF)), "-infj") 471 self.assertEqual(repr(complex(0, NAN)), "nanj") 472 473 def test_neg(self): 474 self.assertEqual(-(1+6j), -1-6j) 475 476 def test_file(self): 477 a = 3.33+4.43j 478 b = 5.1+2.3j 479 480 fo = None 481 try: 482 fo = open(test_support.TESTFN, "wb") 483 print >>fo, a, b 484 fo.close() 485 fo = open(test_support.TESTFN, "rb") 486 self.assertEqual(fo.read(), "%s %s\n" % (a, b)) 487 finally: 488 if (fo is not None) and (not fo.closed): 489 fo.close() 490 test_support.unlink(test_support.TESTFN) 491 492 def test_getnewargs(self): 493 self.assertEqual((1+2j).__getnewargs__(), (1.0, 2.0)) 494 self.assertEqual((1-2j).__getnewargs__(), (1.0, -2.0)) 495 self.assertEqual((2j).__getnewargs__(), (0.0, 2.0)) 496 self.assertEqual((-0j).__getnewargs__(), (0.0, -0.0)) 497 self.assertEqual(complex(0, INF).__getnewargs__(), (0.0, INF)) 498 self.assertEqual(complex(INF, 0).__getnewargs__(), (INF, 0.0)) 499 500 if float.__getformat__("double").startswith("IEEE"): 501 def test_plus_minus_0j(self): 502 # test that -0j and 0j literals are not identified 503 z1, z2 = 0j, -0j 504 self.assertEqual(atan2(z1.imag, -1.), atan2(0., -1.)) 505 self.assertEqual(atan2(z2.imag, -1.), atan2(-0., -1.)) 506 507 @unittest.skipUnless(float.__getformat__("double").startswith("IEEE"), 508 "test requires IEEE 754 doubles") 509 def test_overflow(self): 510 self.assertEqual(complex("1e500"), complex(INF, 0.0)) 511 self.assertEqual(complex("-1e500j"), complex(0.0, -INF)) 512 self.assertEqual(complex("-1e500+1.8e308j"), complex(-INF, INF)) 513 514 @unittest.skipUnless(float.__getformat__("double").startswith("IEEE"), 515 "test requires IEEE 754 doubles") 516 def test_repr_roundtrip(self): 517 vals = [0.0, 1e-500, 1e-315, 1e-200, 0.0123, 3.1415, 1e50, INF, NAN] 518 vals += [-v for v in vals] 519 520 # complex(repr(z)) should recover z exactly, even for complex 521 # numbers involving an infinity, nan, or negative zero 522 for x in vals: 523 for y in vals: 524 z = complex(x, y) 525 roundtrip = complex(repr(z)) 526 self.assertFloatsAreIdentical(z.real, roundtrip.real) 527 self.assertFloatsAreIdentical(z.imag, roundtrip.imag) 528 529 # if we predefine some constants, then eval(repr(z)) should 530 # also work, except that it might change the sign of zeros 531 inf, nan = float('inf'), float('nan') 532 infj, nanj = complex(0.0, inf), complex(0.0, nan) 533 for x in vals: 534 for y in vals: 535 z = complex(x, y) 536 roundtrip = eval(repr(z)) 537 # adding 0.0 has no effect beside changing -0.0 to 0.0 538 self.assertFloatsAreIdentical(0.0 + z.real, 539 0.0 + roundtrip.real) 540 self.assertFloatsAreIdentical(0.0 + z.imag, 541 0.0 + roundtrip.imag) 542 543 def test_format(self): 544 # empty format string is same as str() 545 self.assertEqual(format(1+3j, ''), str(1+3j)) 546 self.assertEqual(format(1.5+3.5j, ''), str(1.5+3.5j)) 547 self.assertEqual(format(3j, ''), str(3j)) 548 self.assertEqual(format(3.2j, ''), str(3.2j)) 549 self.assertEqual(format(3+0j, ''), str(3+0j)) 550 self.assertEqual(format(3.2+0j, ''), str(3.2+0j)) 551 552 # empty presentation type should still be analogous to str, 553 # even when format string is nonempty (issue #5920). 554 self.assertEqual(format(3.2+0j, '-'), str(3.2+0j)) 555 self.assertEqual(format(3.2+0j, '<'), str(3.2+0j)) 556 z = 4/7. - 100j/7. 557 self.assertEqual(format(z, ''), str(z)) 558 self.assertEqual(format(z, '-'), str(z)) 559 self.assertEqual(format(z, '<'), str(z)) 560 self.assertEqual(format(z, '10'), str(z)) 561 z = complex(0.0, 3.0) 562 self.assertEqual(format(z, ''), str(z)) 563 self.assertEqual(format(z, '-'), str(z)) 564 self.assertEqual(format(z, '<'), str(z)) 565 self.assertEqual(format(z, '2'), str(z)) 566 z = complex(-0.0, 2.0) 567 self.assertEqual(format(z, ''), str(z)) 568 self.assertEqual(format(z, '-'), str(z)) 569 self.assertEqual(format(z, '<'), str(z)) 570 self.assertEqual(format(z, '3'), str(z)) 571 572 self.assertEqual(format(1+3j, 'g'), '1+3j') 573 self.assertEqual(format(3j, 'g'), '0+3j') 574 self.assertEqual(format(1.5+3.5j, 'g'), '1.5+3.5j') 575 576 self.assertEqual(format(1.5+3.5j, '+g'), '+1.5+3.5j') 577 self.assertEqual(format(1.5-3.5j, '+g'), '+1.5-3.5j') 578 self.assertEqual(format(1.5-3.5j, '-g'), '1.5-3.5j') 579 self.assertEqual(format(1.5+3.5j, ' g'), ' 1.5+3.5j') 580 self.assertEqual(format(1.5-3.5j, ' g'), ' 1.5-3.5j') 581 self.assertEqual(format(-1.5+3.5j, ' g'), '-1.5+3.5j') 582 self.assertEqual(format(-1.5-3.5j, ' g'), '-1.5-3.5j') 583 584 self.assertEqual(format(-1.5-3.5e-20j, 'g'), '-1.5-3.5e-20j') 585 self.assertEqual(format(-1.5-3.5j, 'f'), '-1.500000-3.500000j') 586 self.assertEqual(format(-1.5-3.5j, 'F'), '-1.500000-3.500000j') 587 self.assertEqual(format(-1.5-3.5j, 'e'), '-1.500000e+00-3.500000e+00j') 588 self.assertEqual(format(-1.5-3.5j, '.2e'), '-1.50e+00-3.50e+00j') 589 self.assertEqual(format(-1.5-3.5j, '.2E'), '-1.50E+00-3.50E+00j') 590 self.assertEqual(format(-1.5e10-3.5e5j, '.2G'), '-1.5E+10-3.5E+05j') 591 592 self.assertEqual(format(1.5+3j, '<20g'), '1.5+3j ') 593 self.assertEqual(format(1.5+3j, '*<20g'), '1.5+3j**************') 594 self.assertEqual(format(1.5+3j, '>20g'), ' 1.5+3j') 595 self.assertEqual(format(1.5+3j, '^20g'), ' 1.5+3j ') 596 self.assertEqual(format(1.5+3j, '<20'), '(1.5+3j) ') 597 self.assertEqual(format(1.5+3j, '>20'), ' (1.5+3j)') 598 self.assertEqual(format(1.5+3j, '^20'), ' (1.5+3j) ') 599 self.assertEqual(format(1.123-3.123j, '^20.2'), ' (1.1-3.1j) ') 600 601 self.assertEqual(format(1.5+3j, '20.2f'), ' 1.50+3.00j') 602 self.assertEqual(format(1.5+3j, '>20.2f'), ' 1.50+3.00j') 603 self.assertEqual(format(1.5+3j, '<20.2f'), '1.50+3.00j ') 604 self.assertEqual(format(1.5e20+3j, '<20.2f'), '150000000000000000000.00+3.00j') 605 self.assertEqual(format(1.5e20+3j, '>40.2f'), ' 150000000000000000000.00+3.00j') 606 self.assertEqual(format(1.5e20+3j, '^40,.2f'), ' 150,000,000,000,000,000,000.00+3.00j ') 607 self.assertEqual(format(1.5e21+3j, '^40,.2f'), ' 1,500,000,000,000,000,000,000.00+3.00j ') 608 self.assertEqual(format(1.5e21+3000j, ',.2f'), '1,500,000,000,000,000,000,000.00+3,000.00j') 609 610 # alternate is invalid 611 self.assertRaises(ValueError, (1.5+0.5j).__format__, '#f') 612 613 # zero padding is invalid 614 self.assertRaises(ValueError, (1.5+0.5j).__format__, '010f') 615 616 # '=' alignment is invalid 617 self.assertRaises(ValueError, (1.5+3j).__format__, '=20') 618 619 # integer presentation types are an error 620 for t in 'bcdoxX': 621 self.assertRaises(ValueError, (1.5+0.5j).__format__, t) 622 623 # make sure everything works in ''.format() 624 self.assertEqual('*{0:.3f}*'.format(3.14159+2.71828j), '*3.142+2.718j*') 625 626 # issue 3382: 'f' and 'F' with inf's and nan's 627 self.assertEqual('{0:f}'.format(INF+0j), 'inf+0.000000j') 628 self.assertEqual('{0:F}'.format(INF+0j), 'INF+0.000000j') 629 self.assertEqual('{0:f}'.format(-INF+0j), '-inf+0.000000j') 630 self.assertEqual('{0:F}'.format(-INF+0j), '-INF+0.000000j') 631 self.assertEqual('{0:f}'.format(complex(INF, INF)), 'inf+infj') 632 self.assertEqual('{0:F}'.format(complex(INF, INF)), 'INF+INFj') 633 self.assertEqual('{0:f}'.format(complex(INF, -INF)), 'inf-infj') 634 self.assertEqual('{0:F}'.format(complex(INF, -INF)), 'INF-INFj') 635 self.assertEqual('{0:f}'.format(complex(-INF, INF)), '-inf+infj') 636 self.assertEqual('{0:F}'.format(complex(-INF, INF)), '-INF+INFj') 637 self.assertEqual('{0:f}'.format(complex(-INF, -INF)), '-inf-infj') 638 self.assertEqual('{0:F}'.format(complex(-INF, -INF)), '-INF-INFj') 639 640 self.assertEqual('{0:f}'.format(complex(NAN, 0)), 'nan+0.000000j') 641 self.assertEqual('{0:F}'.format(complex(NAN, 0)), 'NAN+0.000000j') 642 self.assertEqual('{0:f}'.format(complex(NAN, NAN)), 'nan+nanj') 643 self.assertEqual('{0:F}'.format(complex(NAN, NAN)), 'NAN+NANj') 644 645 def test_main(): 646 with test_support.check_warnings(("complex divmod.., // and % are " 647 "deprecated", DeprecationWarning)): 648 test_support.run_unittest(ComplexTest) 649 650 if __name__ == "__main__": 651 test_main() 652