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