test_numeric_tower.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. # test interactions between int, float, Decimal and Fraction
  2. import unittest
  3. import random
  4. import math
  5. import sys
  6. import operator
  7. from decimal import Decimal as D
  8. from fractions import Fraction as F
  9. # Constants related to the hash implementation; hash(x) is based
  10. # on the reduction of x modulo the prime _PyHASH_MODULUS.
  11. _PyHASH_MODULUS = sys.hash_info.modulus
  12. _PyHASH_INF = sys.hash_info.inf
  13. class DummyIntegral(int):
  14. """Dummy Integral class to test conversion of the Rational to float."""
  15. def __mul__(self, other):
  16. return DummyIntegral(super().__mul__(other))
  17. __rmul__ = __mul__
  18. def __truediv__(self, other):
  19. return NotImplemented
  20. __rtruediv__ = __truediv__
  21. @property
  22. def numerator(self):
  23. return DummyIntegral(self)
  24. @property
  25. def denominator(self):
  26. return DummyIntegral(1)
  27. class HashTest(unittest.TestCase):
  28. def check_equal_hash(self, x, y):
  29. # check both that x and y are equal and that their hashes are equal
  30. self.assertEqual(hash(x), hash(y),
  31. "got different hashes for {!r} and {!r}".format(x, y))
  32. self.assertEqual(x, y)
  33. def test_bools(self):
  34. self.check_equal_hash(False, 0)
  35. self.check_equal_hash(True, 1)
  36. def test_integers(self):
  37. # check that equal values hash equal
  38. # exact integers
  39. for i in range(-1000, 1000):
  40. self.check_equal_hash(i, float(i))
  41. self.check_equal_hash(i, D(i))
  42. self.check_equal_hash(i, F(i))
  43. # the current hash is based on reduction modulo 2**n-1 for some
  44. # n, so pay special attention to numbers of the form 2**n and 2**n-1.
  45. for i in range(100):
  46. n = 2**i - 1
  47. if n == int(float(n)):
  48. self.check_equal_hash(n, float(n))
  49. self.check_equal_hash(-n, -float(n))
  50. self.check_equal_hash(n, D(n))
  51. self.check_equal_hash(n, F(n))
  52. self.check_equal_hash(-n, D(-n))
  53. self.check_equal_hash(-n, F(-n))
  54. n = 2**i
  55. self.check_equal_hash(n, float(n))
  56. self.check_equal_hash(-n, -float(n))
  57. self.check_equal_hash(n, D(n))
  58. self.check_equal_hash(n, F(n))
  59. self.check_equal_hash(-n, D(-n))
  60. self.check_equal_hash(-n, F(-n))
  61. # random values of various sizes
  62. for _ in range(1000):
  63. e = random.randrange(300)
  64. n = random.randrange(-10**e, 10**e)
  65. self.check_equal_hash(n, D(n))
  66. self.check_equal_hash(n, F(n))
  67. if n == int(float(n)):
  68. self.check_equal_hash(n, float(n))
  69. def test_binary_floats(self):
  70. # check that floats hash equal to corresponding Fractions and Decimals
  71. # floats that are distinct but numerically equal should hash the same
  72. self.check_equal_hash(0.0, -0.0)
  73. # zeros
  74. self.check_equal_hash(0.0, D(0))
  75. self.check_equal_hash(-0.0, D(0))
  76. self.check_equal_hash(-0.0, D('-0.0'))
  77. self.check_equal_hash(0.0, F(0))
  78. # infinities and nans
  79. self.check_equal_hash(float('inf'), D('inf'))
  80. self.check_equal_hash(float('-inf'), D('-inf'))
  81. for _ in range(1000):
  82. x = random.random() * math.exp(random.random()*200.0 - 100.0)
  83. self.check_equal_hash(x, D.from_float(x))
  84. self.check_equal_hash(x, F.from_float(x))
  85. def test_complex(self):
  86. # complex numbers with zero imaginary part should hash equal to
  87. # the corresponding float
  88. test_values = [0.0, -0.0, 1.0, -1.0, 0.40625, -5136.5,
  89. float('inf'), float('-inf')]
  90. for zero in -0.0, 0.0:
  91. for value in test_values:
  92. self.check_equal_hash(value, complex(value, zero))
  93. def test_decimals(self):
  94. # check that Decimal instances that have different representations
  95. # but equal values give the same hash
  96. zeros = ['0', '-0', '0.0', '-0.0e10', '000e-10']
  97. for zero in zeros:
  98. self.check_equal_hash(D(zero), D(0))
  99. self.check_equal_hash(D('1.00'), D(1))
  100. self.check_equal_hash(D('1.00000'), D(1))
  101. self.check_equal_hash(D('-1.00'), D(-1))
  102. self.check_equal_hash(D('-1.00000'), D(-1))
  103. self.check_equal_hash(D('123e2'), D(12300))
  104. self.check_equal_hash(D('1230e1'), D(12300))
  105. self.check_equal_hash(D('12300'), D(12300))
  106. self.check_equal_hash(D('12300.0'), D(12300))
  107. self.check_equal_hash(D('12300.00'), D(12300))
  108. self.check_equal_hash(D('12300.000'), D(12300))
  109. def test_fractions(self):
  110. # check special case for fractions where either the numerator
  111. # or the denominator is a multiple of _PyHASH_MODULUS
  112. self.assertEqual(hash(F(1, _PyHASH_MODULUS)), _PyHASH_INF)
  113. self.assertEqual(hash(F(-1, 3*_PyHASH_MODULUS)), -_PyHASH_INF)
  114. self.assertEqual(hash(F(7*_PyHASH_MODULUS, 1)), 0)
  115. self.assertEqual(hash(F(-_PyHASH_MODULUS, 1)), 0)
  116. # The numbers ABC doesn't enforce that the "true" division
  117. # of integers produces a float. This tests that the
  118. # Rational.__float__() method has required type conversions.
  119. x = F(DummyIntegral(1), DummyIntegral(2), _normalize=False)
  120. self.assertRaises(TypeError, lambda: x.numerator/x.denominator)
  121. self.assertEqual(float(x), 0.5)
  122. def test_hash_normalization(self):
  123. # Test for a bug encountered while changing long_hash.
  124. #
  125. # Given objects x and y, it should be possible for y's
  126. # __hash__ method to return hash(x) in order to ensure that
  127. # hash(x) == hash(y). But hash(x) is not exactly equal to the
  128. # result of x.__hash__(): there's some internal normalization
  129. # to make sure that the result fits in a C long, and is not
  130. # equal to the invalid hash value -1. This internal
  131. # normalization must therefore not change the result of
  132. # hash(x) for any x.
  133. class HalibutProxy:
  134. def __hash__(self):
  135. return hash('halibut')
  136. def __eq__(self, other):
  137. return other == 'halibut'
  138. x = {'halibut', HalibutProxy()}
  139. self.assertEqual(len(x), 1)
  140. class ComparisonTest(unittest.TestCase):
  141. def test_mixed_comparisons(self):
  142. # ordered list of distinct test values of various types:
  143. # int, float, Fraction, Decimal
  144. test_values = [
  145. float('-inf'),
  146. D('-1e425000000'),
  147. -1e308,
  148. F(-22, 7),
  149. -3.14,
  150. -2,
  151. 0.0,
  152. 1e-320,
  153. True,
  154. F('1.2'),
  155. D('1.3'),
  156. float('1.4'),
  157. F(275807, 195025),
  158. D('1.414213562373095048801688724'),
  159. F(114243, 80782),
  160. F(473596569, 84615),
  161. 7e200,
  162. D('infinity'),
  163. ]
  164. for i, first in enumerate(test_values):
  165. for second in test_values[i+1:]:
  166. self.assertLess(first, second)
  167. self.assertLessEqual(first, second)
  168. self.assertGreater(second, first)
  169. self.assertGreaterEqual(second, first)
  170. def test_complex(self):
  171. # comparisons with complex are special: equality and inequality
  172. # comparisons should always succeed, but order comparisons should
  173. # raise TypeError.
  174. z = 1.0 + 0j
  175. w = -3.14 + 2.7j
  176. for v in 1, 1.0, F(1), D(1), complex(1):
  177. self.assertEqual(z, v)
  178. self.assertEqual(v, z)
  179. for v in 2, 2.0, F(2), D(2), complex(2):
  180. self.assertNotEqual(z, v)
  181. self.assertNotEqual(v, z)
  182. self.assertNotEqual(w, v)
  183. self.assertNotEqual(v, w)
  184. for v in (1, 1.0, F(1), D(1), complex(1),
  185. 2, 2.0, F(2), D(2), complex(2), w):
  186. for op in operator.le, operator.lt, operator.ge, operator.gt:
  187. self.assertRaises(TypeError, op, z, v)
  188. self.assertRaises(TypeError, op, v, z)
  189. if __name__ == '__main__':
  190. unittest.main()