• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1from test.test_support import run_unittest, cpython_only
2from test.test_math import parse_testfile, test_file
3import unittest
4import cmath, math
5from cmath import phase, polar, rect, pi
6
7INF = float('inf')
8NAN = float('nan')
9
10complex_zeros = [complex(x, y) for x in [0.0, -0.0] for y in [0.0, -0.0]]
11complex_infinities = [complex(x, y) for x, y in [
12        (INF, 0.0),  # 1st quadrant
13        (INF, 2.3),
14        (INF, INF),
15        (2.3, INF),
16        (0.0, INF),
17        (-0.0, INF), # 2nd quadrant
18        (-2.3, INF),
19        (-INF, INF),
20        (-INF, 2.3),
21        (-INF, 0.0),
22        (-INF, -0.0), # 3rd quadrant
23        (-INF, -2.3),
24        (-INF, -INF),
25        (-2.3, -INF),
26        (-0.0, -INF),
27        (0.0, -INF), # 4th quadrant
28        (2.3, -INF),
29        (INF, -INF),
30        (INF, -2.3),
31        (INF, -0.0)
32        ]]
33complex_nans = [complex(x, y) for x, y in [
34        (NAN, -INF),
35        (NAN, -2.3),
36        (NAN, -0.0),
37        (NAN, 0.0),
38        (NAN, 2.3),
39        (NAN, INF),
40        (-INF, NAN),
41        (-2.3, NAN),
42        (-0.0, NAN),
43        (0.0, NAN),
44        (2.3, NAN),
45        (INF, NAN)
46        ]]
47
48class CMathTests(unittest.TestCase):
49    # list of all functions in cmath
50    test_functions = [getattr(cmath, fname) for fname in [
51            'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh',
52            'cos', 'cosh', 'exp', 'log', 'log10', 'sin', 'sinh',
53            'sqrt', 'tan', 'tanh']]
54    # test first and second arguments independently for 2-argument log
55    test_functions.append(lambda x : cmath.log(x, 1729. + 0j))
56    test_functions.append(lambda x : cmath.log(14.-27j, x))
57
58    def setUp(self):
59        self.test_values = open(test_file)
60
61    def tearDown(self):
62        self.test_values.close()
63
64    def rAssertAlmostEqual(self, a, b, rel_err = 2e-15, abs_err = 5e-323,
65                           msg=None):
66        """Fail if the two floating-point numbers are not almost equal.
67
68        Determine whether floating-point values a and b are equal to within
69        a (small) rounding error.  The default values for rel_err and
70        abs_err are chosen to be suitable for platforms where a float is
71        represented by an IEEE 754 double.  They allow an error of between
72        9 and 19 ulps.
73        """
74
75        # special values testing
76        if math.isnan(a):
77            if math.isnan(b):
78                return
79            self.fail(msg or '{!r} should be nan'.format(b))
80
81        if math.isinf(a):
82            if a == b:
83                return
84            self.fail(msg or 'finite result where infinity expected: '
85                      'expected {!r}, got {!r}'.format(a, b))
86
87        # if both a and b are zero, check whether they have the same sign
88        # (in theory there are examples where it would be legitimate for a
89        # and b to have opposite signs; in practice these hardly ever
90        # occur).
91        if not a and not b:
92            if math.copysign(1., a) != math.copysign(1., b):
93                self.fail(msg or 'zero has wrong sign: expected {!r}, '
94                          'got {!r}'.format(a, b))
95
96        # if a-b overflows, or b is infinite, return False.  Again, in
97        # theory there are examples where a is within a few ulps of the
98        # max representable float, and then b could legitimately be
99        # infinite.  In practice these examples are rare.
100        try:
101            absolute_error = abs(b-a)
102        except OverflowError:
103            pass
104        else:
105            # test passes if either the absolute error or the relative
106            # error is sufficiently small.  The defaults amount to an
107            # error of between 9 ulps and 19 ulps on an IEEE-754 compliant
108            # machine.
109            if absolute_error <= max(abs_err, rel_err * abs(a)):
110                return
111        self.fail(msg or
112                  '{!r} and {!r} are not sufficiently close'.format(a, b))
113
114    def test_constants(self):
115        e_expected = 2.71828182845904523536
116        pi_expected = 3.14159265358979323846
117        self.assertAlmostEqual(cmath.pi, pi_expected, places=9,
118            msg="cmath.pi is {}; should be {}".format(cmath.pi, pi_expected))
119        self.assertAlmostEqual(cmath.e, e_expected, places=9,
120            msg="cmath.e is {}; should be {}".format(cmath.e, e_expected))
121
122    def test_user_object(self):
123        # Test automatic calling of __complex__ and __float__ by cmath
124        # functions
125
126        # some random values to use as test values; we avoid values
127        # for which any of the functions in cmath is undefined
128        # (i.e. 0., 1., -1., 1j, -1j) or would cause overflow
129        cx_arg = 4.419414439 + 1.497100113j
130        flt_arg = -6.131677725
131
132        # a variety of non-complex numbers, used to check that
133        # non-complex return values from __complex__ give an error
134        non_complexes = ["not complex", 1, 5L, 2., None,
135                         object(), NotImplemented]
136
137        # Now we introduce a variety of classes whose instances might
138        # end up being passed to the cmath functions
139
140        # usual case: new-style class implementing __complex__
141        class MyComplex(object):
142            def __init__(self, value):
143                self.value = value
144            def __complex__(self):
145                return self.value
146
147        # old-style class implementing __complex__
148        class MyComplexOS:
149            def __init__(self, value):
150                self.value = value
151            def __complex__(self):
152                return self.value
153
154        # classes for which __complex__ raises an exception
155        class SomeException(Exception):
156            pass
157        class MyComplexException(object):
158            def __complex__(self):
159                raise SomeException
160        class MyComplexExceptionOS:
161            def __complex__(self):
162                raise SomeException
163
164        # some classes not providing __float__ or __complex__
165        class NeitherComplexNorFloat(object):
166            pass
167        class NeitherComplexNorFloatOS:
168            pass
169        class MyInt(object):
170            def __int__(self): return 2
171            def __long__(self): return 2L
172            def __index__(self): return 2
173        class MyIntOS:
174            def __int__(self): return 2
175            def __long__(self): return 2L
176            def __index__(self): return 2
177
178        # other possible combinations of __float__ and __complex__
179        # that should work
180        class FloatAndComplex(object):
181            def __float__(self):
182                return flt_arg
183            def __complex__(self):
184                return cx_arg
185        class FloatAndComplexOS:
186            def __float__(self):
187                return flt_arg
188            def __complex__(self):
189                return cx_arg
190        class JustFloat(object):
191            def __float__(self):
192                return flt_arg
193        class JustFloatOS:
194            def __float__(self):
195                return flt_arg
196
197        for f in self.test_functions:
198            # usual usage
199            self.assertEqual(f(MyComplex(cx_arg)), f(cx_arg))
200            self.assertEqual(f(MyComplexOS(cx_arg)), f(cx_arg))
201            # other combinations of __float__ and __complex__
202            self.assertEqual(f(FloatAndComplex()), f(cx_arg))
203            self.assertEqual(f(FloatAndComplexOS()), f(cx_arg))
204            self.assertEqual(f(JustFloat()), f(flt_arg))
205            self.assertEqual(f(JustFloatOS()), f(flt_arg))
206            # TypeError should be raised for classes not providing
207            # either __complex__ or __float__, even if they provide
208            # __int__, __long__ or __index__.  An old-style class
209            # currently raises AttributeError instead of a TypeError;
210            # this could be considered a bug.
211            self.assertRaises(TypeError, f, NeitherComplexNorFloat())
212            self.assertRaises(TypeError, f, MyInt())
213            self.assertRaises(Exception, f, NeitherComplexNorFloatOS())
214            self.assertRaises(Exception, f, MyIntOS())
215            # non-complex return value from __complex__ -> TypeError
216            for bad_complex in non_complexes:
217                self.assertRaises(TypeError, f, MyComplex(bad_complex))
218                self.assertRaises(TypeError, f, MyComplexOS(bad_complex))
219            # exceptions in __complex__ should be propagated correctly
220            self.assertRaises(SomeException, f, MyComplexException())
221            self.assertRaises(SomeException, f, MyComplexExceptionOS())
222
223    def test_input_type(self):
224        # ints and longs should be acceptable inputs to all cmath
225        # functions, by virtue of providing a __float__ method
226        for f in self.test_functions:
227            for arg in [2, 2L, 2.]:
228                self.assertEqual(f(arg), f(arg.__float__()))
229
230        # but strings should give a TypeError
231        for f in self.test_functions:
232            for arg in ["a", "long_string", "0", "1j", ""]:
233                self.assertRaises(TypeError, f, arg)
234
235    def test_cmath_matches_math(self):
236        # check that corresponding cmath and math functions are equal
237        # for floats in the appropriate range
238
239        # test_values in (0, 1)
240        test_values = [0.01, 0.1, 0.2, 0.5, 0.9, 0.99]
241
242        # test_values for functions defined on [-1., 1.]
243        unit_interval = test_values + [-x for x in test_values] + \
244            [0., 1., -1.]
245
246        # test_values for log, log10, sqrt
247        positive = test_values + [1.] + [1./x for x in test_values]
248        nonnegative = [0.] + positive
249
250        # test_values for functions defined on the whole real line
251        real_line = [0.] + positive + [-x for x in positive]
252
253        test_functions = {
254            'acos' : unit_interval,
255            'asin' : unit_interval,
256            'atan' : real_line,
257            'cos' : real_line,
258            'cosh' : real_line,
259            'exp' : real_line,
260            'log' : positive,
261            'log10' : positive,
262            'sin' : real_line,
263            'sinh' : real_line,
264            'sqrt' : nonnegative,
265            'tan' : real_line,
266            'tanh' : real_line}
267
268        for fn, values in test_functions.items():
269            float_fn = getattr(math, fn)
270            complex_fn = getattr(cmath, fn)
271            for v in values:
272                z = complex_fn(v)
273                self.rAssertAlmostEqual(float_fn(v), z.real)
274                self.assertEqual(0., z.imag)
275
276        # test two-argument version of log with various bases
277        for base in [0.5, 2., 10.]:
278            for v in positive:
279                z = cmath.log(v, base)
280                self.rAssertAlmostEqual(math.log(v, base), z.real)
281                self.assertEqual(0., z.imag)
282
283    def test_specific_values(self):
284        if not float.__getformat__("double").startswith("IEEE"):
285            self.skipTest('needs IEEE double')
286
287        def rect_complex(z):
288            """Wrapped version of rect that accepts a complex number instead of
289            two float arguments."""
290            return cmath.rect(z.real, z.imag)
291
292        def polar_complex(z):
293            """Wrapped version of polar that returns a complex number instead of
294            two floats."""
295            return complex(*polar(z))
296
297        for id, fn, ar, ai, er, ei, flags in parse_testfile(test_file):
298            arg = complex(ar, ai)
299            expected = complex(er, ei)
300            if fn == 'rect':
301                function = rect_complex
302            elif fn == 'polar':
303                function = polar_complex
304            else:
305                function = getattr(cmath, fn)
306            if 'divide-by-zero' in flags or 'invalid' in flags:
307                try:
308                    actual = function(arg)
309                except ValueError:
310                    continue
311                else:
312                    self.fail('ValueError not raised in test '
313                          '{}: {}(complex({!r}, {!r}))'.format(id, fn, ar, ai))
314
315            if 'overflow' in flags:
316                try:
317                    actual = function(arg)
318                except OverflowError:
319                    continue
320                else:
321                    self.fail('OverflowError not raised in test '
322                          '{}: {}(complex({!r}, {!r}))'.format(id, fn, ar, ai))
323
324            actual = function(arg)
325
326            if 'ignore-real-sign' in flags:
327                actual = complex(abs(actual.real), actual.imag)
328                expected = complex(abs(expected.real), expected.imag)
329            if 'ignore-imag-sign' in flags:
330                actual = complex(actual.real, abs(actual.imag))
331                expected = complex(expected.real, abs(expected.imag))
332
333            # for the real part of the log function, we allow an
334            # absolute error of up to 2e-15.
335            if fn in ('log', 'log10'):
336                real_abs_err = 2e-15
337            else:
338                real_abs_err = 5e-323
339
340            error_message = (
341                '{}: {}(complex({!r}, {!r}))\n'
342                'Expected: complex({!r}, {!r})\n'
343                'Received: complex({!r}, {!r})\n'
344                'Received value insufficiently close to expected value.'
345                ).format(id, fn, ar, ai,
346                     expected.real, expected.imag,
347                     actual.real, actual.imag)
348            self.rAssertAlmostEqual(expected.real, actual.real,
349                                        abs_err=real_abs_err,
350                                        msg=error_message)
351            self.rAssertAlmostEqual(expected.imag, actual.imag,
352                                        msg=error_message)
353
354    def check_polar(self, func):
355        def check(arg, expected):
356            got = func(arg)
357            for e, g in zip(expected, got):
358                self.rAssertAlmostEqual(e, g)
359        check(0, (0., 0.))
360        check(1, (1., 0.))
361        check(-1, (1., pi))
362        check(1j, (1., pi / 2))
363        check(-3j, (3., -pi / 2))
364        inf = float('inf')
365        check(complex(inf, 0), (inf, 0.))
366        check(complex(-inf, 0), (inf, pi))
367        check(complex(3, inf), (inf, pi / 2))
368        check(complex(5, -inf), (inf, -pi / 2))
369        check(complex(inf, inf), (inf, pi / 4))
370        check(complex(inf, -inf), (inf, -pi / 4))
371        check(complex(-inf, inf), (inf, 3 * pi / 4))
372        check(complex(-inf, -inf), (inf, -3 * pi / 4))
373        nan = float('nan')
374        check(complex(nan, 0), (nan, nan))
375        check(complex(0, nan), (nan, nan))
376        check(complex(nan, nan), (nan, nan))
377        check(complex(inf, nan), (inf, nan))
378        check(complex(-inf, nan), (inf, nan))
379        check(complex(nan, inf), (inf, nan))
380        check(complex(nan, -inf), (inf, nan))
381
382    def test_polar(self):
383        self.check_polar(polar)
384
385    @cpython_only
386    def test_polar_errno(self):
387        # Issue #24489: check a previously set C errno doesn't disturb polar()
388        from _testcapi import set_errno
389        def polar_with_errno_set(z):
390            set_errno(11)
391            try:
392                return polar(z)
393            finally:
394                set_errno(0)
395        self.check_polar(polar_with_errno_set)
396
397    def test_phase(self):
398        self.assertAlmostEqual(phase(0), 0.)
399        self.assertAlmostEqual(phase(1.), 0.)
400        self.assertAlmostEqual(phase(-1.), pi)
401        self.assertAlmostEqual(phase(-1.+1E-300j), pi)
402        self.assertAlmostEqual(phase(-1.-1E-300j), -pi)
403        self.assertAlmostEqual(phase(1j), pi/2)
404        self.assertAlmostEqual(phase(-1j), -pi/2)
405
406        # zeros
407        self.assertEqual(phase(complex(0.0, 0.0)), 0.0)
408        self.assertEqual(phase(complex(0.0, -0.0)), -0.0)
409        self.assertEqual(phase(complex(-0.0, 0.0)), pi)
410        self.assertEqual(phase(complex(-0.0, -0.0)), -pi)
411
412        # infinities
413        self.assertAlmostEqual(phase(complex(-INF, -0.0)), -pi)
414        self.assertAlmostEqual(phase(complex(-INF, -2.3)), -pi)
415        self.assertAlmostEqual(phase(complex(-INF, -INF)), -0.75*pi)
416        self.assertAlmostEqual(phase(complex(-2.3, -INF)), -pi/2)
417        self.assertAlmostEqual(phase(complex(-0.0, -INF)), -pi/2)
418        self.assertAlmostEqual(phase(complex(0.0, -INF)), -pi/2)
419        self.assertAlmostEqual(phase(complex(2.3, -INF)), -pi/2)
420        self.assertAlmostEqual(phase(complex(INF, -INF)), -pi/4)
421        self.assertEqual(phase(complex(INF, -2.3)), -0.0)
422        self.assertEqual(phase(complex(INF, -0.0)), -0.0)
423        self.assertEqual(phase(complex(INF, 0.0)), 0.0)
424        self.assertEqual(phase(complex(INF, 2.3)), 0.0)
425        self.assertAlmostEqual(phase(complex(INF, INF)), pi/4)
426        self.assertAlmostEqual(phase(complex(2.3, INF)), pi/2)
427        self.assertAlmostEqual(phase(complex(0.0, INF)), pi/2)
428        self.assertAlmostEqual(phase(complex(-0.0, INF)), pi/2)
429        self.assertAlmostEqual(phase(complex(-2.3, INF)), pi/2)
430        self.assertAlmostEqual(phase(complex(-INF, INF)), 0.75*pi)
431        self.assertAlmostEqual(phase(complex(-INF, 2.3)), pi)
432        self.assertAlmostEqual(phase(complex(-INF, 0.0)), pi)
433
434        # real or imaginary part NaN
435        for z in complex_nans:
436            self.assertTrue(math.isnan(phase(z)))
437
438    def test_abs(self):
439        # zeros
440        for z in complex_zeros:
441            self.assertEqual(abs(z), 0.0)
442
443        # infinities
444        for z in complex_infinities:
445            self.assertEqual(abs(z), INF)
446
447        # real or imaginary part NaN
448        self.assertEqual(abs(complex(NAN, -INF)), INF)
449        self.assertTrue(math.isnan(abs(complex(NAN, -2.3))))
450        self.assertTrue(math.isnan(abs(complex(NAN, -0.0))))
451        self.assertTrue(math.isnan(abs(complex(NAN, 0.0))))
452        self.assertTrue(math.isnan(abs(complex(NAN, 2.3))))
453        self.assertEqual(abs(complex(NAN, INF)), INF)
454        self.assertEqual(abs(complex(-INF, NAN)), INF)
455        self.assertTrue(math.isnan(abs(complex(-2.3, NAN))))
456        self.assertTrue(math.isnan(abs(complex(-0.0, NAN))))
457        self.assertTrue(math.isnan(abs(complex(0.0, NAN))))
458        self.assertTrue(math.isnan(abs(complex(2.3, NAN))))
459        self.assertEqual(abs(complex(INF, NAN)), INF)
460        self.assertTrue(math.isnan(abs(complex(NAN, NAN))))
461
462        # result overflows
463        if float.__getformat__("double").startswith("IEEE"):
464            self.assertRaises(OverflowError, abs, complex(1.4e308, 1.4e308))
465
466    def assertCEqual(self, a, b):
467        eps = 1E-7
468        if abs(a.real - b[0]) > eps or abs(a.imag - b[1]) > eps:
469            self.fail((a ,b))
470
471    def test_rect(self):
472        self.assertCEqual(rect(0, 0), (0, 0))
473        self.assertCEqual(rect(1, 0), (1., 0))
474        self.assertCEqual(rect(1, -pi), (-1., 0))
475        self.assertCEqual(rect(1, pi/2), (0, 1.))
476        self.assertCEqual(rect(1, -pi/2), (0, -1.))
477
478    def test_isnan(self):
479        self.assertFalse(cmath.isnan(1))
480        self.assertFalse(cmath.isnan(1j))
481        self.assertFalse(cmath.isnan(INF))
482        self.assertTrue(cmath.isnan(NAN))
483        self.assertTrue(cmath.isnan(complex(NAN, 0)))
484        self.assertTrue(cmath.isnan(complex(0, NAN)))
485        self.assertTrue(cmath.isnan(complex(NAN, NAN)))
486        self.assertTrue(cmath.isnan(complex(NAN, INF)))
487        self.assertTrue(cmath.isnan(complex(INF, NAN)))
488
489    def test_isinf(self):
490        self.assertFalse(cmath.isinf(1))
491        self.assertFalse(cmath.isinf(1j))
492        self.assertFalse(cmath.isinf(NAN))
493        self.assertTrue(cmath.isinf(INF))
494        self.assertTrue(cmath.isinf(complex(INF, 0)))
495        self.assertTrue(cmath.isinf(complex(0, INF)))
496        self.assertTrue(cmath.isinf(complex(INF, INF)))
497        self.assertTrue(cmath.isinf(complex(NAN, INF)))
498        self.assertTrue(cmath.isinf(complex(INF, NAN)))
499
500
501def test_main():
502    run_unittest(CMathTests)
503
504if __name__ == "__main__":
505    test_main()
506