blob: 11b0c6120240fc3ec9f941acca4d7b186fb838f9 [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
Mark Dickinson84e63112016-08-29 13:56:58 +0100157 def test_infinity_and_nan_constants(self):
158 self.assertEqual(cmath.inf.real, math.inf)
159 self.assertEqual(cmath.inf.imag, 0.0)
160 self.assertEqual(cmath.infj.real, 0.0)
161 self.assertEqual(cmath.infj.imag, math.inf)
162
163 self.assertTrue(math.isnan(cmath.nan.real))
164 self.assertEqual(cmath.nan.imag, 0.0)
165 self.assertEqual(cmath.nanj.real, 0.0)
166 self.assertTrue(math.isnan(cmath.nanj.imag))
167
168 # Check consistency with reprs.
169 self.assertEqual(repr(cmath.inf), "inf")
170 self.assertEqual(repr(cmath.infj), "infj")
171 self.assertEqual(repr(cmath.nan), "nan")
172 self.assertEqual(repr(cmath.nanj), "nanj")
173
Guido van Rossumd8faa362007-04-27 19:54:29 +0000174 def test_user_object(self):
175 # Test automatic calling of __complex__ and __float__ by cmath
176 # functions
Roger E. Massefab8ab81996-12-20 22:36:52 +0000177
Guido van Rossumd8faa362007-04-27 19:54:29 +0000178 # some random values to use as test values; we avoid values
179 # for which any of the functions in cmath is undefined
180 # (i.e. 0., 1., -1., 1j, -1j) or would cause overflow
181 cx_arg = 4.419414439 + 1.497100113j
182 flt_arg = -6.131677725
Roger E. Massefab8ab81996-12-20 22:36:52 +0000183
Guido van Rossumd8faa362007-04-27 19:54:29 +0000184 # a variety of non-complex numbers, used to check that
185 # non-complex return values from __complex__ give an error
186 non_complexes = ["not complex", 1, 5, 2., None,
187 object(), NotImplemented]
188
189 # Now we introduce a variety of classes whose instances might
190 # end up being passed to the cmath functions
191
192 # usual case: new-style class implementing __complex__
193 class MyComplex(object):
194 def __init__(self, value):
195 self.value = value
196 def __complex__(self):
197 return self.value
198
199 # old-style class implementing __complex__
200 class MyComplexOS:
201 def __init__(self, value):
202 self.value = value
203 def __complex__(self):
204 return self.value
205
206 # classes for which __complex__ raises an exception
207 class SomeException(Exception):
208 pass
209 class MyComplexException(object):
210 def __complex__(self):
211 raise SomeException
212 class MyComplexExceptionOS:
213 def __complex__(self):
214 raise SomeException
215
216 # some classes not providing __float__ or __complex__
217 class NeitherComplexNorFloat(object):
218 pass
219 class NeitherComplexNorFloatOS:
220 pass
221 class MyInt(object):
222 def __int__(self): return 2
Guido van Rossumd8faa362007-04-27 19:54:29 +0000223 def __index__(self): return 2
224 class MyIntOS:
225 def __int__(self): return 2
Guido van Rossumd8faa362007-04-27 19:54:29 +0000226 def __index__(self): return 2
227
228 # other possible combinations of __float__ and __complex__
229 # that should work
230 class FloatAndComplex(object):
231 def __float__(self):
232 return flt_arg
233 def __complex__(self):
234 return cx_arg
235 class FloatAndComplexOS:
236 def __float__(self):
237 return flt_arg
238 def __complex__(self):
239 return cx_arg
240 class JustFloat(object):
241 def __float__(self):
242 return flt_arg
243 class JustFloatOS:
244 def __float__(self):
245 return flt_arg
246
247 for f in self.test_functions:
248 # usual usage
Christian Heimes53876d92008-04-19 00:31:39 +0000249 self.assertEqual(f(MyComplex(cx_arg)), f(cx_arg))
250 self.assertEqual(f(MyComplexOS(cx_arg)), f(cx_arg))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000251 # other combinations of __float__ and __complex__
Christian Heimes53876d92008-04-19 00:31:39 +0000252 self.assertEqual(f(FloatAndComplex()), f(cx_arg))
253 self.assertEqual(f(FloatAndComplexOS()), f(cx_arg))
254 self.assertEqual(f(JustFloat()), f(flt_arg))
255 self.assertEqual(f(JustFloatOS()), f(flt_arg))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000256 # TypeError should be raised for classes not providing
257 # either __complex__ or __float__, even if they provide
Mark Dickinsoncce2f212009-01-15 19:32:23 +0000258 # __int__ or __index__. An old-style class
Guido van Rossumd8faa362007-04-27 19:54:29 +0000259 # currently raises AttributeError instead of a TypeError;
260 # this could be considered a bug.
261 self.assertRaises(TypeError, f, NeitherComplexNorFloat())
262 self.assertRaises(TypeError, f, MyInt())
263 self.assertRaises(Exception, f, NeitherComplexNorFloatOS())
264 self.assertRaises(Exception, f, MyIntOS())
265 # non-complex return value from __complex__ -> TypeError
266 for bad_complex in non_complexes:
267 self.assertRaises(TypeError, f, MyComplex(bad_complex))
268 self.assertRaises(TypeError, f, MyComplexOS(bad_complex))
269 # exceptions in __complex__ should be propagated correctly
270 self.assertRaises(SomeException, f, MyComplexException())
271 self.assertRaises(SomeException, f, MyComplexExceptionOS())
272
273 def test_input_type(self):
Serhiy Storchaka95949422013-08-27 19:40:23 +0300274 # ints should be acceptable inputs to all cmath
Guido van Rossumd8faa362007-04-27 19:54:29 +0000275 # functions, by virtue of providing a __float__ method
276 for f in self.test_functions:
277 for arg in [2, 2.]:
Christian Heimes53876d92008-04-19 00:31:39 +0000278 self.assertEqual(f(arg), f(arg.__float__()))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000279
280 # but strings should give a TypeError
281 for f in self.test_functions:
282 for arg in ["a", "long_string", "0", "1j", ""]:
283 self.assertRaises(TypeError, f, arg)
284
285 def test_cmath_matches_math(self):
286 # check that corresponding cmath and math functions are equal
287 # for floats in the appropriate range
288
289 # test_values in (0, 1)
290 test_values = [0.01, 0.1, 0.2, 0.5, 0.9, 0.99]
291
292 # test_values for functions defined on [-1., 1.]
293 unit_interval = test_values + [-x for x in test_values] + \
294 [0., 1., -1.]
295
296 # test_values for log, log10, sqrt
297 positive = test_values + [1.] + [1./x for x in test_values]
298 nonnegative = [0.] + positive
299
300 # test_values for functions defined on the whole real line
301 real_line = [0.] + positive + [-x for x in positive]
302
303 test_functions = {
304 'acos' : unit_interval,
305 'asin' : unit_interval,
306 'atan' : real_line,
307 'cos' : real_line,
308 'cosh' : real_line,
309 'exp' : real_line,
310 'log' : positive,
311 'log10' : positive,
312 'sin' : real_line,
313 'sinh' : real_line,
314 'sqrt' : nonnegative,
315 'tan' : real_line,
316 'tanh' : real_line}
317
318 for fn, values in test_functions.items():
319 float_fn = getattr(math, fn)
320 complex_fn = getattr(cmath, fn)
321 for v in values:
Christian Heimes53876d92008-04-19 00:31:39 +0000322 z = complex_fn(v)
323 self.rAssertAlmostEqual(float_fn(v), z.real)
324 self.assertEqual(0., z.imag)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000325
326 # test two-argument version of log with various bases
327 for base in [0.5, 2., 10.]:
328 for v in positive:
Christian Heimes53876d92008-04-19 00:31:39 +0000329 z = cmath.log(v, base)
330 self.rAssertAlmostEqual(math.log(v, base), z.real)
331 self.assertEqual(0., z.imag)
332
Eric Smith3ab08ca2010-12-04 15:17:38 +0000333 @requires_IEEE_754
Christian Heimes53876d92008-04-19 00:31:39 +0000334 def test_specific_values(self):
Christian Heimes53876d92008-04-19 00:31:39 +0000335 def rect_complex(z):
336 """Wrapped version of rect that accepts a complex number instead of
337 two float arguments."""
338 return cmath.rect(z.real, z.imag)
339
340 def polar_complex(z):
341 """Wrapped version of polar that returns a complex number instead of
342 two floats."""
343 return complex(*polar(z))
344
345 for id, fn, ar, ai, er, ei, flags in parse_testfile(test_file):
346 arg = complex(ar, ai)
347 expected = complex(er, ei)
348 if fn == 'rect':
349 function = rect_complex
350 elif fn == 'polar':
351 function = polar_complex
352 else:
353 function = getattr(cmath, fn)
354 if 'divide-by-zero' in flags or 'invalid' in flags:
355 try:
356 actual = function(arg)
357 except ValueError:
358 continue
359 else:
Mark Dickinson4d1e50d2009-12-20 20:37:56 +0000360 self.fail('ValueError not raised in test '
361 '{}: {}(complex({!r}, {!r}))'.format(id, fn, ar, ai))
Christian Heimes53876d92008-04-19 00:31:39 +0000362
363 if 'overflow' in flags:
364 try:
365 actual = function(arg)
366 except OverflowError:
367 continue
368 else:
Mark Dickinson4d1e50d2009-12-20 20:37:56 +0000369 self.fail('OverflowError not raised in test '
370 '{}: {}(complex({!r}, {!r}))'.format(id, fn, ar, ai))
Christian Heimes53876d92008-04-19 00:31:39 +0000371
372 actual = function(arg)
373
374 if 'ignore-real-sign' in flags:
375 actual = complex(abs(actual.real), actual.imag)
376 expected = complex(abs(expected.real), expected.imag)
377 if 'ignore-imag-sign' in flags:
378 actual = complex(actual.real, abs(actual.imag))
379 expected = complex(expected.real, abs(expected.imag))
380
381 # for the real part of the log function, we allow an
382 # absolute error of up to 2e-15.
383 if fn in ('log', 'log10'):
384 real_abs_err = 2e-15
385 else:
386 real_abs_err = 5e-323
387
Mark Dickinson4d1e50d2009-12-20 20:37:56 +0000388 error_message = (
389 '{}: {}(complex({!r}, {!r}))\n'
390 'Expected: complex({!r}, {!r})\n'
391 'Received: complex({!r}, {!r})\n'
392 'Received value insufficiently close to expected value.'
393 ).format(id, fn, ar, ai,
394 expected.real, expected.imag,
395 actual.real, actual.imag)
396 self.rAssertAlmostEqual(expected.real, actual.real,
397 abs_err=real_abs_err,
398 msg=error_message)
399 self.rAssertAlmostEqual(expected.imag, actual.imag,
400 msg=error_message)
Christian Heimes53876d92008-04-19 00:31:39 +0000401
Antoine Pitrou6bc217d2015-06-23 14:31:11 +0200402 def check_polar(self, func):
403 def check(arg, expected):
404 got = func(arg)
405 for e, g in zip(expected, got):
406 self.rAssertAlmostEqual(e, g)
407 check(0, (0., 0.))
408 check(1, (1., 0.))
409 check(-1, (1., pi))
410 check(1j, (1., pi / 2))
411 check(-3j, (3., -pi / 2))
412 inf = float('inf')
413 check(complex(inf, 0), (inf, 0.))
414 check(complex(-inf, 0), (inf, pi))
415 check(complex(3, inf), (inf, pi / 2))
416 check(complex(5, -inf), (inf, -pi / 2))
417 check(complex(inf, inf), (inf, pi / 4))
418 check(complex(inf, -inf), (inf, -pi / 4))
419 check(complex(-inf, inf), (inf, 3 * pi / 4))
420 check(complex(-inf, -inf), (inf, -3 * pi / 4))
421 nan = float('nan')
422 check(complex(nan, 0), (nan, nan))
423 check(complex(0, nan), (nan, nan))
424 check(complex(nan, nan), (nan, nan))
425 check(complex(inf, nan), (inf, nan))
426 check(complex(-inf, nan), (inf, nan))
427 check(complex(nan, inf), (inf, nan))
428 check(complex(nan, -inf), (inf, nan))
Christian Heimes53876d92008-04-19 00:31:39 +0000429
430 def test_polar(self):
Antoine Pitrou6bc217d2015-06-23 14:31:11 +0200431 self.check_polar(polar)
432
433 @cpython_only
434 def test_polar_errno(self):
435 # Issue #24489: check a previously set C errno doesn't disturb polar()
436 from _testcapi import set_errno
437 def polar_with_errno_set(z):
438 set_errno(11)
439 try:
440 return polar(z)
441 finally:
442 set_errno(0)
443 self.check_polar(polar_with_errno_set)
Christian Heimes53876d92008-04-19 00:31:39 +0000444
445 def test_phase(self):
446 self.assertAlmostEqual(phase(0), 0.)
447 self.assertAlmostEqual(phase(1.), 0.)
448 self.assertAlmostEqual(phase(-1.), pi)
449 self.assertAlmostEqual(phase(-1.+1E-300j), pi)
450 self.assertAlmostEqual(phase(-1.-1E-300j), -pi)
451 self.assertAlmostEqual(phase(1j), pi/2)
452 self.assertAlmostEqual(phase(-1j), -pi/2)
453
454 # zeros
455 self.assertEqual(phase(complex(0.0, 0.0)), 0.0)
456 self.assertEqual(phase(complex(0.0, -0.0)), -0.0)
457 self.assertEqual(phase(complex(-0.0, 0.0)), pi)
458 self.assertEqual(phase(complex(-0.0, -0.0)), -pi)
459
460 # infinities
461 self.assertAlmostEqual(phase(complex(-INF, -0.0)), -pi)
462 self.assertAlmostEqual(phase(complex(-INF, -2.3)), -pi)
463 self.assertAlmostEqual(phase(complex(-INF, -INF)), -0.75*pi)
464 self.assertAlmostEqual(phase(complex(-2.3, -INF)), -pi/2)
465 self.assertAlmostEqual(phase(complex(-0.0, -INF)), -pi/2)
466 self.assertAlmostEqual(phase(complex(0.0, -INF)), -pi/2)
467 self.assertAlmostEqual(phase(complex(2.3, -INF)), -pi/2)
468 self.assertAlmostEqual(phase(complex(INF, -INF)), -pi/4)
469 self.assertEqual(phase(complex(INF, -2.3)), -0.0)
470 self.assertEqual(phase(complex(INF, -0.0)), -0.0)
471 self.assertEqual(phase(complex(INF, 0.0)), 0.0)
472 self.assertEqual(phase(complex(INF, 2.3)), 0.0)
473 self.assertAlmostEqual(phase(complex(INF, INF)), pi/4)
474 self.assertAlmostEqual(phase(complex(2.3, INF)), pi/2)
475 self.assertAlmostEqual(phase(complex(0.0, INF)), pi/2)
476 self.assertAlmostEqual(phase(complex(-0.0, INF)), pi/2)
477 self.assertAlmostEqual(phase(complex(-2.3, INF)), pi/2)
478 self.assertAlmostEqual(phase(complex(-INF, INF)), 0.75*pi)
479 self.assertAlmostEqual(phase(complex(-INF, 2.3)), pi)
480 self.assertAlmostEqual(phase(complex(-INF, 0.0)), pi)
481
482 # real or imaginary part NaN
483 for z in complex_nans:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000484 self.assertTrue(math.isnan(phase(z)))
Christian Heimes53876d92008-04-19 00:31:39 +0000485
486 def test_abs(self):
487 # zeros
488 for z in complex_zeros:
489 self.assertEqual(abs(z), 0.0)
490
491 # infinities
492 for z in complex_infinities:
493 self.assertEqual(abs(z), INF)
494
495 # real or imaginary part NaN
496 self.assertEqual(abs(complex(NAN, -INF)), INF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000497 self.assertTrue(math.isnan(abs(complex(NAN, -2.3))))
498 self.assertTrue(math.isnan(abs(complex(NAN, -0.0))))
499 self.assertTrue(math.isnan(abs(complex(NAN, 0.0))))
500 self.assertTrue(math.isnan(abs(complex(NAN, 2.3))))
Christian Heimes53876d92008-04-19 00:31:39 +0000501 self.assertEqual(abs(complex(NAN, INF)), INF)
502 self.assertEqual(abs(complex(-INF, NAN)), INF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000503 self.assertTrue(math.isnan(abs(complex(-2.3, NAN))))
504 self.assertTrue(math.isnan(abs(complex(-0.0, NAN))))
505 self.assertTrue(math.isnan(abs(complex(0.0, NAN))))
506 self.assertTrue(math.isnan(abs(complex(2.3, NAN))))
Christian Heimes53876d92008-04-19 00:31:39 +0000507 self.assertEqual(abs(complex(INF, NAN)), INF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000508 self.assertTrue(math.isnan(abs(complex(NAN, NAN))))
Christian Heimes53876d92008-04-19 00:31:39 +0000509
Eric Smith3ab08ca2010-12-04 15:17:38 +0000510
511 @requires_IEEE_754
512 def test_abs_overflows(self):
Christian Heimes53876d92008-04-19 00:31:39 +0000513 # result overflows
Eric Smith3ab08ca2010-12-04 15:17:38 +0000514 self.assertRaises(OverflowError, abs, complex(1.4e308, 1.4e308))
Christian Heimes53876d92008-04-19 00:31:39 +0000515
516 def assertCEqual(self, a, b):
517 eps = 1E-7
518 if abs(a.real - b[0]) > eps or abs(a.imag - b[1]) > eps:
519 self.fail((a ,b))
520
521 def test_rect(self):
522 self.assertCEqual(rect(0, 0), (0, 0))
523 self.assertCEqual(rect(1, 0), (1., 0))
524 self.assertCEqual(rect(1, -pi), (-1., 0))
525 self.assertCEqual(rect(1, pi/2), (0, 1.))
526 self.assertCEqual(rect(1, -pi/2), (0, -1.))
527
Mark Dickinson8e0c9962010-07-11 17:38:24 +0000528 def test_isfinite(self):
529 real_vals = [float('-inf'), -2.3, -0.0,
530 0.0, 2.3, float('inf'), float('nan')]
531 for x in real_vals:
532 for y in real_vals:
533 z = complex(x, y)
Mark Dickinson68c5de62010-07-11 19:12:10 +0000534 self.assertEqual(cmath.isfinite(z),
Mark Dickinson8e0c9962010-07-11 17:38:24 +0000535 math.isfinite(x) and math.isfinite(y))
536
Christian Heimes53876d92008-04-19 00:31:39 +0000537 def test_isnan(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000538 self.assertFalse(cmath.isnan(1))
539 self.assertFalse(cmath.isnan(1j))
540 self.assertFalse(cmath.isnan(INF))
541 self.assertTrue(cmath.isnan(NAN))
542 self.assertTrue(cmath.isnan(complex(NAN, 0)))
543 self.assertTrue(cmath.isnan(complex(0, NAN)))
544 self.assertTrue(cmath.isnan(complex(NAN, NAN)))
545 self.assertTrue(cmath.isnan(complex(NAN, INF)))
546 self.assertTrue(cmath.isnan(complex(INF, NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000547
548 def test_isinf(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000549 self.assertFalse(cmath.isinf(1))
550 self.assertFalse(cmath.isinf(1j))
551 self.assertFalse(cmath.isinf(NAN))
552 self.assertTrue(cmath.isinf(INF))
553 self.assertTrue(cmath.isinf(complex(INF, 0)))
554 self.assertTrue(cmath.isinf(complex(0, INF)))
555 self.assertTrue(cmath.isinf(complex(INF, INF)))
556 self.assertTrue(cmath.isinf(complex(NAN, INF)))
557 self.assertTrue(cmath.isinf(complex(INF, NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000558
Victor Stinnerbe3da382010-11-07 14:14:27 +0000559 @requires_IEEE_754
560 @unittest.skipIf(sysconfig.get_config_var('TANH_PRESERVES_ZERO_SIGN') == 0,
561 "system tanh() function doesn't copy the sign")
562 def testTanhSign(self):
Mark Dickinson5ccafba2010-11-13 10:43:40 +0000563 for z in complex_zeros:
564 self.assertComplexIdentical(cmath.tanh(z), z)
Victor Stinnerbe3da382010-11-07 14:14:27 +0000565
Mark Dickinson4ccc1372010-11-20 11:08:27 +0000566 # The algorithm used for atan and atanh makes use of the system
567 # log1p function; If that system function doesn't respect the sign
568 # of zero, then atan and atanh will also have difficulties with
569 # the sign of complex zeros.
570 @requires_IEEE_754
Mark Dickinson4ccc1372010-11-20 11:08:27 +0000571 def testAtanSign(self):
572 for z in complex_zeros:
573 self.assertComplexIdentical(cmath.atan(z), z)
574
575 @requires_IEEE_754
Mark Dickinson4ccc1372010-11-20 11:08:27 +0000576 def testAtanhSign(self):
577 for z in complex_zeros:
578 self.assertComplexIdentical(cmath.atanh(z), z)
579
Guido van Rossumd8faa362007-04-27 19:54:29 +0000580
Tal Einatd5519ed2015-05-31 22:05:00 +0300581class IsCloseTests(test_math.IsCloseTests):
582 isclose = cmath.isclose
583
584 def test_reject_complex_tolerances(self):
585 with self.assertRaises(TypeError):
586 self.isclose(1j, 1j, rel_tol=1j)
587
588 with self.assertRaises(TypeError):
589 self.isclose(1j, 1j, abs_tol=1j)
590
591 with self.assertRaises(TypeError):
592 self.isclose(1j, 1j, rel_tol=1j, abs_tol=1j)
593
594 def test_complex_values(self):
595 # test complex values that are close to within 12 decimal places
596 complex_examples = [(1.0+1.0j, 1.000000000001+1.0j),
597 (1.0+1.0j, 1.0+1.000000000001j),
598 (-1.0+1.0j, -1.000000000001+1.0j),
599 (1.0-1.0j, 1.0-0.999999999999j),
600 ]
601
602 self.assertAllClose(complex_examples, rel_tol=1e-12)
603 self.assertAllNotClose(complex_examples, rel_tol=1e-13)
604
605 def test_complex_near_zero(self):
606 # test values near zero that are near to within three decimal places
607 near_zero_examples = [(0.001j, 0),
608 (0.001, 0),
609 (0.001+0.001j, 0),
610 (-0.001+0.001j, 0),
611 (0.001-0.001j, 0),
612 (-0.001-0.001j, 0),
613 ]
614
615 self.assertAllClose(near_zero_examples, abs_tol=1.5e-03)
616 self.assertAllNotClose(near_zero_examples, abs_tol=0.5e-03)
617
618 self.assertIsClose(0.001-0.001j, 0.001+0.001j, abs_tol=2e-03)
619 self.assertIsNotClose(0.001-0.001j, 0.001+0.001j, abs_tol=1e-03)
620
621
Guido van Rossumd8faa362007-04-27 19:54:29 +0000622if __name__ == "__main__":
Zachary Ware38c707e2015-04-13 15:00:43 -0500623 unittest.main()