/Lib/test/test_cmath.py

http://unladen-swallow.googlecode.com/ · Python · 488 lines · 357 code · 62 blank · 69 comment · 64 complexity · d8d5928d07809adc2574a9354aec40f3 MD5 · raw file

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