PageRenderTime 66ms CodeModel.GetById 8ms RepoModel.GetById 1ms app.codeStats 0ms

/pypy/module/cmath/test/test_cmath.py

https://bitbucket.org/dac_io/pypy
Python | 241 lines | 213 code | 22 blank | 6 comment | 7 complexity | b925e2b82277d65afd70b59ceb1bc8b0 MD5 | raw file
  1. from __future__ import with_statement
  2. from pypy.conftest import gettestobjspace
  3. from pypy.rlib.rfloat import copysign, isnan, isinf
  4. from pypy.module.cmath import interp_cmath
  5. import os, sys, math
  6. def test_special_values():
  7. from pypy.module.cmath.special_value import sqrt_special_values
  8. assert len(sqrt_special_values) == 7
  9. assert len(sqrt_special_values[4]) == 7
  10. assert isinstance(sqrt_special_values[5][1], tuple)
  11. assert sqrt_special_values[5][1][0] == 1e200 * 1e200
  12. assert sqrt_special_values[5][1][1] == -0.
  13. assert copysign(1., sqrt_special_values[5][1][1]) == -1.
  14. class AppTestCMath:
  15. def setup_class(cls):
  16. cls.space = gettestobjspace(usemodules=['cmath'])
  17. def test_sign(self):
  18. import math
  19. z = eval("-0j")
  20. assert z == -0j
  21. assert math.copysign(1., z.real) == 1.
  22. assert math.copysign(1., z.imag) == -1.
  23. def test_sqrt(self):
  24. import cmath, math
  25. assert cmath.sqrt(3+4j) == 2+1j
  26. z = cmath.sqrt(-0j)
  27. assert math.copysign(1., z.real) == 1.
  28. assert math.copysign(1., z.imag) == -1.
  29. dbl_min = 2.2250738585072014e-308
  30. z = cmath.sqrt((dbl_min * 0.00000000000001) + 0j)
  31. assert abs(z.real - 1.49107189843e-161) < 1e-170
  32. assert z.imag == 0.0
  33. z = cmath.sqrt(1e200*1e200 - 10j)
  34. assert math.isinf(z.real) and z.real > 0.0
  35. assert z.imag == 0.0 and math.copysign(1., z.imag) == -1.
  36. def test_log(self):
  37. import cmath, math
  38. z = cmath.log(100j, 10j)
  39. assert abs(z - (1.6824165174565446-0.46553647994440367j)) < 1e-10
  40. def test_pi_e(self):
  41. import cmath, math
  42. assert cmath.pi == math.pi
  43. assert cmath.e == math.e
  44. def test_rect(self):
  45. import cmath
  46. z = cmath.rect(2.0, cmath.pi/2)
  47. assert abs(z - 2j) < 1e-10
  48. def test_polar(self):
  49. import cmath
  50. r, phi = cmath.polar(2j)
  51. assert r == 2
  52. assert abs(phi - cmath.pi/2) < 1e-10
  53. def test_phase(self):
  54. import cmath
  55. phi = cmath.phase(2j)
  56. assert abs(phi - cmath.pi/2) < 1e-10
  57. def test_valueerror(self):
  58. import cmath
  59. raises(ValueError, cmath.log, 0j)
  60. def test_stringarg(self):
  61. import cmath
  62. raises(TypeError, cmath.log, "-3j")
  63. def test_isinf(self):
  64. import cmath
  65. assert not cmath.isinf(2+3j)
  66. assert cmath.isinf(float("inf"))
  67. assert cmath.isinf(-float("inf"))
  68. assert cmath.isinf(complex("infj"))
  69. assert cmath.isinf(complex("2-infj"))
  70. assert cmath.isinf(complex("inf+nanj"))
  71. assert cmath.isinf(complex("nan+infj"))
  72. def test_isnan(self):
  73. import cmath
  74. assert not cmath.isnan(2+3j)
  75. assert cmath.isnan(float("nan"))
  76. assert cmath.isnan(complex("nanj"))
  77. assert cmath.isnan(complex("inf+nanj"))
  78. assert cmath.isnan(complex("nan+infj"))
  79. def test_user_defined_complex(self):
  80. import cmath
  81. class Foo(object):
  82. def __complex__(self):
  83. return 2j
  84. r, phi = cmath.polar(Foo())
  85. assert r == 2
  86. assert abs(phi - cmath.pi/2) < 1e-10
  87. def test_user_defined_float(self):
  88. import cmath
  89. class Foo(object):
  90. def __float__(self):
  91. return 2.0
  92. assert cmath.polar(Foo()) == (2, 0)
  93. def parse_testfile(fname):
  94. """Parse a file with test values
  95. Empty lines or lines starting with -- are ignored
  96. yields id, fn, arg_real, arg_imag, exp_real, exp_imag
  97. """
  98. fname = os.path.join(os.path.dirname(__file__), fname)
  99. with open(fname) as fp:
  100. for line in fp:
  101. # skip comment lines and blank lines
  102. if line.startswith('--') or not line.strip():
  103. continue
  104. lhs, rhs = line.split('->')
  105. id, fn, arg_real, arg_imag = lhs.split()
  106. rhs_pieces = rhs.split()
  107. exp_real, exp_imag = rhs_pieces[0], rhs_pieces[1]
  108. flags = rhs_pieces[2:]
  109. yield (id, fn,
  110. float(arg_real), float(arg_imag),
  111. float(exp_real), float(exp_imag),
  112. flags
  113. )
  114. def rAssertAlmostEqual(a, b, rel_err = 2e-15, abs_err = 5e-323, msg=''):
  115. """Fail if the two floating-point numbers are not almost equal.
  116. Determine whether floating-point values a and b are equal to within
  117. a (small) rounding error. The default values for rel_err and
  118. abs_err are chosen to be suitable for platforms where a float is
  119. represented by an IEEE 754 double. They allow an error of between
  120. 9 and 19 ulps.
  121. """
  122. # special values testing
  123. if isnan(a):
  124. if isnan(b):
  125. return
  126. raise AssertionError(msg + '%r should be nan' % (b,))
  127. if isinf(a):
  128. if a == b:
  129. return
  130. raise AssertionError(msg + 'finite result where infinity expected: '
  131. 'expected %r, got %r' % (a, b))
  132. # if both a and b are zero, check whether they have the same sign
  133. # (in theory there are examples where it would be legitimate for a
  134. # and b to have opposite signs; in practice these hardly ever
  135. # occur).
  136. if not a and not b:
  137. # only check it if we are running on top of CPython >= 2.6
  138. if sys.version_info >= (2, 6) and copysign(1., a) != copysign(1., b):
  139. raise AssertionError(msg + 'zero has wrong sign: expected %r, '
  140. 'got %r' % (a, b))
  141. # if a-b overflows, or b is infinite, return False. Again, in
  142. # theory there are examples where a is within a few ulps of the
  143. # max representable float, and then b could legitimately be
  144. # infinite. In practice these examples are rare.
  145. try:
  146. absolute_error = abs(b-a)
  147. except OverflowError:
  148. pass
  149. else:
  150. # test passes if either the absolute error or the relative
  151. # error is sufficiently small. The defaults amount to an
  152. # error of between 9 ulps and 19 ulps on an IEEE-754 compliant
  153. # machine.
  154. if absolute_error <= max(abs_err, rel_err * abs(a)):
  155. return
  156. raise AssertionError(msg + '%r and %r are not sufficiently close' % (a, b))
  157. def test_specific_values():
  158. #if not float.__getformat__("double").startswith("IEEE"):
  159. # return
  160. for id, fn, ar, ai, er, ei, flags in parse_testfile('cmath_testcases.txt'):
  161. arg = (ar, ai)
  162. expected = (er, ei)
  163. function = getattr(interp_cmath, 'c_' + fn)
  164. #
  165. if 'divide-by-zero' in flags or 'invalid' in flags:
  166. try:
  167. actual = function(*arg)
  168. except ValueError:
  169. continue
  170. else:
  171. raise AssertionError('ValueError not raised in test '
  172. '%s: %s(complex(%r, %r))' % (id, fn,
  173. ar, ai))
  174. if 'overflow' in flags:
  175. try:
  176. actual = function(*arg)
  177. except OverflowError:
  178. continue
  179. else:
  180. raise AssertionError('OverflowError not raised in test '
  181. '%s: %s(complex(%r, %r))' % (id, fn,
  182. ar, ai))
  183. actual = function(*arg)
  184. if 'ignore-real-sign' in flags:
  185. actual = (abs(actual[0]), actual[1])
  186. expected = (abs(expected[0]), expected[1])
  187. if 'ignore-imag-sign' in flags:
  188. actual = (actual[0], abs(actual[1]))
  189. expected = (expected[0], abs(expected[1]))
  190. # for the real part of the log function, we allow an
  191. # absolute error of up to 2e-15.
  192. if fn in ('log', 'log10'):
  193. real_abs_err = 2e-15
  194. else:
  195. real_abs_err = 5e-323
  196. error_message = (
  197. '%s: %s(complex(%r, %r))\n'
  198. 'Expected: complex(%r, %r)\n'
  199. 'Received: complex(%r, %r)\n'
  200. ) % (id, fn, ar, ai,
  201. expected[0], expected[1],
  202. actual[0], actual[1])
  203. rAssertAlmostEqual(expected[0], actual[0],
  204. abs_err=real_abs_err,
  205. msg=error_message)
  206. rAssertAlmostEqual(expected[1], actual[1],
  207. msg=error_message)