blob: 20abce26df45268bfa9fdd34421f47ba6f9ba33b [file] [log] [blame]
Jeffrey Yasskind7b00332008-01-15 07:46:24 +00001"""Tests for Lib/rational.py."""
2
3from decimal import Decimal
4from test.test_support import run_unittest, verbose
5import math
6import operator
7import rational
8import unittest
Raymond Hettingera6216742008-01-25 00:21:54 +00009from copy import copy, deepcopy
10from cPickle import dumps, loads
Jeffrey Yasskind7b00332008-01-15 07:46:24 +000011R = rational.Rational
12
13def _components(r):
14 return (r.numerator, r.denominator)
15
16class RationalTest(unittest.TestCase):
17
18 def assertTypedEquals(self, expected, actual):
19 """Asserts that both the types and values are the same."""
20 self.assertEquals(type(expected), type(actual))
21 self.assertEquals(expected, actual)
22
23 def assertRaisesMessage(self, exc_type, message,
24 callable, *args, **kwargs):
25 """Asserts that callable(*args, **kwargs) raises exc_type(message)."""
26 try:
27 callable(*args, **kwargs)
28 except exc_type, e:
29 self.assertEquals(message, str(e))
30 else:
31 self.fail("%s not raised" % exc_type.__name__)
32
33 def testInit(self):
34 self.assertEquals((0, 1), _components(R()))
35 self.assertEquals((7, 1), _components(R(7)))
36 self.assertEquals((7, 3), _components(R(R(7, 3))))
37
38 self.assertEquals((-1, 1), _components(R(-1, 1)))
39 self.assertEquals((-1, 1), _components(R(1, -1)))
40 self.assertEquals((1, 1), _components(R(-2, -2)))
41 self.assertEquals((1, 2), _components(R(5, 10)))
42 self.assertEquals((7, 15), _components(R(7, 15)))
43 self.assertEquals((10**23, 1), _components(R(10**23)))
44
45 self.assertRaisesMessage(ZeroDivisionError, "Rational(12, 0)",
46 R, 12, 0)
47 self.assertRaises(TypeError, R, 1.5)
48 self.assertRaises(TypeError, R, 1.5 + 3j)
49
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +000050 self.assertRaises(TypeError, R, R(1, 2), 3)
51 self.assertRaises(TypeError, R, "3/2", 3)
52
53 def testFromString(self):
54 self.assertEquals((5, 1), _components(R("5")))
55 self.assertEquals((3, 2), _components(R("3/2")))
56 self.assertEquals((3, 2), _components(R(" \n +3/2")))
57 self.assertEquals((-3, 2), _components(R("-3/2 ")))
58 self.assertEquals((3, 2), _components(R(" 03/02 \n ")))
59 self.assertEquals((3, 2), _components(R(u" 03/02 \n ")))
60
61 self.assertRaisesMessage(
62 ZeroDivisionError, "Rational(3, 0)",
63 R, "3/0")
64 self.assertRaisesMessage(
65 ValueError, "Invalid literal for Rational: 3/",
66 R, "3/")
67 self.assertRaisesMessage(
68 ValueError, "Invalid literal for Rational: 3 /2",
69 R, "3 /2")
70 self.assertRaisesMessage(
71 # Denominators don't need a sign.
72 ValueError, "Invalid literal for Rational: 3/+2",
73 R, "3/+2")
74 self.assertRaisesMessage(
75 # Imitate float's parsing.
76 ValueError, "Invalid literal for Rational: + 3/2",
77 R, "+ 3/2")
78 self.assertRaisesMessage(
79 # Only parse fractions, not decimals.
80 ValueError, "Invalid literal for Rational: 3.2",
81 R, "3.2")
82
83 def testImmutable(self):
84 r = R(7, 3)
85 r.__init__(2, 15)
86 self.assertEquals((7, 3), _components(r))
87
Jeffrey Yasskind7b00332008-01-15 07:46:24 +000088 def testFromFloat(self):
89 self.assertRaisesMessage(
90 TypeError, "Rational.from_float() only takes floats, not 3 (int)",
91 R.from_float, 3)
92
93 self.assertEquals((0, 1), _components(R.from_float(-0.0)))
94 self.assertEquals((10, 1), _components(R.from_float(10.0)))
95 self.assertEquals((-5, 2), _components(R.from_float(-2.5)))
96 self.assertEquals((99999999999999991611392, 1),
97 _components(R.from_float(1e23)))
98 self.assertEquals(float(10**23), float(R.from_float(1e23)))
99 self.assertEquals((3602879701896397, 1125899906842624),
100 _components(R.from_float(3.2)))
101 self.assertEquals(3.2, float(R.from_float(3.2)))
102
103 inf = 1e1000
104 nan = inf - inf
105 self.assertRaisesMessage(
106 TypeError, "Cannot convert inf to Rational.",
107 R.from_float, inf)
108 self.assertRaisesMessage(
109 TypeError, "Cannot convert -inf to Rational.",
110 R.from_float, -inf)
111 self.assertRaisesMessage(
112 TypeError, "Cannot convert nan to Rational.",
113 R.from_float, nan)
114
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +0000115 def testFromDecimal(self):
116 self.assertRaisesMessage(
117 TypeError,
118 "Rational.from_decimal() only takes Decimals, not 3 (int)",
119 R.from_decimal, 3)
120 self.assertEquals(R(0), R.from_decimal(Decimal("-0")))
121 self.assertEquals(R(5, 10), R.from_decimal(Decimal("0.5")))
122 self.assertEquals(R(5, 1000), R.from_decimal(Decimal("5e-3")))
123 self.assertEquals(R(5000), R.from_decimal(Decimal("5e3")))
124 self.assertEquals(1 - R(1, 10**30),
125 R.from_decimal(Decimal("0." + "9" * 30)))
126
127 self.assertRaisesMessage(
128 TypeError, "Cannot convert Infinity to Rational.",
129 R.from_decimal, Decimal("inf"))
130 self.assertRaisesMessage(
131 TypeError, "Cannot convert -Infinity to Rational.",
132 R.from_decimal, Decimal("-inf"))
133 self.assertRaisesMessage(
134 TypeError, "Cannot convert NaN to Rational.",
135 R.from_decimal, Decimal("nan"))
136 self.assertRaisesMessage(
137 TypeError, "Cannot convert sNaN to Rational.",
138 R.from_decimal, Decimal("snan"))
139
Raymond Hettingercf109262008-01-24 00:54:21 +0000140 def testFromContinuedFraction(self):
141 self.assertRaises(TypeError, R.from_continued_fraction, None)
142 phi = R.from_continued_fraction([1]*100)
143 self.assertEquals(round(phi - (1 + 5 ** 0.5) / 2, 10), 0.0)
144
Raymond Hettingereb461902008-01-24 02:00:25 +0000145 minusphi = R.from_continued_fraction([-1]*100)
146 self.assertEquals(round(minusphi + (1 + 5 ** 0.5) / 2, 10), 0.0)
147
148 self.assertEquals(R.from_continued_fraction([0]), R(0))
149 self.assertEquals(R.from_continued_fraction([]), R(0))
150
Raymond Hettingercf109262008-01-24 00:54:21 +0000151 def testAsContinuedFraction(self):
152 self.assertEqual(R.from_float(math.pi).as_continued_fraction()[:15],
153 [3, 7, 15, 1, 292, 1, 1, 1, 2, 1, 3, 1, 14, 3, 3])
Raymond Hettingereb461902008-01-24 02:00:25 +0000154 self.assertEqual(R.from_float(-math.pi).as_continued_fraction()[:16],
155 [-4, 1, 6, 15, 1, 292, 1, 1, 1, 2, 1, 3, 1, 14, 3, 3])
156 self.assertEqual(R(0).as_continued_fraction(), [0])
Raymond Hettingercf109262008-01-24 00:54:21 +0000157
158 def testApproximateFromFloat(self):
159 self.assertEqual(R.approximate_from_float(math.pi, 10000), R(355, 113))
Raymond Hettingereb461902008-01-24 02:00:25 +0000160 self.assertEqual(R.approximate_from_float(-math.pi, 10000), R(-355, 113))
161 self.assertEqual(R.approximate_from_float(0.0, 10000), R(0))
Raymond Hettingercf109262008-01-24 00:54:21 +0000162
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000163 def testConversions(self):
164 self.assertTypedEquals(-1, trunc(R(-11, 10)))
Raymond Hettinger5b0e27e2008-01-24 19:30:19 +0000165 self.assertTypedEquals(-1, int(R(-11, 10)))
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000166 self.assertTypedEquals(-2, R(-11, 10).__floor__())
167 self.assertTypedEquals(-1, R(-11, 10).__ceil__())
168 self.assertTypedEquals(-1, R(-10, 10).__ceil__())
169
170 self.assertTypedEquals(0, R(-1, 10).__round__())
171 self.assertTypedEquals(0, R(-5, 10).__round__())
172 self.assertTypedEquals(-2, R(-15, 10).__round__())
173 self.assertTypedEquals(-1, R(-7, 10).__round__())
174
175 self.assertEquals(False, bool(R(0, 1)))
176 self.assertEquals(True, bool(R(3, 2)))
177 self.assertTypedEquals(0.1, float(R(1, 10)))
178
179 # Check that __float__ isn't implemented by converting the
180 # numerator and denominator to float before dividing.
181 self.assertRaises(OverflowError, float, long('2'*400+'7'))
182 self.assertAlmostEquals(2.0/3,
183 float(R(long('2'*400+'7'), long('3'*400+'1'))))
184
185 self.assertTypedEquals(0.1+0j, complex(R(1,10)))
186
187 def testRound(self):
188 self.assertTypedEquals(R(-200), R(-150).__round__(-2))
189 self.assertTypedEquals(R(-200), R(-250).__round__(-2))
190 self.assertTypedEquals(R(30), R(26).__round__(-1))
191 self.assertTypedEquals(R(-2, 10), R(-15, 100).__round__(1))
192 self.assertTypedEquals(R(-2, 10), R(-25, 100).__round__(1))
193
194
195 def testArithmetic(self):
196 self.assertEquals(R(1, 2), R(1, 10) + R(2, 5))
197 self.assertEquals(R(-3, 10), R(1, 10) - R(2, 5))
198 self.assertEquals(R(1, 25), R(1, 10) * R(2, 5))
199 self.assertEquals(R(1, 4), R(1, 10) / R(2, 5))
200 self.assertTypedEquals(2, R(9, 10) // R(2, 5))
201 self.assertTypedEquals(10**23, R(10**23, 1) // R(1))
202 self.assertEquals(R(2, 3), R(-7, 3) % R(3, 2))
203 self.assertEquals(R(8, 27), R(2, 3) ** R(3))
204 self.assertEquals(R(27, 8), R(2, 3) ** R(-3))
205 self.assertTypedEquals(2.0, R(4) ** R(1, 2))
206 # Will return 1j in 3.0:
207 self.assertRaises(ValueError, pow, R(-1), R(1, 2))
208
209 def testMixedArithmetic(self):
210 self.assertTypedEquals(R(11, 10), R(1, 10) + 1)
211 self.assertTypedEquals(1.1, R(1, 10) + 1.0)
212 self.assertTypedEquals(1.1 + 0j, R(1, 10) + (1.0 + 0j))
213 self.assertTypedEquals(R(11, 10), 1 + R(1, 10))
214 self.assertTypedEquals(1.1, 1.0 + R(1, 10))
215 self.assertTypedEquals(1.1 + 0j, (1.0 + 0j) + R(1, 10))
216
217 self.assertTypedEquals(R(-9, 10), R(1, 10) - 1)
218 self.assertTypedEquals(-0.9, R(1, 10) - 1.0)
219 self.assertTypedEquals(-0.9 + 0j, R(1, 10) - (1.0 + 0j))
220 self.assertTypedEquals(R(9, 10), 1 - R(1, 10))
221 self.assertTypedEquals(0.9, 1.0 - R(1, 10))
222 self.assertTypedEquals(0.9 + 0j, (1.0 + 0j) - R(1, 10))
223
224 self.assertTypedEquals(R(1, 10), R(1, 10) * 1)
225 self.assertTypedEquals(0.1, R(1, 10) * 1.0)
226 self.assertTypedEquals(0.1 + 0j, R(1, 10) * (1.0 + 0j))
227 self.assertTypedEquals(R(1, 10), 1 * R(1, 10))
228 self.assertTypedEquals(0.1, 1.0 * R(1, 10))
229 self.assertTypedEquals(0.1 + 0j, (1.0 + 0j) * R(1, 10))
230
231 self.assertTypedEquals(R(1, 10), R(1, 10) / 1)
232 self.assertTypedEquals(0.1, R(1, 10) / 1.0)
233 self.assertTypedEquals(0.1 + 0j, R(1, 10) / (1.0 + 0j))
234 self.assertTypedEquals(R(10, 1), 1 / R(1, 10))
235 self.assertTypedEquals(10.0, 1.0 / R(1, 10))
236 self.assertTypedEquals(10.0 + 0j, (1.0 + 0j) / R(1, 10))
237
238 self.assertTypedEquals(0, R(1, 10) // 1)
239 self.assertTypedEquals(0.0, R(1, 10) // 1.0)
240 self.assertTypedEquals(10, 1 // R(1, 10))
241 self.assertTypedEquals(10**23, 10**22 // R(1, 10))
242 self.assertTypedEquals(10.0, 1.0 // R(1, 10))
243
244 self.assertTypedEquals(R(1, 10), R(1, 10) % 1)
245 self.assertTypedEquals(0.1, R(1, 10) % 1.0)
246 self.assertTypedEquals(R(0, 1), 1 % R(1, 10))
247 self.assertTypedEquals(0.0, 1.0 % R(1, 10))
248
249 # No need for divmod since we don't override it.
250
251 # ** has more interesting conversion rules.
252 self.assertTypedEquals(R(100, 1), R(1, 10) ** -2)
253 self.assertTypedEquals(R(100, 1), R(10, 1) ** 2)
254 self.assertTypedEquals(0.1, R(1, 10) ** 1.0)
255 self.assertTypedEquals(0.1 + 0j, R(1, 10) ** (1.0 + 0j))
256 self.assertTypedEquals(4 , 2 ** R(2, 1))
257 # Will return 1j in 3.0:
258 self.assertRaises(ValueError, pow, (-1), R(1, 2))
259 self.assertTypedEquals(R(1, 4) , 2 ** R(-2, 1))
260 self.assertTypedEquals(2.0 , 4 ** R(1, 2))
261 self.assertTypedEquals(0.25, 2.0 ** R(-2, 1))
262 self.assertTypedEquals(1.0 + 0j, (1.0 + 0j) ** R(1, 10))
263
264 def testMixingWithDecimal(self):
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +0000265 # Decimal refuses mixed comparisons.
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000266 self.assertRaisesMessage(
267 TypeError,
268 "unsupported operand type(s) for +: 'Rational' and 'Decimal'",
269 operator.add, R(3,11), Decimal('3.1415926'))
270 self.assertNotEquals(R(5, 2), Decimal('2.5'))
271
272 def testComparisons(self):
273 self.assertTrue(R(1, 2) < R(2, 3))
274 self.assertFalse(R(1, 2) < R(1, 2))
275 self.assertTrue(R(1, 2) <= R(2, 3))
276 self.assertTrue(R(1, 2) <= R(1, 2))
277 self.assertFalse(R(2, 3) <= R(1, 2))
278 self.assertTrue(R(1, 2) == R(1, 2))
279 self.assertFalse(R(1, 2) == R(1, 3))
280
281 def testMixedLess(self):
282 self.assertTrue(2 < R(5, 2))
283 self.assertFalse(2 < R(4, 2))
284 self.assertTrue(R(5, 2) < 3)
285 self.assertFalse(R(4, 2) < 2)
286
287 self.assertTrue(R(1, 2) < 0.6)
288 self.assertFalse(R(1, 2) < 0.4)
289 self.assertTrue(0.4 < R(1, 2))
290 self.assertFalse(0.5 < R(1, 2))
291
292 def testMixedLessEqual(self):
293 self.assertTrue(0.5 <= R(1, 2))
294 self.assertFalse(0.6 <= R(1, 2))
295 self.assertTrue(R(1, 2) <= 0.5)
296 self.assertFalse(R(1, 2) <= 0.4)
297 self.assertTrue(2 <= R(4, 2))
298 self.assertFalse(2 <= R(3, 2))
299 self.assertTrue(R(4, 2) <= 2)
300 self.assertFalse(R(5, 2) <= 2)
301
302 def testBigFloatComparisons(self):
303 # Because 10**23 can't be represented exactly as a float:
304 self.assertFalse(R(10**23) == float(10**23))
305 # The first test demonstrates why these are important.
306 self.assertFalse(1e23 < float(R(trunc(1e23) + 1)))
307 self.assertTrue(1e23 < R(trunc(1e23) + 1))
308 self.assertFalse(1e23 <= R(trunc(1e23) - 1))
309 self.assertTrue(1e23 > R(trunc(1e23) - 1))
310 self.assertFalse(1e23 >= R(trunc(1e23) + 1))
311
312 def testBigComplexComparisons(self):
313 self.assertFalse(R(10**23) == complex(10**23))
314 self.assertTrue(R(10**23) > complex(10**23))
315 self.assertFalse(R(10**23) <= complex(10**23))
316
317 def testMixedEqual(self):
318 self.assertTrue(0.5 == R(1, 2))
319 self.assertFalse(0.6 == R(1, 2))
320 self.assertTrue(R(1, 2) == 0.5)
321 self.assertFalse(R(1, 2) == 0.4)
322 self.assertTrue(2 == R(4, 2))
323 self.assertFalse(2 == R(3, 2))
324 self.assertTrue(R(4, 2) == 2)
325 self.assertFalse(R(5, 2) == 2)
326
327 def testStringification(self):
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +0000328 self.assertEquals("Rational(7,3)", repr(R(7, 3)))
329 self.assertEquals("7/3", str(R(7, 3)))
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000330 self.assertEquals("7", str(R(7, 1)))
331
332 def testHash(self):
333 self.assertEquals(hash(2.5), hash(R(5, 2)))
334 self.assertEquals(hash(10**50), hash(R(10**50)))
335 self.assertNotEquals(hash(float(10**23)), hash(R(10**23)))
336
337 def testApproximatePi(self):
338 # Algorithm borrowed from
339 # http://docs.python.org/lib/decimal-recipes.html
340 three = R(3)
341 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
342 while abs(s - lasts) > R(1, 10**9):
343 lasts = s
344 n, na = n+na, na+8
345 d, da = d+da, da+32
346 t = (t * n) / d
347 s += t
348 self.assertAlmostEquals(math.pi, s)
349
350 def testApproximateCos1(self):
351 # Algorithm borrowed from
352 # http://docs.python.org/lib/decimal-recipes.html
353 x = R(1)
354 i, lasts, s, fact, num, sign = 0, 0, R(1), 1, 1, 1
355 while abs(s - lasts) > R(1, 10**9):
356 lasts = s
357 i += 2
358 fact *= i * (i-1)
359 num *= x * x
360 sign *= -1
361 s += num / fact * sign
362 self.assertAlmostEquals(math.cos(1), s)
363
Raymond Hettingera6216742008-01-25 00:21:54 +0000364 def test_copy_deepcopy_pickle(self):
365 r = R(13, 7)
366 self.assertEqual(r, loads(dumps(r)))
367 self.assertEqual(id(r), id(copy(r)))
368 self.assertEqual(id(r), id(deepcopy(r)))
369
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000370def test_main():
371 run_unittest(RationalTest)
372
373if __name__ == '__main__':
374 test_main()