New \grammartoken markup, similar to \token but allowed everywhere.
[python/dscho.git] / Lib / test / test_complex.py
blob9faab71d83058fbdea36927404db8cd05cd8442d
1 from test_support import TestFailed
2 from random import random
4 # XXX need many, many more tests here.
6 nerrors = 0
8 def check_close_real(x, y, eps=1e-9):
9 """Return true iff floats x and y "are close\""""
10 # put the one with larger magnitude second
11 if abs(x) > abs(y):
12 x, y = y, x
13 if y == 0:
14 return abs(x) < eps
15 if x == 0:
16 return abs(y) < eps
17 # check that relative difference < eps
18 return abs((x-y)/y) < eps
20 def check_close(x, y, eps=1e-9):
21 """Return true iff complexes x and y "are close\""""
22 return check_close_real(x.real, y.real, eps) and \
23 check_close_real(x.imag, y.imag, eps)
25 def test_div(x, y):
26 """Compute complex z=x*y, and check that z/x==y and z/y==x."""
27 global nerrors
28 z = x * y
29 if x != 0:
30 q = z / x
31 if not check_close(q, y):
32 nerrors += 1
33 print "%r / %r == %r but expected %r" % (z, x, q, y)
34 if y != 0:
35 q = z / y
36 if not check_close(q, x):
37 nerrors += 1
38 print "%r / %r == %r but expected %r" % (z, y, q, x)
40 simple_real = [float(i) for i in range(-5, 6)]
41 simple_complex = [complex(x, y) for x in simple_real for y in simple_real]
42 for x in simple_complex:
43 for y in simple_complex:
44 test_div(x, y)
46 # A naive complex division algorithm (such as in 2.0) is very prone to
47 # nonsense errors for these (overflows and underflows).
48 test_div(complex(1e200, 1e200), 1+0j)
49 test_div(complex(1e-200, 1e-200), 1+0j)
51 # Just for fun.
52 for i in range(100):
53 test_div(complex(random(), random()),
54 complex(random(), random()))
56 try:
57 z = 1.0 / (0+0j)
58 except ZeroDivisionError:
59 pass
60 else:
61 nerrors += 1
62 raise TestFailed("Division by complex 0 didn't raise ZeroDivisionError")
64 if nerrors:
65 raise TestFailed("%d tests failed" % nerrors)