1 from test
.test_support
import TestFailed
, vereq
2 from random
import random
4 # These tests ensure that complex math does the right thing; tests of
5 # the complex() function/constructor are in test_b1.py.
7 # XXX need many, many more tests here.
11 def check_close_real(x
, y
, eps
=1e-9):
12 """Return true iff floats x and y "are close\""""
13 # put the one with larger magnitude second
20 # check that relative difference < eps
21 return abs((x-y)/y) < eps
23 def check_close(x, y, eps=1e-9):
24 """Return true iff complexes x
and y
"are close\""""
25 return check_close_real(x
.real
, y
.real
, eps
) and \
26 check_close_real(x
.imag
, y
.imag
, eps
)
29 """Compute complex z=x*y, and check that z/x==y and z/y==x."""
34 if not check_close(q
, y
):
36 print "%r / %r == %r but expected %r" % (z
, x
, q
, y
)
39 if not check_close(q
, x
):
41 print "%r / %r == %r but expected %r" % (z
, y
, q
, x
)
43 simple_real
= [float(i
) for i
in range(-5, 6)]
44 simple_complex
= [complex(x
, y
) for x
in simple_real
for y
in simple_real
]
45 for x
in simple_complex
:
46 for y
in simple_complex
:
49 # A naive complex division algorithm (such as in 2.0) is very prone to
50 # nonsense errors for these (overflows and underflows).
51 test_div(complex(1e200
, 1e200
), 1+0j
)
52 test_div(complex(1e-200, 1e-200), 1+0j
)
56 test_div(complex(random(), random()),
57 complex(random(), random()))
60 if not complex(random() + 1e-6, random() + 1e-6):
61 raise TestFailed("complex(random(), random()) should be true")
64 raise TestFailed("complex(0.0, 0.0) should be false")
66 vereq(complex(5.3, 9.8).conjugate(), 5.3-9.8j
)
73 raise TestFailed("int(complex()) didn't raise TypeError")
80 raise TestFailed("float(complex()) didn't raise TypeError")
84 except ZeroDivisionError:
88 raise TestFailed("Division by complex 0 didn't raise ZeroDivisionError")
91 raise TestFailed("%d tests failed" % nerrors
)