blob: f16fb3bf2e7ffdbd084f225e662bc2a7e501720b [file] [log] [blame]
Tim Petersc5b235c2001-09-06 23:00:21 +00001from test_support import TestFailed
Tim Peters0f336042001-03-18 08:21:57 +00002from random import random
3
Fred Drake68773e72001-12-13 19:57:53 +00004# These tests ensure that complex math does the right thing; tests of
5# the complex() function/constructor are in test_b1.py.
6
Tim Peters0f336042001-03-18 08:21:57 +00007# XXX need many, many more tests here.
8
9nerrors = 0
10
Tim Petersc5b235c2001-09-06 23:00:21 +000011def 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
14 if abs(x) > abs(y):
15 x, y = y, x
16 if y == 0:
17 return abs(x) < eps
18 if x == 0:
19 return abs(y) < eps
20 # check that relative difference < eps
21 return abs((x-y)/y) < eps
22
23def check_close(x, y, eps=1e-9):
Tim Peters0f336042001-03-18 08:21:57 +000024 """Return true iff complexes x and y "are close\""""
Tim Petersc5b235c2001-09-06 23:00:21 +000025 return check_close_real(x.real, y.real, eps) and \
26 check_close_real(x.imag, y.imag, eps)
Tim Peters0f336042001-03-18 08:21:57 +000027
28def test_div(x, y):
29 """Compute complex z=x*y, and check that z/x==y and z/y==x."""
30 global nerrors
31 z = x * y
32 if x != 0:
33 q = z / x
34 if not check_close(q, y):
35 nerrors += 1
Tim Peters0b76d3a2001-05-29 22:18:09 +000036 print "%r / %r == %r but expected %r" % (z, x, q, y)
Tim Peters0f336042001-03-18 08:21:57 +000037 if y != 0:
38 q = z / y
39 if not check_close(q, x):
40 nerrors += 1
Tim Peters0b76d3a2001-05-29 22:18:09 +000041 print "%r / %r == %r but expected %r" % (z, y, q, x)
Tim Peters0f336042001-03-18 08:21:57 +000042
43simple_real = [float(i) for i in range(-5, 6)]
44simple_complex = [complex(x, y) for x in simple_real for y in simple_real]
45for x in simple_complex:
46 for y in simple_complex:
47 test_div(x, y)
48
49# A naive complex division algorithm (such as in 2.0) is very prone to
50# nonsense errors for these (overflows and underflows).
51test_div(complex(1e200, 1e200), 1+0j)
52test_div(complex(1e-200, 1e-200), 1+0j)
53
54# Just for fun.
55for i in range(100):
56 test_div(complex(random(), random()),
57 complex(random(), random()))
58
59try:
60 z = 1.0 / (0+0j)
61except ZeroDivisionError:
62 pass
63else:
64 nerrors += 1
65 raise TestFailed("Division by complex 0 didn't raise ZeroDivisionError")
66
67if nerrors:
68 raise TestFailed("%d tests failed" % nerrors)