blob: 0e268ab2d6c047c9674966d16afff711c3a3234f [file] [log] [blame]
Tim Peters419670d2001-09-06 22:07:50 +00001from test_support import TestFailed, fcmp
Tim Peters0f336042001-03-18 08:21:57 +00002from random import random
3
4# XXX need many, many more tests here.
5
6nerrors = 0
7
Tim Peters419670d2001-09-06 22:07:50 +00008def check_close(x, y):
Tim Peters0f336042001-03-18 08:21:57 +00009 """Return true iff complexes x and y "are close\""""
Tim Peters419670d2001-09-06 22:07:50 +000010 return fcmp(x.real, y.real) == 0 == fcmp(x.imag, y.imag)
Tim Peters0f336042001-03-18 08:21:57 +000011
12def test_div(x, y):
13 """Compute complex z=x*y, and check that z/x==y and z/y==x."""
14 global nerrors
15 z = x * y
16 if x != 0:
17 q = z / x
18 if not check_close(q, y):
19 nerrors += 1
Tim Peters0b76d3a2001-05-29 22:18:09 +000020 print "%r / %r == %r but expected %r" % (z, x, q, y)
Tim Peters0f336042001-03-18 08:21:57 +000021 if y != 0:
22 q = z / y
23 if not check_close(q, x):
24 nerrors += 1
Tim Peters0b76d3a2001-05-29 22:18:09 +000025 print "%r / %r == %r but expected %r" % (z, y, q, x)
Tim Peters0f336042001-03-18 08:21:57 +000026
27simple_real = [float(i) for i in range(-5, 6)]
28simple_complex = [complex(x, y) for x in simple_real for y in simple_real]
29for x in simple_complex:
30 for y in simple_complex:
31 test_div(x, y)
32
33# A naive complex division algorithm (such as in 2.0) is very prone to
34# nonsense errors for these (overflows and underflows).
35test_div(complex(1e200, 1e200), 1+0j)
36test_div(complex(1e-200, 1e-200), 1+0j)
37
38# Just for fun.
39for i in range(100):
40 test_div(complex(random(), random()),
41 complex(random(), random()))
42
43try:
44 z = 1.0 / (0+0j)
45except ZeroDivisionError:
46 pass
47else:
48 nerrors += 1
49 raise TestFailed("Division by complex 0 didn't raise ZeroDivisionError")
50
51if nerrors:
52 raise TestFailed("%d tests failed" % nerrors)