ยปCore Development>Code coverage>Lib/test/test_complex.py

Python code coverage for Lib/test/test_complex.py

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