blob: 6b34ddc0a68a6813110b0790841e6a1409d52c90 [file] [log] [blame]
Florent Xicluna41fe6152010-04-02 18:52:12 +00001import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002from test import support
Walter Dörwald5edd7852003-06-18 14:26:18 +00003
Tim Peters0f336042001-03-18 08:21:57 +00004from random import random
Mark Dickinsonad476da2009-04-23 19:14:16 +00005from math import atan2, isnan, copysign
Mark Dickinsonf673f0c2010-03-13 09:48:39 +00006import operator
Tim Peters0f336042001-03-18 08:21:57 +00007
Christian Heimesa156e092008-02-16 07:38:31 +00008INF = float("inf")
9NAN = float("nan")
Walter Dörwald5edd7852003-06-18 14:26:18 +000010# These tests ensure that complex math does the right thing
Fred Drake68773e72001-12-13 19:57:53 +000011
Walter Dörwald5edd7852003-06-18 14:26:18 +000012class ComplexTest(unittest.TestCase):
Tim Peters0f336042001-03-18 08:21:57 +000013
Walter Dörwald5edd7852003-06-18 14:26:18 +000014 def assertAlmostEqual(self, a, b):
15 if isinstance(a, complex):
16 if isinstance(b, complex):
17 unittest.TestCase.assertAlmostEqual(self, a.real, b.real)
18 unittest.TestCase.assertAlmostEqual(self, a.imag, b.imag)
19 else:
20 unittest.TestCase.assertAlmostEqual(self, a.real, b)
21 unittest.TestCase.assertAlmostEqual(self, a.imag, 0.)
22 else:
23 if isinstance(b, complex):
24 unittest.TestCase.assertAlmostEqual(self, a, b.real)
25 unittest.TestCase.assertAlmostEqual(self, 0., b.imag)
26 else:
27 unittest.TestCase.assertAlmostEqual(self, a, b)
Tim Peters0f336042001-03-18 08:21:57 +000028
Walter Dörwald5edd7852003-06-18 14:26:18 +000029 def assertCloseAbs(self, x, y, eps=1e-9):
30 """Return true iff floats x and y "are close\""""
31 # put the one with larger magnitude second
32 if abs(x) > abs(y):
33 x, y = y, x
34 if y == 0:
35 return abs(x) < eps
36 if x == 0:
37 return abs(y) < eps
38 # check that relative difference < eps
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000039 self.assertTrue(abs((x-y)/y) < eps)
Tim Petersc5b235c2001-09-06 23:00:21 +000040
Mark Dickinsonad476da2009-04-23 19:14:16 +000041 def assertFloatsAreIdentical(self, x, y):
42 """assert that floats x and y are identical, in the sense that:
43 (1) both x and y are nans, or
44 (2) both x and y are infinities, with the same sign, or
45 (3) both x and y are zeros, with the same sign, or
46 (4) x and y are both finite and nonzero, and x == y
47
48 """
49 msg = 'floats {!r} and {!r} are not identical'
50
51 if isnan(x) or isnan(y):
52 if isnan(x) and isnan(y):
53 return
54 elif x == y:
55 if x != 0.0:
56 return
57 # both zero; check that signs match
58 elif copysign(1.0, x) == copysign(1.0, y):
59 return
60 else:
61 msg += ': zeros have different signs'
62 self.fail(msg.format(x, y))
63
Walter Dörwald5edd7852003-06-18 14:26:18 +000064 def assertClose(self, x, y, eps=1e-9):
65 """Return true iff complexes x and y "are close\""""
66 self.assertCloseAbs(x.real, y.real, eps)
67 self.assertCloseAbs(x.imag, y.imag, eps)
Tim Peters0f336042001-03-18 08:21:57 +000068
Walter Dörwald5edd7852003-06-18 14:26:18 +000069 def check_div(self, x, y):
70 """Compute complex z=x*y, and check that z/x==y and z/y==x."""
71 z = x * y
72 if x != 0:
73 q = z / x
74 self.assertClose(q, y)
Walter Dörwaldb27cca62003-08-05 15:34:34 +000075 q = z.__truediv__(x)
76 self.assertClose(q, y)
Walter Dörwald5edd7852003-06-18 14:26:18 +000077 if y != 0:
78 q = z / y
79 self.assertClose(q, x)
Walter Dörwaldb27cca62003-08-05 15:34:34 +000080 q = z.__truediv__(y)
81 self.assertClose(q, x)
Tim Peters0f336042001-03-18 08:21:57 +000082
Neal Norwitzbcc0db82006-03-24 08:14:36 +000083 def test_truediv(self):
Guido van Rossum805365e2007-05-07 22:24:25 +000084 simple_real = [float(i) for i in range(-5, 6)]
Walter Dörwald5edd7852003-06-18 14:26:18 +000085 simple_complex = [complex(x, y) for x in simple_real for y in simple_real]
86 for x in simple_complex:
87 for y in simple_complex:
88 self.check_div(x, y)
Tim Peters0f336042001-03-18 08:21:57 +000089
Walter Dörwald5edd7852003-06-18 14:26:18 +000090 # A naive complex division algorithm (such as in 2.0) is very prone to
91 # nonsense errors for these (overflows and underflows).
92 self.check_div(complex(1e200, 1e200), 1+0j)
93 self.check_div(complex(1e-200, 1e-200), 1+0j)
Tim Peters0f336042001-03-18 08:21:57 +000094
Walter Dörwald5edd7852003-06-18 14:26:18 +000095 # Just for fun.
Guido van Rossum805365e2007-05-07 22:24:25 +000096 for i in range(100):
Walter Dörwald5edd7852003-06-18 14:26:18 +000097 self.check_div(complex(random(), random()),
98 complex(random(), random()))
Neal Norwitzfc37af82001-12-29 01:02:21 +000099
Neal Norwitzbcc0db82006-03-24 08:14:36 +0000100 self.assertRaises(ZeroDivisionError, complex.__truediv__, 1+1j, 0+0j)
Walter Dörwald5edd7852003-06-18 14:26:18 +0000101 # FIXME: The following currently crashes on Alpha
102 # self.assertRaises(OverflowError, pow, 1e200+1j, 1e200+1j)
Neal Norwitzfc37af82001-12-29 01:02:21 +0000103
Walter Dörwald5edd7852003-06-18 14:26:18 +0000104 def test_truediv(self):
105 self.assertAlmostEqual(complex.__truediv__(2+0j, 1+1j), 1-1j)
106 self.assertRaises(ZeroDivisionError, complex.__truediv__, 1+1j, 0+0j)
Neal Norwitz5a0f0102001-12-29 14:31:46 +0000107
Walter Dörwald5edd7852003-06-18 14:26:18 +0000108 def test_floordiv(self):
Guido van Rossum9648d622007-08-03 20:40:44 +0000109 self.assertRaises(TypeError, complex.__floordiv__, 3+0j, 1.5+0j)
110 self.assertRaises(TypeError, complex.__floordiv__, 3+0j, 0+0j)
Neal Norwitzfc37af82001-12-29 01:02:21 +0000111
Walter Dörwald5edd7852003-06-18 14:26:18 +0000112 def test_richcompare(self):
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000113 self.assertIs(complex.__eq__(1+1j, 1<<10000), False)
Mark Dickinsonf673f0c2010-03-13 09:48:39 +0000114 self.assertIs(complex.__lt__(1+1j, None), NotImplemented)
Walter Dörwald5edd7852003-06-18 14:26:18 +0000115 self.assertIs(complex.__eq__(1+1j, 1+1j), True)
116 self.assertIs(complex.__eq__(1+1j, 2+2j), False)
117 self.assertIs(complex.__ne__(1+1j, 1+1j), False)
118 self.assertIs(complex.__ne__(1+1j, 2+2j), True)
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000119 for i in range(1, 100):
120 f = i / 100.0
121 self.assertIs(complex.__eq__(f+0j, f), True)
122 self.assertIs(complex.__ne__(f+0j, f), False)
123 self.assertIs(complex.__eq__(complex(f, f), f), False)
124 self.assertIs(complex.__ne__(complex(f, f), f), True)
Mark Dickinsonf673f0c2010-03-13 09:48:39 +0000125 self.assertIs(complex.__lt__(1+1j, 2+2j), NotImplemented)
126 self.assertIs(complex.__le__(1+1j, 2+2j), NotImplemented)
127 self.assertIs(complex.__gt__(1+1j, 2+2j), NotImplemented)
128 self.assertIs(complex.__ge__(1+1j, 2+2j), NotImplemented)
129 self.assertRaises(TypeError, operator.lt, 1+1j, 2+2j)
130 self.assertRaises(TypeError, operator.le, 1+1j, 2+2j)
131 self.assertRaises(TypeError, operator.gt, 1+1j, 2+2j)
132 self.assertRaises(TypeError, operator.ge, 1+1j, 2+2j)
133 self.assertIs(operator.eq(1+1j, 1+1j), True)
134 self.assertIs(operator.eq(1+1j, 2+2j), False)
135 self.assertIs(operator.ne(1+1j, 1+1j), False)
136 self.assertIs(operator.ne(1+1j, 2+2j), True)
Tim Peters0f336042001-03-18 08:21:57 +0000137
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000138 def test_richcompare_boundaries(self):
139 def check(n, deltas, is_equal, imag = 0.0):
140 for delta in deltas:
141 i = n + delta
142 z = complex(i, imag)
143 self.assertIs(complex.__eq__(z, i), is_equal(delta))
144 self.assertIs(complex.__ne__(z, i), not is_equal(delta))
145 # For IEEE-754 doubles the following should hold:
146 # x in [2 ** (52 + i), 2 ** (53 + i + 1)] -> x mod 2 ** i == 0
147 # where the interval is representable, of course.
148 for i in range(1, 10):
149 pow = 52 + i
150 mult = 2 ** i
151 check(2 ** pow, range(1, 101), lambda delta: delta % mult == 0)
152 check(2 ** pow, range(1, 101), lambda delta: False, float(i))
153 check(2 ** 53, range(-100, 0), lambda delta: True)
154
Walter Dörwald5edd7852003-06-18 14:26:18 +0000155 def test_mod(self):
Guido van Rossum9648d622007-08-03 20:40:44 +0000156 # % is no longer supported on complex numbers
157 self.assertRaises(TypeError, (1+1j).__mod__, 0+0j)
158 self.assertRaises(TypeError, lambda: (3.33+4.43j) % 0)
Jeffrey Yasskin3404b3c2007-09-07 15:15:49 +0000159 self.assertRaises(TypeError, (1+1j).__mod__, 4.3j)
Walter Dörwaldf393fc62003-07-15 18:47:27 +0000160
Walter Dörwald5edd7852003-06-18 14:26:18 +0000161 def test_divmod(self):
Guido van Rossum9648d622007-08-03 20:40:44 +0000162 self.assertRaises(TypeError, divmod, 1+1j, 1+0j)
163 self.assertRaises(TypeError, divmod, 1+1j, 0+0j)
Walter Dörwald5edd7852003-06-18 14:26:18 +0000164
165 def test_pow(self):
166 self.assertAlmostEqual(pow(1+1j, 0+0j), 1.0)
167 self.assertAlmostEqual(pow(0+0j, 2+0j), 0.0)
168 self.assertRaises(ZeroDivisionError, pow, 0+0j, 1j)
169 self.assertAlmostEqual(pow(1j, -1), 1/1j)
170 self.assertAlmostEqual(pow(1j, 200), 1)
171 self.assertRaises(ValueError, pow, 1+1j, 1+1j, 1+1j)
172
Walter Dörwaldf393fc62003-07-15 18:47:27 +0000173 a = 3.33+4.43j
174 self.assertEqual(a ** 0j, 1)
175 self.assertEqual(a ** 0.+0.j, 1)
176
177 self.assertEqual(3j ** 0j, 1)
178 self.assertEqual(3j ** 0, 1)
179
180 try:
181 0j ** a
182 except ZeroDivisionError:
183 pass
184 else:
185 self.fail("should fail 0.0 to negative or complex power")
186
187 try:
188 0j ** (3-2j)
189 except ZeroDivisionError:
190 pass
191 else:
192 self.fail("should fail 0.0 to negative or complex power")
193
194 # The following is used to exercise certain code paths
195 self.assertEqual(a ** 105, a ** 105)
196 self.assertEqual(a ** -105, a ** -105)
197 self.assertEqual(a ** -30, a ** -30)
198
199 self.assertEqual(0.0j ** 0, 1)
200
201 b = 5.1+2.3j
202 self.assertRaises(ValueError, pow, a, b, 0)
203
Walter Dörwald5edd7852003-06-18 14:26:18 +0000204 def test_boolcontext(self):
Guido van Rossum805365e2007-05-07 22:24:25 +0000205 for i in range(100):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000206 self.assertTrue(complex(random() + 1e-6, random() + 1e-6))
207 self.assertTrue(not complex(0.0, 0.0))
Walter Dörwald5edd7852003-06-18 14:26:18 +0000208
209 def test_conjugate(self):
210 self.assertClose(complex(5.3, 9.8).conjugate(), 5.3-9.8j)
211
212 def test_constructor(self):
213 class OS:
214 def __init__(self, value): self.value = value
215 def __complex__(self): return self.value
216 class NS(object):
217 def __init__(self, value): self.value = value
218 def __complex__(self): return self.value
219 self.assertEqual(complex(OS(1+10j)), 1+10j)
220 self.assertEqual(complex(NS(1+10j)), 1+10j)
221 self.assertRaises(TypeError, complex, OS(None))
222 self.assertRaises(TypeError, complex, NS(None))
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000223 self.assertRaises(TypeError, complex, {})
Walter Dörwald5edd7852003-06-18 14:26:18 +0000224
225 self.assertAlmostEqual(complex("1+10j"), 1+10j)
226 self.assertAlmostEqual(complex(10), 10+0j)
227 self.assertAlmostEqual(complex(10.0), 10+0j)
Guido van Rossume2a383d2007-01-15 16:59:06 +0000228 self.assertAlmostEqual(complex(10), 10+0j)
Walter Dörwald5edd7852003-06-18 14:26:18 +0000229 self.assertAlmostEqual(complex(10+0j), 10+0j)
230 self.assertAlmostEqual(complex(1,10), 1+10j)
Guido van Rossume2a383d2007-01-15 16:59:06 +0000231 self.assertAlmostEqual(complex(1,10), 1+10j)
Walter Dörwald5edd7852003-06-18 14:26:18 +0000232 self.assertAlmostEqual(complex(1,10.0), 1+10j)
Guido van Rossume2a383d2007-01-15 16:59:06 +0000233 self.assertAlmostEqual(complex(1,10), 1+10j)
234 self.assertAlmostEqual(complex(1,10), 1+10j)
235 self.assertAlmostEqual(complex(1,10.0), 1+10j)
Walter Dörwald5edd7852003-06-18 14:26:18 +0000236 self.assertAlmostEqual(complex(1.0,10), 1+10j)
Guido van Rossume2a383d2007-01-15 16:59:06 +0000237 self.assertAlmostEqual(complex(1.0,10), 1+10j)
Walter Dörwald5edd7852003-06-18 14:26:18 +0000238 self.assertAlmostEqual(complex(1.0,10.0), 1+10j)
239 self.assertAlmostEqual(complex(3.14+0j), 3.14+0j)
240 self.assertAlmostEqual(complex(3.14), 3.14+0j)
241 self.assertAlmostEqual(complex(314), 314.0+0j)
Guido van Rossume2a383d2007-01-15 16:59:06 +0000242 self.assertAlmostEqual(complex(314), 314.0+0j)
Walter Dörwald5edd7852003-06-18 14:26:18 +0000243 self.assertAlmostEqual(complex(3.14+0j, 0j), 3.14+0j)
244 self.assertAlmostEqual(complex(3.14, 0.0), 3.14+0j)
245 self.assertAlmostEqual(complex(314, 0), 314.0+0j)
Guido van Rossume2a383d2007-01-15 16:59:06 +0000246 self.assertAlmostEqual(complex(314, 0), 314.0+0j)
Walter Dörwald5edd7852003-06-18 14:26:18 +0000247 self.assertAlmostEqual(complex(0j, 3.14j), -3.14+0j)
248 self.assertAlmostEqual(complex(0.0, 3.14j), -3.14+0j)
249 self.assertAlmostEqual(complex(0j, 3.14), 3.14j)
250 self.assertAlmostEqual(complex(0.0, 3.14), 3.14j)
251 self.assertAlmostEqual(complex("1"), 1+0j)
252 self.assertAlmostEqual(complex("1j"), 1j)
253 self.assertAlmostEqual(complex(), 0)
254 self.assertAlmostEqual(complex("-1"), -1)
255 self.assertAlmostEqual(complex("+1"), +1)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000256 self.assertAlmostEqual(complex("(1+2j)"), 1+2j)
257 self.assertAlmostEqual(complex("(1.3+2.2j)"), 1.3+2.2j)
Mark Dickinsonad476da2009-04-23 19:14:16 +0000258 self.assertAlmostEqual(complex("3.14+1J"), 3.14+1j)
259 self.assertAlmostEqual(complex(" ( +3.14-6J )"), 3.14-6j)
Mark Dickinson6649fa42009-04-24 13:25:20 +0000260 self.assertAlmostEqual(complex(" ( +3.14-J )"), 3.14-1j)
261 self.assertAlmostEqual(complex(" ( +3.14+j )"), 3.14+1j)
262 self.assertAlmostEqual(complex("J"), 1j)
263 self.assertAlmostEqual(complex("( j )"), 1j)
264 self.assertAlmostEqual(complex("+J"), 1j)
265 self.assertAlmostEqual(complex("( -j)"), -1j)
266 self.assertAlmostEqual(complex('1e-500'), 0.0 + 0.0j)
267 self.assertAlmostEqual(complex('-1e-500j'), 0.0 - 0.0j)
268 self.assertAlmostEqual(complex('-1e-500+1e-500j'), -0.0 + 0.0j)
Walter Dörwald5edd7852003-06-18 14:26:18 +0000269
270 class complex2(complex): pass
271 self.assertAlmostEqual(complex(complex2(1+1j)), 1+1j)
272 self.assertAlmostEqual(complex(real=17, imag=23), 17+23j)
273 self.assertAlmostEqual(complex(real=17+23j), 17+23j)
274 self.assertAlmostEqual(complex(real=17+23j, imag=23), 17+46j)
275 self.assertAlmostEqual(complex(real=1+2j, imag=3+4j), -3+5j)
276
Christian Heimes69a79632007-11-28 10:04:30 +0000277 # check that the sign of a zero in the real or imaginary part
278 # is preserved when constructing from two floats. (These checks
279 # are harmless on systems without support for signed zeros.)
280 def split_zeros(x):
281 """Function that produces different results for 0. and -0."""
282 return atan2(x, -1.)
283
284 self.assertEqual(split_zeros(complex(1., 0.).imag), split_zeros(0.))
285 self.assertEqual(split_zeros(complex(1., -0.).imag), split_zeros(-0.))
286 self.assertEqual(split_zeros(complex(0., 1.).real), split_zeros(0.))
287 self.assertEqual(split_zeros(complex(-0., 1.).real), split_zeros(-0.))
288
Walter Dörwald5edd7852003-06-18 14:26:18 +0000289 c = 3.14 + 1j
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000290 self.assertTrue(complex(c) is c)
Walter Dörwald5edd7852003-06-18 14:26:18 +0000291 del c
292
293 self.assertRaises(TypeError, complex, "1", "1")
294 self.assertRaises(TypeError, complex, 1, "1")
295
Walter Dörwald5edd7852003-06-18 14:26:18 +0000296 # SF bug 543840: complex(string) accepts strings with \0
297 # Fixed in 2.3.
298 self.assertRaises(ValueError, complex, '1+1j\0j')
299
300 self.assertRaises(TypeError, int, 5+3j)
Guido van Rossume2a383d2007-01-15 16:59:06 +0000301 self.assertRaises(TypeError, int, 5+3j)
Walter Dörwald5edd7852003-06-18 14:26:18 +0000302 self.assertRaises(TypeError, float, 5+3j)
303 self.assertRaises(ValueError, complex, "")
304 self.assertRaises(TypeError, complex, None)
305 self.assertRaises(ValueError, complex, "\0")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000306 self.assertRaises(ValueError, complex, "3\09")
Walter Dörwald5edd7852003-06-18 14:26:18 +0000307 self.assertRaises(TypeError, complex, "1", "2")
308 self.assertRaises(TypeError, complex, "1", 42)
309 self.assertRaises(TypeError, complex, 1, "2")
310 self.assertRaises(ValueError, complex, "1+")
311 self.assertRaises(ValueError, complex, "1+1j+1j")
312 self.assertRaises(ValueError, complex, "--")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000313 self.assertRaises(ValueError, complex, "(1+2j")
314 self.assertRaises(ValueError, complex, "1+2j)")
315 self.assertRaises(ValueError, complex, "1+(2j)")
316 self.assertRaises(ValueError, complex, "(1+2j)123")
Walter Dörwald1f5947b2007-05-22 16:52:54 +0000317 self.assertRaises(ValueError, complex, "x")
Mark Dickinsonad476da2009-04-23 19:14:16 +0000318 self.assertRaises(ValueError, complex, "1j+2")
319 self.assertRaises(ValueError, complex, "1e1ej")
320 self.assertRaises(ValueError, complex, "1e++1ej")
321 self.assertRaises(ValueError, complex, ")1+2j(")
Mark Dickinson6649fa42009-04-24 13:25:20 +0000322 # the following three are accepted by Python 2.6
323 self.assertRaises(ValueError, complex, "1..1j")
324 self.assertRaises(ValueError, complex, "1.11.1j")
325 self.assertRaises(ValueError, complex, "1e1.1j")
Walter Dörwald5edd7852003-06-18 14:26:18 +0000326
Mark Dickinsonf9724882009-10-26 21:51:18 +0000327 # check that complex accepts long unicode strings
328 self.assertEqual(type(complex("1"*500)), complex)
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000329 # check whitespace processing
330 self.assertEqual(complex('\N{EM SPACE}(\N{EN SPACE}1+1j ) '), 1+1j)
Mark Dickinsonf9724882009-10-26 21:51:18 +0000331
Walter Dörwald5edd7852003-06-18 14:26:18 +0000332 class EvilExc(Exception):
Tim Peters478c1052003-06-29 05:46:54 +0000333 pass
Walter Dörwald5edd7852003-06-18 14:26:18 +0000334
335 class evilcomplex:
336 def __complex__(self):
337 raise EvilExc
338
339 self.assertRaises(EvilExc, complex, evilcomplex())
340
341 class float2:
342 def __init__(self, value):
343 self.value = value
344 def __float__(self):
345 return self.value
346
347 self.assertAlmostEqual(complex(float2(42.)), 42)
348 self.assertAlmostEqual(complex(real=float2(17.), imag=float2(23.)), 17+23j)
349 self.assertRaises(TypeError, complex, float2(None))
350
Brett Cannonc3647ac2005-04-26 03:45:26 +0000351 class complex0(complex):
352 """Test usage of __complex__() when inheriting from 'complex'"""
353 def __complex__(self):
354 return 42j
355
356 class complex1(complex):
357 """Test usage of __complex__() with a __new__() method"""
358 def __new__(self, value=0j):
359 return complex.__new__(self, 2*value)
360 def __complex__(self):
361 return self
362
363 class complex2(complex):
364 """Make sure that __complex__() calls fail if anything other than a
365 complex is returned"""
366 def __complex__(self):
367 return None
368
369 self.assertAlmostEqual(complex(complex0(1j)), 42j)
370 self.assertAlmostEqual(complex(complex1(1j)), 2j)
371 self.assertRaises(TypeError, complex, complex2(1j))
372
Walter Dörwald5edd7852003-06-18 14:26:18 +0000373 def test_hash(self):
Guido van Rossum805365e2007-05-07 22:24:25 +0000374 for x in range(-30, 30):
Walter Dörwald5edd7852003-06-18 14:26:18 +0000375 self.assertEqual(hash(x), hash(complex(x, 0)))
376 x /= 3.0 # now check against floating point
377 self.assertEqual(hash(x), hash(complex(x, 0.)))
378
379 def test_abs(self):
Guido van Rossum805365e2007-05-07 22:24:25 +0000380 nums = [complex(x/3., y/7.) for x in range(-9,9) for y in range(-9,9)]
Walter Dörwald5edd7852003-06-18 14:26:18 +0000381 for num in nums:
382 self.assertAlmostEqual((num.real**2 + num.imag**2) ** 0.5, abs(num))
383
Eric Smith70099a12010-12-04 13:27:34 +0000384 def test_repr_str(self):
385 def test(v, expected, test_fn=self.assertEqual):
386 test_fn(repr(v), expected)
387 test_fn(str(v), expected)
Walter Dörwald5edd7852003-06-18 14:26:18 +0000388
Eric Smith70099a12010-12-04 13:27:34 +0000389 test(1+6j, '(1+6j)')
390 test(1-6j, '(1-6j)')
391
392 test(-(1+0j), '(-1+-0j)', test_fn=self.assertNotEqual)
393
394 test(complex(1., INF), "(1+infj)")
395 test(complex(1., -INF), "(1-infj)")
396 test(complex(INF, 1), "(inf+1j)")
397 test(complex(-INF, INF), "(-inf+infj)")
398 test(complex(NAN, 1), "(nan+1j)")
399 test(complex(1, NAN), "(1+nanj)")
400 test(complex(NAN, NAN), "(nan+nanj)")
401
402 test(complex(0, INF), "infj")
403 test(complex(0, -INF), "-infj")
404 test(complex(0, NAN), "nanj")
Georg Brandl9e281072005-09-17 07:51:15 +0000405
Guido van Rossumd8faa362007-04-27 19:54:29 +0000406 self.assertEqual(1-6j,complex(repr(1-6j)))
407 self.assertEqual(1+6j,complex(repr(1+6j)))
408 self.assertEqual(-6j,complex(repr(-6j)))
409 self.assertEqual(6j,complex(repr(6j)))
410
Eric Smith1ed77f32010-12-04 15:26:13 +0000411 @support.requires_IEEE_754
412 def test_negative_zero_repr_str(self):
413 def test(v, expected, test_fn=self.assertEqual):
414 test_fn(repr(v), expected)
415 test_fn(str(v), expected)
416
417 test(complex(0., 1.), "1j")
418 test(complex(-0., 1.), "(-0+1j)")
419 test(complex(0., -1.), "-1j")
420 test(complex(-0., -1.), "(-0-1j)")
421
422 test(complex(0., 0.), "0j")
423 test(complex(0., -0.), "-0j")
424 test(complex(-0., 0.), "(-0+0j)")
425 test(complex(-0., -0.), "(-0-0j)")
426
Walter Dörwald5edd7852003-06-18 14:26:18 +0000427 def test_neg(self):
428 self.assertEqual(-(1+6j), -1-6j)
429
Walter Dörwaldf393fc62003-07-15 18:47:27 +0000430 def test_file(self):
431 a = 3.33+4.43j
432 b = 5.1+2.3j
433
434 fo = None
435 try:
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000436 fo = open(support.TESTFN, "w")
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000437 print(a, b, file=fo)
Walter Dörwaldf393fc62003-07-15 18:47:27 +0000438 fo.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000439 fo = open(support.TESTFN, "r")
Guido van Rossum09549f42007-08-27 20:40:10 +0000440 self.assertEqual(fo.read(), ("%s %s\n" % (a, b)))
Walter Dörwaldf393fc62003-07-15 18:47:27 +0000441 finally:
442 if (fo is not None) and (not fo.closed):
443 fo.close()
Florent Xicluna41fe6152010-04-02 18:52:12 +0000444 support.unlink(support.TESTFN)
Walter Dörwald5edd7852003-06-18 14:26:18 +0000445
Georg Brandl0c77a822008-06-10 16:37:50 +0000446 def test_getnewargs(self):
447 self.assertEqual((1+2j).__getnewargs__(), (1.0, 2.0))
448 self.assertEqual((1-2j).__getnewargs__(), (1.0, -2.0))
449 self.assertEqual((2j).__getnewargs__(), (0.0, 2.0))
450 self.assertEqual((-0j).__getnewargs__(), (0.0, -0.0))
451 self.assertEqual(complex(0, INF).__getnewargs__(), (0.0, INF))
452 self.assertEqual(complex(INF, 0).__getnewargs__(), (INF, 0.0))
453
Eric Smith3ab08ca2010-12-04 15:17:38 +0000454 @support.requires_IEEE_754
455 def test_plus_minus_0j(self):
456 # test that -0j and 0j literals are not identified
457 z1, z2 = 0j, -0j
458 self.assertEqual(atan2(z1.imag, -1.), atan2(0., -1.))
459 self.assertEqual(atan2(z2.imag, -1.), atan2(-0., -1.))
Christian Heimes400adb02008-02-01 08:12:03 +0000460
Eric Smith3ab08ca2010-12-04 15:17:38 +0000461 @support.requires_IEEE_754
Mark Dickinson50b79a82010-06-30 11:13:36 +0000462 def test_negated_imaginary_literal(self):
463 z0 = -0j
464 z1 = -7j
465 z2 = -1e1000j
466 # Note: In versions of Python < 3.2, a negated imaginary literal
467 # accidentally ended up with real part 0.0 instead of -0.0, thanks to a
468 # modification during CST -> AST translation (see issue #9011). That's
469 # fixed in Python 3.2.
470 self.assertFloatsAreIdentical(z0.real, -0.0)
471 self.assertFloatsAreIdentical(z0.imag, -0.0)
472 self.assertFloatsAreIdentical(z1.real, -0.0)
473 self.assertFloatsAreIdentical(z1.imag, -7.0)
474 self.assertFloatsAreIdentical(z2.real, -0.0)
475 self.assertFloatsAreIdentical(z2.imag, -INF)
476
Eric Smith3ab08ca2010-12-04 15:17:38 +0000477 @support.requires_IEEE_754
Mark Dickinson6b1e43b2009-05-20 18:41:04 +0000478 def test_overflow(self):
479 self.assertEqual(complex("1e500"), complex(INF, 0.0))
480 self.assertEqual(complex("-1e500j"), complex(0.0, -INF))
481 self.assertEqual(complex("-1e500+1.8e308j"), complex(-INF, INF))
482
Eric Smith3ab08ca2010-12-04 15:17:38 +0000483 @support.requires_IEEE_754
Mark Dickinsonad476da2009-04-23 19:14:16 +0000484 def test_repr_roundtrip(self):
Mark Dickinsonde8a7102009-04-25 10:11:40 +0000485 vals = [0.0, 1e-500, 1e-315, 1e-200, 0.0123, 3.1415, 1e50, INF, NAN]
Mark Dickinsonad476da2009-04-23 19:14:16 +0000486 vals += [-v for v in vals]
Mark Dickinsonde8a7102009-04-25 10:11:40 +0000487
488 # complex(repr(z)) should recover z exactly, even for complex
489 # numbers involving an infinity, nan, or negative zero
Mark Dickinsonad476da2009-04-23 19:14:16 +0000490 for x in vals:
491 for y in vals:
492 z = complex(x, y)
493 roundtrip = complex(repr(z))
494 self.assertFloatsAreIdentical(z.real, roundtrip.real)
495 self.assertFloatsAreIdentical(z.imag, roundtrip.imag)
496
Mark Dickinsonde8a7102009-04-25 10:11:40 +0000497 # if we predefine some constants, then eval(repr(z)) should
498 # also work, except that it might change the sign of zeros
499 inf, nan = float('inf'), float('nan')
500 infj, nanj = complex(0.0, inf), complex(0.0, nan)
501 for x in vals:
502 for y in vals:
503 z = complex(x, y)
504 roundtrip = eval(repr(z))
505 # adding 0.0 has no effect beside changing -0.0 to 0.0
506 self.assertFloatsAreIdentical(0.0 + z.real,
507 0.0 + roundtrip.real)
508 self.assertFloatsAreIdentical(0.0 + z.imag,
509 0.0 + roundtrip.imag)
510
Eric Smith58a42242009-04-30 01:00:33 +0000511 def test_format(self):
512 # empty format string is same as str()
513 self.assertEqual(format(1+3j, ''), str(1+3j))
514 self.assertEqual(format(1.5+3.5j, ''), str(1.5+3.5j))
515 self.assertEqual(format(3j, ''), str(3j))
516 self.assertEqual(format(3.2j, ''), str(3.2j))
517 self.assertEqual(format(3+0j, ''), str(3+0j))
518 self.assertEqual(format(3.2+0j, ''), str(3.2+0j))
Mark Dickinsonde8a7102009-04-25 10:11:40 +0000519
Eric Smith63376222009-05-05 14:04:18 +0000520 # empty presentation type should still be analogous to str,
521 # even when format string is nonempty (issue #5920).
522 self.assertEqual(format(3.2+0j, '-'), str(3.2+0j))
523 self.assertEqual(format(3.2+0j, '<'), str(3.2+0j))
524 z = 4/7. - 100j/7.
525 self.assertEqual(format(z, ''), str(z))
526 self.assertEqual(format(z, '-'), str(z))
527 self.assertEqual(format(z, '<'), str(z))
528 self.assertEqual(format(z, '10'), str(z))
Mark Dickinson5b65df72010-08-01 10:41:49 +0000529 z = complex(0.0, 3.0)
530 self.assertEqual(format(z, ''), str(z))
531 self.assertEqual(format(z, '-'), str(z))
532 self.assertEqual(format(z, '<'), str(z))
533 self.assertEqual(format(z, '2'), str(z))
534 z = complex(-0.0, 2.0)
535 self.assertEqual(format(z, ''), str(z))
536 self.assertEqual(format(z, '-'), str(z))
537 self.assertEqual(format(z, '<'), str(z))
538 self.assertEqual(format(z, '3'), str(z))
Eric Smith63376222009-05-05 14:04:18 +0000539
Eric Smith58a42242009-04-30 01:00:33 +0000540 self.assertEqual(format(1+3j, 'g'), '1+3j')
541 self.assertEqual(format(3j, 'g'), '0+3j')
542 self.assertEqual(format(1.5+3.5j, 'g'), '1.5+3.5j')
543
544 self.assertEqual(format(1.5+3.5j, '+g'), '+1.5+3.5j')
545 self.assertEqual(format(1.5-3.5j, '+g'), '+1.5-3.5j')
546 self.assertEqual(format(1.5-3.5j, '-g'), '1.5-3.5j')
547 self.assertEqual(format(1.5+3.5j, ' g'), ' 1.5+3.5j')
548 self.assertEqual(format(1.5-3.5j, ' g'), ' 1.5-3.5j')
549 self.assertEqual(format(-1.5+3.5j, ' g'), '-1.5+3.5j')
550 self.assertEqual(format(-1.5-3.5j, ' g'), '-1.5-3.5j')
551
552 self.assertEqual(format(-1.5-3.5e-20j, 'g'), '-1.5-3.5e-20j')
553 self.assertEqual(format(-1.5-3.5j, 'f'), '-1.500000-3.500000j')
554 self.assertEqual(format(-1.5-3.5j, 'F'), '-1.500000-3.500000j')
555 self.assertEqual(format(-1.5-3.5j, 'e'), '-1.500000e+00-3.500000e+00j')
556 self.assertEqual(format(-1.5-3.5j, '.2e'), '-1.50e+00-3.50e+00j')
557 self.assertEqual(format(-1.5-3.5j, '.2E'), '-1.50E+00-3.50E+00j')
558 self.assertEqual(format(-1.5e10-3.5e5j, '.2G'), '-1.5E+10-3.5E+05j')
559
560 self.assertEqual(format(1.5+3j, '<20g'), '1.5+3j ')
561 self.assertEqual(format(1.5+3j, '*<20g'), '1.5+3j**************')
562 self.assertEqual(format(1.5+3j, '>20g'), ' 1.5+3j')
563 self.assertEqual(format(1.5+3j, '^20g'), ' 1.5+3j ')
564 self.assertEqual(format(1.5+3j, '<20'), '(1.5+3j) ')
565 self.assertEqual(format(1.5+3j, '>20'), ' (1.5+3j)')
566 self.assertEqual(format(1.5+3j, '^20'), ' (1.5+3j) ')
567 self.assertEqual(format(1.123-3.123j, '^20.2'), ' (1.1-3.1j) ')
568
Eric Smith4e260c52010-02-22 18:54:44 +0000569 self.assertEqual(format(1.5+3j, '20.2f'), ' 1.50+3.00j')
570 self.assertEqual(format(1.5+3j, '>20.2f'), ' 1.50+3.00j')
Eric Smith58a42242009-04-30 01:00:33 +0000571 self.assertEqual(format(1.5+3j, '<20.2f'), '1.50+3.00j ')
572 self.assertEqual(format(1.5e20+3j, '<20.2f'), '150000000000000000000.00+3.00j')
573 self.assertEqual(format(1.5e20+3j, '>40.2f'), ' 150000000000000000000.00+3.00j')
574 self.assertEqual(format(1.5e20+3j, '^40,.2f'), ' 150,000,000,000,000,000,000.00+3.00j ')
575 self.assertEqual(format(1.5e21+3j, '^40,.2f'), ' 1,500,000,000,000,000,000,000.00+3.00j ')
576 self.assertEqual(format(1.5e21+3000j, ',.2f'), '1,500,000,000,000,000,000,000.00+3,000.00j')
577
Eric Smith984bb582010-11-25 16:08:06 +0000578 # Issue 7094: Alternate formatting (specified by #)
579 self.assertEqual(format(1+1j, '.0e'), '1e+00+1e+00j')
580 self.assertEqual(format(1+1j, '#.0e'), '1.e+00+1.e+00j')
581 self.assertEqual(format(1+1j, '.0f'), '1+1j')
582 self.assertEqual(format(1+1j, '#.0f'), '1.+1.j')
583 self.assertEqual(format(1.1+1.1j, 'g'), '1.1+1.1j')
584 self.assertEqual(format(1.1+1.1j, '#g'), '1.10000+1.10000j')
585
586 # Alternate doesn't make a difference for these, they format the same with or without it
587 self.assertEqual(format(1+1j, '.1e'), '1.0e+00+1.0e+00j')
588 self.assertEqual(format(1+1j, '#.1e'), '1.0e+00+1.0e+00j')
589 self.assertEqual(format(1+1j, '.1f'), '1.0+1.0j')
590 self.assertEqual(format(1+1j, '#.1f'), '1.0+1.0j')
591
592 # Misc. other alternate tests
593 self.assertEqual(format((-1.5+0.5j), '#f'), '-1.500000+0.500000j')
594 self.assertEqual(format((-1.5+0.5j), '#.0f'), '-2.+0.j')
595 self.assertEqual(format((-1.5+0.5j), '#e'), '-1.500000e+00+5.000000e-01j')
596 self.assertEqual(format((-1.5+0.5j), '#.0e'), '-2.e+00+5.e-01j')
597 self.assertEqual(format((-1.5+0.5j), '#g'), '-1.50000+0.500000j')
598 self.assertEqual(format((-1.5+0.5j), '.0g'), '-2+0.5j')
599 self.assertEqual(format((-1.5+0.5j), '#.0g'), '-2.+0.5j')
Eric Smith58a42242009-04-30 01:00:33 +0000600
601 # zero padding is invalid
602 self.assertRaises(ValueError, (1.5+0.5j).__format__, '010f')
603
604 # '=' alignment is invalid
605 self.assertRaises(ValueError, (1.5+3j).__format__, '=20')
606
607 # integer presentation types are an error
608 for t in 'bcdoxX':
609 self.assertRaises(ValueError, (1.5+0.5j).__format__, t)
610
611 # make sure everything works in ''.format()
612 self.assertEqual('*{0:.3f}*'.format(3.14159+2.71828j), '*3.142+2.718j*')
Mark Dickinsonad476da2009-04-23 19:14:16 +0000613
Eric Smith741191f2009-05-06 13:08:15 +0000614 # issue 3382
615 self.assertEqual(format(complex(NAN, NAN), 'f'), 'nan+nanj')
616 self.assertEqual(format(complex(1, NAN), 'f'), '1.000000+nanj')
617 self.assertEqual(format(complex(NAN, 1), 'f'), 'nan+1.000000j')
618 self.assertEqual(format(complex(NAN, -1), 'f'), 'nan-1.000000j')
619 self.assertEqual(format(complex(NAN, NAN), 'F'), 'NAN+NANj')
620 self.assertEqual(format(complex(1, NAN), 'F'), '1.000000+NANj')
621 self.assertEqual(format(complex(NAN, 1), 'F'), 'NAN+1.000000j')
622 self.assertEqual(format(complex(NAN, -1), 'F'), 'NAN-1.000000j')
623 self.assertEqual(format(complex(INF, INF), 'f'), 'inf+infj')
624 self.assertEqual(format(complex(1, INF), 'f'), '1.000000+infj')
625 self.assertEqual(format(complex(INF, 1), 'f'), 'inf+1.000000j')
626 self.assertEqual(format(complex(INF, -1), 'f'), 'inf-1.000000j')
627 self.assertEqual(format(complex(INF, INF), 'F'), 'INF+INFj')
628 self.assertEqual(format(complex(1, INF), 'F'), '1.000000+INFj')
629 self.assertEqual(format(complex(INF, 1), 'F'), 'INF+1.000000j')
630 self.assertEqual(format(complex(INF, -1), 'F'), 'INF-1.000000j')
631
Walter Dörwald5edd7852003-06-18 14:26:18 +0000632def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000633 support.run_unittest(ComplexTest)
Walter Dörwald5edd7852003-06-18 14:26:18 +0000634
635if __name__ == "__main__":
636 test_main()