PageRenderTime 45ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/test/test_cmath.py

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