blob: 1f884e52a2c9c4a5c074ccce6ee0fdefee8be1c8 [file] [log] [blame]
Antoine Pitroua72f0cd2015-06-23 14:38:13 +02001from test.support import requires_IEEE_754, cpython_only
Eric Smith3ab08ca2010-12-04 15:17:38 +00002from test.test_math import parse_testfile, test_file
Tal Einatd5519ed2015-05-31 22:05:00 +03003import test.test_math as test_math
Guido van Rossumd8faa362007-04-27 19:54:29 +00004import unittest
Raymond Hettingerb67ad7e2004-06-14 07:40:10 +00005import cmath, math
Christian Heimes53876d92008-04-19 00:31:39 +00006from cmath import phase, polar, rect, pi
Victor Stinnerbe3da382010-11-07 14:14:27 +00007import sysconfig
Christian Heimes53876d92008-04-19 00:31:39 +00008
9INF = float('inf')
10NAN = float('nan')
11
12complex_zeros = [complex(x, y) for x in [0.0, -0.0] for y in [0.0, -0.0]]
13complex_infinities = [complex(x, y) for x, y in [
14 (INF, 0.0), # 1st quadrant
15 (INF, 2.3),
16 (INF, INF),
17 (2.3, INF),
18 (0.0, INF),
19 (-0.0, INF), # 2nd quadrant
20 (-2.3, INF),
21 (-INF, INF),
22 (-INF, 2.3),
23 (-INF, 0.0),
24 (-INF, -0.0), # 3rd quadrant
25 (-INF, -2.3),
26 (-INF, -INF),
27 (-2.3, -INF),
28 (-0.0, -INF),
29 (0.0, -INF), # 4th quadrant
30 (2.3, -INF),
31 (INF, -INF),
32 (INF, -2.3),
33 (INF, -0.0)
34 ]]
35complex_nans = [complex(x, y) for x, y in [
36 (NAN, -INF),
37 (NAN, -2.3),
38 (NAN, -0.0),
39 (NAN, 0.0),
40 (NAN, 2.3),
41 (NAN, INF),
42 (-INF, NAN),
43 (-2.3, NAN),
44 (-0.0, NAN),
45 (0.0, NAN),
46 (2.3, NAN),
47 (INF, NAN)
48 ]]
49
Guido van Rossumd8faa362007-04-27 19:54:29 +000050class CMathTests(unittest.TestCase):
51 # list of all functions in cmath
52 test_functions = [getattr(cmath, fname) for fname in [
53 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh',
54 'cos', 'cosh', 'exp', 'log', 'log10', 'sin', 'sinh',
55 'sqrt', 'tan', 'tanh']]
56 # test first and second arguments independently for 2-argument log
57 test_functions.append(lambda x : cmath.log(x, 1729. + 0j))
58 test_functions.append(lambda x : cmath.log(14.-27j, x))
Raymond Hettingerb67ad7e2004-06-14 07:40:10 +000059
Christian Heimes53876d92008-04-19 00:31:39 +000060 def setUp(self):
61 self.test_values = open(test_file)
62
63 def tearDown(self):
64 self.test_values.close()
65
Mark Dickinsona837aa62010-11-07 15:31:41 +000066 def assertFloatIdentical(self, x, y):
67 """Fail unless floats x and y are identical, in the sense that:
68 (1) both x and y are nans, or
69 (2) both x and y are infinities, with the same sign, or
70 (3) both x and y are zeros, with the same sign, or
71 (4) x and y are both finite and nonzero, and x == y
72
73 """
74 msg = 'floats {!r} and {!r} are not identical'
75
76 if math.isnan(x) or math.isnan(y):
77 if math.isnan(x) and math.isnan(y):
78 return
79 elif x == y:
80 if x != 0.0:
81 return
82 # both zero; check that signs match
83 elif math.copysign(1.0, x) == math.copysign(1.0, y):
84 return
85 else:
86 msg += ': zeros have different signs'
87 self.fail(msg.format(x, y))
88
89 def assertComplexIdentical(self, x, y):
90 """Fail unless complex numbers x and y have equal values and signs.
91
92 In particular, if x and y both have real (or imaginary) part
93 zero, but the zeros have different signs, this test will fail.
94
95 """
96 self.assertFloatIdentical(x.real, y.real)
97 self.assertFloatIdentical(x.imag, y.imag)
Victor Stinnerbe3da382010-11-07 14:14:27 +000098
Mark Dickinson4d1e50d2009-12-20 20:37:56 +000099 def rAssertAlmostEqual(self, a, b, rel_err = 2e-15, abs_err = 5e-323,
100 msg=None):
101 """Fail if the two floating-point numbers are not almost equal.
102
103 Determine whether floating-point values a and b are equal to within
104 a (small) rounding error. The default values for rel_err and
105 abs_err are chosen to be suitable for platforms where a float is
106 represented by an IEEE 754 double. They allow an error of between
107 9 and 19 ulps.
108 """
Christian Heimes53876d92008-04-19 00:31:39 +0000109
110 # special values testing
111 if math.isnan(a):
112 if math.isnan(b):
113 return
Mark Dickinson4d1e50d2009-12-20 20:37:56 +0000114 self.fail(msg or '{!r} should be nan'.format(b))
Christian Heimes53876d92008-04-19 00:31:39 +0000115
116 if math.isinf(a):
117 if a == b:
118 return
Mark Dickinson4d1e50d2009-12-20 20:37:56 +0000119 self.fail(msg or 'finite result where infinity expected: '
120 'expected {!r}, got {!r}'.format(a, b))
Christian Heimes53876d92008-04-19 00:31:39 +0000121
Mark Dickinson4d1e50d2009-12-20 20:37:56 +0000122 # if both a and b are zero, check whether they have the same sign
123 # (in theory there are examples where it would be legitimate for a
124 # and b to have opposite signs; in practice these hardly ever
125 # occur).
Christian Heimes53876d92008-04-19 00:31:39 +0000126 if not a and not b:
Mark Dickinson4d1e50d2009-12-20 20:37:56 +0000127 if math.copysign(1., a) != math.copysign(1., b):
128 self.fail(msg or 'zero has wrong sign: expected {!r}, '
129 'got {!r}'.format(a, b))
Christian Heimes53876d92008-04-19 00:31:39 +0000130
Mark Dickinson4d1e50d2009-12-20 20:37:56 +0000131 # if a-b overflows, or b is infinite, return False. Again, in
132 # theory there are examples where a is within a few ulps of the
133 # max representable float, and then b could legitimately be
134 # infinite. In practice these examples are rare.
Christian Heimes53876d92008-04-19 00:31:39 +0000135 try:
136 absolute_error = abs(b-a)
137 except OverflowError:
138 pass
139 else:
Mark Dickinson4d1e50d2009-12-20 20:37:56 +0000140 # test passes if either the absolute error or the relative
141 # error is sufficiently small. The defaults amount to an
142 # error of between 9 ulps and 19 ulps on an IEEE-754 compliant
143 # machine.
Christian Heimes53876d92008-04-19 00:31:39 +0000144 if absolute_error <= max(abs_err, rel_err * abs(a)):
145 return
Mark Dickinson4d1e50d2009-12-20 20:37:56 +0000146 self.fail(msg or
147 '{!r} and {!r} are not sufficiently close'.format(a, b))
Raymond Hettingerb67ad7e2004-06-14 07:40:10 +0000148
Guido van Rossumd8faa362007-04-27 19:54:29 +0000149 def test_constants(self):
150 e_expected = 2.71828182845904523536
151 pi_expected = 3.14159265358979323846
Mark Dickinsonda892452009-12-20 19:56:09 +0000152 self.assertAlmostEqual(cmath.pi, pi_expected, places=9,
Mark Dickinson4d1e50d2009-12-20 20:37:56 +0000153 msg="cmath.pi is {}; should be {}".format(cmath.pi, pi_expected))
Mark Dickinsonda892452009-12-20 19:56:09 +0000154 self.assertAlmostEqual(cmath.e, e_expected, places=9,
Mark Dickinson4d1e50d2009-12-20 20:37:56 +0000155 msg="cmath.e is {}; should be {}".format(cmath.e, e_expected))
Roger E. Masse3daddda1996-12-09 22:59:15 +0000156
Guido van Rossumd8faa362007-04-27 19:54:29 +0000157 def test_user_object(self):
158 # Test automatic calling of __complex__ and __float__ by cmath
159 # functions
Roger E. Massefab8ab81996-12-20 22:36:52 +0000160
Guido van Rossumd8faa362007-04-27 19:54:29 +0000161 # some random values to use as test values; we avoid values
162 # for which any of the functions in cmath is undefined
163 # (i.e. 0., 1., -1., 1j, -1j) or would cause overflow
164 cx_arg = 4.419414439 + 1.497100113j
165 flt_arg = -6.131677725
Roger E. Massefab8ab81996-12-20 22:36:52 +0000166
Guido van Rossumd8faa362007-04-27 19:54:29 +0000167 # a variety of non-complex numbers, used to check that
168 # non-complex return values from __complex__ give an error
169 non_complexes = ["not complex", 1, 5, 2., None,
170 object(), NotImplemented]
171
172 # Now we introduce a variety of classes whose instances might
173 # end up being passed to the cmath functions
174
175 # usual case: new-style class implementing __complex__
176 class MyComplex(object):
177 def __init__(self, value):
178 self.value = value
179 def __complex__(self):
180 return self.value
181
182 # old-style class implementing __complex__
183 class MyComplexOS:
184 def __init__(self, value):
185 self.value = value
186 def __complex__(self):
187 return self.value
188
189 # classes for which __complex__ raises an exception
190 class SomeException(Exception):
191 pass
192 class MyComplexException(object):
193 def __complex__(self):
194 raise SomeException
195 class MyComplexExceptionOS:
196 def __complex__(self):
197 raise SomeException
198
199 # some classes not providing __float__ or __complex__
200 class NeitherComplexNorFloat(object):
201 pass
202 class NeitherComplexNorFloatOS:
203 pass
204 class MyInt(object):
205 def __int__(self): return 2
Guido van Rossumd8faa362007-04-27 19:54:29 +0000206 def __index__(self): return 2
207 class MyIntOS:
208 def __int__(self): return 2
Guido van Rossumd8faa362007-04-27 19:54:29 +0000209 def __index__(self): return 2
210
211 # other possible combinations of __float__ and __complex__
212 # that should work
213 class FloatAndComplex(object):
214 def __float__(self):
215 return flt_arg
216 def __complex__(self):
217 return cx_arg
218 class FloatAndComplexOS:
219 def __float__(self):
220 return flt_arg
221 def __complex__(self):
222 return cx_arg
223 class JustFloat(object):
224 def __float__(self):
225 return flt_arg
226 class JustFloatOS:
227 def __float__(self):
228 return flt_arg
229
230 for f in self.test_functions:
231 # usual usage
Christian Heimes53876d92008-04-19 00:31:39 +0000232 self.assertEqual(f(MyComplex(cx_arg)), f(cx_arg))
233 self.assertEqual(f(MyComplexOS(cx_arg)), f(cx_arg))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000234 # other combinations of __float__ and __complex__
Christian Heimes53876d92008-04-19 00:31:39 +0000235 self.assertEqual(f(FloatAndComplex()), f(cx_arg))
236 self.assertEqual(f(FloatAndComplexOS()), f(cx_arg))
237 self.assertEqual(f(JustFloat()), f(flt_arg))
238 self.assertEqual(f(JustFloatOS()), f(flt_arg))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000239 # TypeError should be raised for classes not providing
240 # either __complex__ or __float__, even if they provide
Mark Dickinsoncce2f212009-01-15 19:32:23 +0000241 # __int__ or __index__. An old-style class
Guido van Rossumd8faa362007-04-27 19:54:29 +0000242 # currently raises AttributeError instead of a TypeError;
243 # this could be considered a bug.
244 self.assertRaises(TypeError, f, NeitherComplexNorFloat())
245 self.assertRaises(TypeError, f, MyInt())
246 self.assertRaises(Exception, f, NeitherComplexNorFloatOS())
247 self.assertRaises(Exception, f, MyIntOS())
248 # non-complex return value from __complex__ -> TypeError
249 for bad_complex in non_complexes:
250 self.assertRaises(TypeError, f, MyComplex(bad_complex))
251 self.assertRaises(TypeError, f, MyComplexOS(bad_complex))
252 # exceptions in __complex__ should be propagated correctly
253 self.assertRaises(SomeException, f, MyComplexException())
254 self.assertRaises(SomeException, f, MyComplexExceptionOS())
255
256 def test_input_type(self):
Serhiy Storchaka95949422013-08-27 19:40:23 +0300257 # ints should be acceptable inputs to all cmath
Guido van Rossumd8faa362007-04-27 19:54:29 +0000258 # functions, by virtue of providing a __float__ method
259 for f in self.test_functions:
260 for arg in [2, 2.]:
Christian Heimes53876d92008-04-19 00:31:39 +0000261 self.assertEqual(f(arg), f(arg.__float__()))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000262
263 # but strings should give a TypeError
264 for f in self.test_functions:
265 for arg in ["a", "long_string", "0", "1j", ""]:
266 self.assertRaises(TypeError, f, arg)
267
268 def test_cmath_matches_math(self):
269 # check that corresponding cmath and math functions are equal
270 # for floats in the appropriate range
271
272 # test_values in (0, 1)
273 test_values = [0.01, 0.1, 0.2, 0.5, 0.9, 0.99]
274
275 # test_values for functions defined on [-1., 1.]
276 unit_interval = test_values + [-x for x in test_values] + \
277 [0., 1., -1.]
278
279 # test_values for log, log10, sqrt
280 positive = test_values + [1.] + [1./x for x in test_values]
281 nonnegative = [0.] + positive
282
283 # test_values for functions defined on the whole real line
284 real_line = [0.] + positive + [-x for x in positive]
285
286 test_functions = {
287 'acos' : unit_interval,
288 'asin' : unit_interval,
289 'atan' : real_line,
290 'cos' : real_line,
291 'cosh' : real_line,
292 'exp' : real_line,
293 'log' : positive,
294 'log10' : positive,
295 'sin' : real_line,
296 'sinh' : real_line,
297 'sqrt' : nonnegative,
298 'tan' : real_line,
299 'tanh' : real_line}
300
301 for fn, values in test_functions.items():
302 float_fn = getattr(math, fn)
303 complex_fn = getattr(cmath, fn)
304 for v in values:
Christian Heimes53876d92008-04-19 00:31:39 +0000305 z = complex_fn(v)
306 self.rAssertAlmostEqual(float_fn(v), z.real)
307 self.assertEqual(0., z.imag)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000308
309 # test two-argument version of log with various bases
310 for base in [0.5, 2., 10.]:
311 for v in positive:
Christian Heimes53876d92008-04-19 00:31:39 +0000312 z = cmath.log(v, base)
313 self.rAssertAlmostEqual(math.log(v, base), z.real)
314 self.assertEqual(0., z.imag)
315
Eric Smith3ab08ca2010-12-04 15:17:38 +0000316 @requires_IEEE_754
Christian Heimes53876d92008-04-19 00:31:39 +0000317 def test_specific_values(self):
Christian Heimes53876d92008-04-19 00:31:39 +0000318 def rect_complex(z):
319 """Wrapped version of rect that accepts a complex number instead of
320 two float arguments."""
321 return cmath.rect(z.real, z.imag)
322
323 def polar_complex(z):
324 """Wrapped version of polar that returns a complex number instead of
325 two floats."""
326 return complex(*polar(z))
327
328 for id, fn, ar, ai, er, ei, flags in parse_testfile(test_file):
329 arg = complex(ar, ai)
330 expected = complex(er, ei)
331 if fn == 'rect':
332 function = rect_complex
333 elif fn == 'polar':
334 function = polar_complex
335 else:
336 function = getattr(cmath, fn)
337 if 'divide-by-zero' in flags or 'invalid' in flags:
338 try:
339 actual = function(arg)
340 except ValueError:
341 continue
342 else:
Mark Dickinson4d1e50d2009-12-20 20:37:56 +0000343 self.fail('ValueError not raised in test '
344 '{}: {}(complex({!r}, {!r}))'.format(id, fn, ar, ai))
Christian Heimes53876d92008-04-19 00:31:39 +0000345
346 if 'overflow' in flags:
347 try:
348 actual = function(arg)
349 except OverflowError:
350 continue
351 else:
Mark Dickinson4d1e50d2009-12-20 20:37:56 +0000352 self.fail('OverflowError not raised in test '
353 '{}: {}(complex({!r}, {!r}))'.format(id, fn, ar, ai))
Christian Heimes53876d92008-04-19 00:31:39 +0000354
355 actual = function(arg)
356
357 if 'ignore-real-sign' in flags:
358 actual = complex(abs(actual.real), actual.imag)
359 expected = complex(abs(expected.real), expected.imag)
360 if 'ignore-imag-sign' in flags:
361 actual = complex(actual.real, abs(actual.imag))
362 expected = complex(expected.real, abs(expected.imag))
363
364 # for the real part of the log function, we allow an
365 # absolute error of up to 2e-15.
366 if fn in ('log', 'log10'):
367 real_abs_err = 2e-15
368 else:
369 real_abs_err = 5e-323
370
Mark Dickinson4d1e50d2009-12-20 20:37:56 +0000371 error_message = (
372 '{}: {}(complex({!r}, {!r}))\n'
373 'Expected: complex({!r}, {!r})\n'
374 'Received: complex({!r}, {!r})\n'
375 'Received value insufficiently close to expected value.'
376 ).format(id, fn, ar, ai,
377 expected.real, expected.imag,
378 actual.real, actual.imag)
379 self.rAssertAlmostEqual(expected.real, actual.real,
380 abs_err=real_abs_err,
381 msg=error_message)
382 self.rAssertAlmostEqual(expected.imag, actual.imag,
383 msg=error_message)
Christian Heimes53876d92008-04-19 00:31:39 +0000384
Antoine Pitrou6bc217d2015-06-23 14:31:11 +0200385 def check_polar(self, func):
386 def check(arg, expected):
387 got = func(arg)
388 for e, g in zip(expected, got):
389 self.rAssertAlmostEqual(e, g)
390 check(0, (0., 0.))
391 check(1, (1., 0.))
392 check(-1, (1., pi))
393 check(1j, (1., pi / 2))
394 check(-3j, (3., -pi / 2))
395 inf = float('inf')
396 check(complex(inf, 0), (inf, 0.))
397 check(complex(-inf, 0), (inf, pi))
398 check(complex(3, inf), (inf, pi / 2))
399 check(complex(5, -inf), (inf, -pi / 2))
400 check(complex(inf, inf), (inf, pi / 4))
401 check(complex(inf, -inf), (inf, -pi / 4))
402 check(complex(-inf, inf), (inf, 3 * pi / 4))
403 check(complex(-inf, -inf), (inf, -3 * pi / 4))
404 nan = float('nan')
405 check(complex(nan, 0), (nan, nan))
406 check(complex(0, nan), (nan, nan))
407 check(complex(nan, nan), (nan, nan))
408 check(complex(inf, nan), (inf, nan))
409 check(complex(-inf, nan), (inf, nan))
410 check(complex(nan, inf), (inf, nan))
411 check(complex(nan, -inf), (inf, nan))
Christian Heimes53876d92008-04-19 00:31:39 +0000412
413 def test_polar(self):
Antoine Pitrou6bc217d2015-06-23 14:31:11 +0200414 self.check_polar(polar)
415
416 @cpython_only
417 def test_polar_errno(self):
418 # Issue #24489: check a previously set C errno doesn't disturb polar()
419 from _testcapi import set_errno
420 def polar_with_errno_set(z):
421 set_errno(11)
422 try:
423 return polar(z)
424 finally:
425 set_errno(0)
426 self.check_polar(polar_with_errno_set)
Christian Heimes53876d92008-04-19 00:31:39 +0000427
428 def test_phase(self):
429 self.assertAlmostEqual(phase(0), 0.)
430 self.assertAlmostEqual(phase(1.), 0.)
431 self.assertAlmostEqual(phase(-1.), pi)
432 self.assertAlmostEqual(phase(-1.+1E-300j), pi)
433 self.assertAlmostEqual(phase(-1.-1E-300j), -pi)
434 self.assertAlmostEqual(phase(1j), pi/2)
435 self.assertAlmostEqual(phase(-1j), -pi/2)
436
437 # zeros
438 self.assertEqual(phase(complex(0.0, 0.0)), 0.0)
439 self.assertEqual(phase(complex(0.0, -0.0)), -0.0)
440 self.assertEqual(phase(complex(-0.0, 0.0)), pi)
441 self.assertEqual(phase(complex(-0.0, -0.0)), -pi)
442
443 # infinities
444 self.assertAlmostEqual(phase(complex(-INF, -0.0)), -pi)
445 self.assertAlmostEqual(phase(complex(-INF, -2.3)), -pi)
446 self.assertAlmostEqual(phase(complex(-INF, -INF)), -0.75*pi)
447 self.assertAlmostEqual(phase(complex(-2.3, -INF)), -pi/2)
448 self.assertAlmostEqual(phase(complex(-0.0, -INF)), -pi/2)
449 self.assertAlmostEqual(phase(complex(0.0, -INF)), -pi/2)
450 self.assertAlmostEqual(phase(complex(2.3, -INF)), -pi/2)
451 self.assertAlmostEqual(phase(complex(INF, -INF)), -pi/4)
452 self.assertEqual(phase(complex(INF, -2.3)), -0.0)
453 self.assertEqual(phase(complex(INF, -0.0)), -0.0)
454 self.assertEqual(phase(complex(INF, 0.0)), 0.0)
455 self.assertEqual(phase(complex(INF, 2.3)), 0.0)
456 self.assertAlmostEqual(phase(complex(INF, INF)), pi/4)
457 self.assertAlmostEqual(phase(complex(2.3, INF)), pi/2)
458 self.assertAlmostEqual(phase(complex(0.0, INF)), pi/2)
459 self.assertAlmostEqual(phase(complex(-0.0, INF)), pi/2)
460 self.assertAlmostEqual(phase(complex(-2.3, INF)), pi/2)
461 self.assertAlmostEqual(phase(complex(-INF, INF)), 0.75*pi)
462 self.assertAlmostEqual(phase(complex(-INF, 2.3)), pi)
463 self.assertAlmostEqual(phase(complex(-INF, 0.0)), pi)
464
465 # real or imaginary part NaN
466 for z in complex_nans:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000467 self.assertTrue(math.isnan(phase(z)))
Christian Heimes53876d92008-04-19 00:31:39 +0000468
469 def test_abs(self):
470 # zeros
471 for z in complex_zeros:
472 self.assertEqual(abs(z), 0.0)
473
474 # infinities
475 for z in complex_infinities:
476 self.assertEqual(abs(z), INF)
477
478 # real or imaginary part NaN
479 self.assertEqual(abs(complex(NAN, -INF)), INF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000480 self.assertTrue(math.isnan(abs(complex(NAN, -2.3))))
481 self.assertTrue(math.isnan(abs(complex(NAN, -0.0))))
482 self.assertTrue(math.isnan(abs(complex(NAN, 0.0))))
483 self.assertTrue(math.isnan(abs(complex(NAN, 2.3))))
Christian Heimes53876d92008-04-19 00:31:39 +0000484 self.assertEqual(abs(complex(NAN, INF)), INF)
485 self.assertEqual(abs(complex(-INF, NAN)), INF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000486 self.assertTrue(math.isnan(abs(complex(-2.3, NAN))))
487 self.assertTrue(math.isnan(abs(complex(-0.0, NAN))))
488 self.assertTrue(math.isnan(abs(complex(0.0, NAN))))
489 self.assertTrue(math.isnan(abs(complex(2.3, NAN))))
Christian Heimes53876d92008-04-19 00:31:39 +0000490 self.assertEqual(abs(complex(INF, NAN)), INF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000491 self.assertTrue(math.isnan(abs(complex(NAN, NAN))))
Christian Heimes53876d92008-04-19 00:31:39 +0000492
Eric Smith3ab08ca2010-12-04 15:17:38 +0000493
494 @requires_IEEE_754
495 def test_abs_overflows(self):
Christian Heimes53876d92008-04-19 00:31:39 +0000496 # result overflows
Eric Smith3ab08ca2010-12-04 15:17:38 +0000497 self.assertRaises(OverflowError, abs, complex(1.4e308, 1.4e308))
Christian Heimes53876d92008-04-19 00:31:39 +0000498
499 def assertCEqual(self, a, b):
500 eps = 1E-7
501 if abs(a.real - b[0]) > eps or abs(a.imag - b[1]) > eps:
502 self.fail((a ,b))
503
504 def test_rect(self):
505 self.assertCEqual(rect(0, 0), (0, 0))
506 self.assertCEqual(rect(1, 0), (1., 0))
507 self.assertCEqual(rect(1, -pi), (-1., 0))
508 self.assertCEqual(rect(1, pi/2), (0, 1.))
509 self.assertCEqual(rect(1, -pi/2), (0, -1.))
510
Mark Dickinson8e0c9962010-07-11 17:38:24 +0000511 def test_isfinite(self):
512 real_vals = [float('-inf'), -2.3, -0.0,
513 0.0, 2.3, float('inf'), float('nan')]
514 for x in real_vals:
515 for y in real_vals:
516 z = complex(x, y)
Mark Dickinson68c5de62010-07-11 19:12:10 +0000517 self.assertEqual(cmath.isfinite(z),
Mark Dickinson8e0c9962010-07-11 17:38:24 +0000518 math.isfinite(x) and math.isfinite(y))
519
Christian Heimes53876d92008-04-19 00:31:39 +0000520 def test_isnan(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000521 self.assertFalse(cmath.isnan(1))
522 self.assertFalse(cmath.isnan(1j))
523 self.assertFalse(cmath.isnan(INF))
524 self.assertTrue(cmath.isnan(NAN))
525 self.assertTrue(cmath.isnan(complex(NAN, 0)))
526 self.assertTrue(cmath.isnan(complex(0, NAN)))
527 self.assertTrue(cmath.isnan(complex(NAN, NAN)))
528 self.assertTrue(cmath.isnan(complex(NAN, INF)))
529 self.assertTrue(cmath.isnan(complex(INF, NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000530
531 def test_isinf(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000532 self.assertFalse(cmath.isinf(1))
533 self.assertFalse(cmath.isinf(1j))
534 self.assertFalse(cmath.isinf(NAN))
535 self.assertTrue(cmath.isinf(INF))
536 self.assertTrue(cmath.isinf(complex(INF, 0)))
537 self.assertTrue(cmath.isinf(complex(0, INF)))
538 self.assertTrue(cmath.isinf(complex(INF, INF)))
539 self.assertTrue(cmath.isinf(complex(NAN, INF)))
540 self.assertTrue(cmath.isinf(complex(INF, NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000541
Victor Stinnerbe3da382010-11-07 14:14:27 +0000542 @requires_IEEE_754
543 @unittest.skipIf(sysconfig.get_config_var('TANH_PRESERVES_ZERO_SIGN') == 0,
544 "system tanh() function doesn't copy the sign")
545 def testTanhSign(self):
Mark Dickinson5ccafba2010-11-13 10:43:40 +0000546 for z in complex_zeros:
547 self.assertComplexIdentical(cmath.tanh(z), z)
Victor Stinnerbe3da382010-11-07 14:14:27 +0000548
Mark Dickinson4ccc1372010-11-20 11:08:27 +0000549 # The algorithm used for atan and atanh makes use of the system
550 # log1p function; If that system function doesn't respect the sign
551 # of zero, then atan and atanh will also have difficulties with
552 # the sign of complex zeros.
553 @requires_IEEE_754
Mark Dickinson4ccc1372010-11-20 11:08:27 +0000554 def testAtanSign(self):
555 for z in complex_zeros:
556 self.assertComplexIdentical(cmath.atan(z), z)
557
558 @requires_IEEE_754
Mark Dickinson4ccc1372010-11-20 11:08:27 +0000559 def testAtanhSign(self):
560 for z in complex_zeros:
561 self.assertComplexIdentical(cmath.atanh(z), z)
562
Guido van Rossumd8faa362007-04-27 19:54:29 +0000563
Tal Einatd5519ed2015-05-31 22:05:00 +0300564class IsCloseTests(test_math.IsCloseTests):
565 isclose = cmath.isclose
566
567 def test_reject_complex_tolerances(self):
568 with self.assertRaises(TypeError):
569 self.isclose(1j, 1j, rel_tol=1j)
570
571 with self.assertRaises(TypeError):
572 self.isclose(1j, 1j, abs_tol=1j)
573
574 with self.assertRaises(TypeError):
575 self.isclose(1j, 1j, rel_tol=1j, abs_tol=1j)
576
577 def test_complex_values(self):
578 # test complex values that are close to within 12 decimal places
579 complex_examples = [(1.0+1.0j, 1.000000000001+1.0j),
580 (1.0+1.0j, 1.0+1.000000000001j),
581 (-1.0+1.0j, -1.000000000001+1.0j),
582 (1.0-1.0j, 1.0-0.999999999999j),
583 ]
584
585 self.assertAllClose(complex_examples, rel_tol=1e-12)
586 self.assertAllNotClose(complex_examples, rel_tol=1e-13)
587
588 def test_complex_near_zero(self):
589 # test values near zero that are near to within three decimal places
590 near_zero_examples = [(0.001j, 0),
591 (0.001, 0),
592 (0.001+0.001j, 0),
593 (-0.001+0.001j, 0),
594 (0.001-0.001j, 0),
595 (-0.001-0.001j, 0),
596 ]
597
598 self.assertAllClose(near_zero_examples, abs_tol=1.5e-03)
599 self.assertAllNotClose(near_zero_examples, abs_tol=0.5e-03)
600
601 self.assertIsClose(0.001-0.001j, 0.001+0.001j, abs_tol=2e-03)
602 self.assertIsNotClose(0.001-0.001j, 0.001+0.001j, abs_tol=1e-03)
603
604
Guido van Rossumd8faa362007-04-27 19:54:29 +0000605if __name__ == "__main__":
Zachary Ware38c707e2015-04-13 15:00:43 -0500606 unittest.main()