Tim Peters | c5b235c | 2001-09-06 23:00:21 +0000 | [diff] [blame] | 1 | from test_support import TestFailed |
Tim Peters | 0f33604 | 2001-03-18 08:21:57 +0000 | [diff] [blame] | 2 | from random import random |
| 3 | |
| 4 | # XXX need many, many more tests here. |
| 5 | |
| 6 | nerrors = 0 |
| 7 | |
Tim Peters | c5b235c | 2001-09-06 23:00:21 +0000 | [diff] [blame] | 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 |
| 19 | |
| 20 | def check_close(x, y, eps=1e-9): |
Tim Peters | 0f33604 | 2001-03-18 08:21:57 +0000 | [diff] [blame] | 21 | """Return true iff complexes x and y "are close\"""" |
Tim Peters | c5b235c | 2001-09-06 23:00:21 +0000 | [diff] [blame] | 22 | return check_close_real(x.real, y.real, eps) and \ |
| 23 | check_close_real(x.imag, y.imag, eps) |
Tim Peters | 0f33604 | 2001-03-18 08:21:57 +0000 | [diff] [blame] | 24 | |
| 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 |
Tim Peters | 0b76d3a | 2001-05-29 22:18:09 +0000 | [diff] [blame] | 33 | print "%r / %r == %r but expected %r" % (z, x, q, y) |
Tim Peters | 0f33604 | 2001-03-18 08:21:57 +0000 | [diff] [blame] | 34 | if y != 0: |
| 35 | q = z / y |
| 36 | if not check_close(q, x): |
| 37 | nerrors += 1 |
Tim Peters | 0b76d3a | 2001-05-29 22:18:09 +0000 | [diff] [blame] | 38 | print "%r / %r == %r but expected %r" % (z, y, q, x) |
Tim Peters | 0f33604 | 2001-03-18 08:21:57 +0000 | [diff] [blame] | 39 | |
| 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) |
| 45 | |
| 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) |
| 50 | |
| 51 | # Just for fun. |
| 52 | for i in range(100): |
| 53 | test_div(complex(random(), random()), |
| 54 | complex(random(), random())) |
| 55 | |
| 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") |
| 63 | |
| 64 | if nerrors: |
| 65 | raise TestFailed("%d tests failed" % nerrors) |