blob: 26e132f4e564b6f1d4c6105504f66514bf67702c [file] [log] [blame]
Christian Heimes3feef612008-02-11 06:19:17 +00001"""Tests for Lib/fractions.py."""
Guido van Rossum7736b5b2008-01-15 21:44:53 +00002
3from decimal import Decimal
Eric Smith3ab08ca2010-12-04 15:17:38 +00004from test.support import run_unittest, requires_IEEE_754
Guido van Rossum7736b5b2008-01-15 21:44:53 +00005import math
Mark Dickinson85424c92009-07-18 14:41:42 +00006import numbers
Guido van Rossum7736b5b2008-01-15 21:44:53 +00007import operator
Christian Heimes3feef612008-02-11 06:19:17 +00008import fractions
Guido van Rossum7736b5b2008-01-15 21:44:53 +00009import unittest
Christian Heimes969fe572008-01-25 11:23:10 +000010from copy import copy, deepcopy
Neal Norwitz6ff93fe2008-01-26 21:52:30 +000011from pickle import dumps, loads
Christian Heimes68f5fbe2008-02-14 08:27:37 +000012F = fractions.Fraction
Christian Heimes3feef612008-02-11 06:19:17 +000013gcd = fractions.gcd
Christian Heimesaf98da12008-01-27 15:18:18 +000014
Mark Dickinson85424c92009-07-18 14:41:42 +000015class DummyFloat(object):
16 """Dummy float class for testing comparisons with Fractions"""
17
18 def __init__(self, value):
19 if not isinstance(value, float):
20 raise TypeError("DummyFloat can only be initialized from float")
21 self.value = value
22
23 def _richcmp(self, other, op):
24 if isinstance(other, numbers.Rational):
25 return op(F.from_float(self.value), other)
26 elif isinstance(other, DummyFloat):
27 return op(self.value, other.value)
28 else:
29 return NotImplemented
30
31 def __eq__(self, other): return self._richcmp(other, operator.eq)
32 def __le__(self, other): return self._richcmp(other, operator.le)
33 def __lt__(self, other): return self._richcmp(other, operator.lt)
34 def __ge__(self, other): return self._richcmp(other, operator.ge)
35 def __gt__(self, other): return self._richcmp(other, operator.gt)
36
37 # shouldn't be calling __float__ at all when doing comparisons
38 def __float__(self):
39 assert False, "__float__ should not be invoked for comparisons"
40
41 # same goes for subtraction
42 def __sub__(self, other):
43 assert False, "__sub__ should not be invoked for comparisons"
44 __rsub__ = __sub__
45
46
47class DummyRational(object):
48 """Test comparison of Fraction with a naive rational implementation."""
49
50 def __init__(self, num, den):
51 g = gcd(num, den)
52 self.num = num // g
53 self.den = den // g
54
55 def __eq__(self, other):
56 if isinstance(other, fractions.Fraction):
57 return (self.num == other._numerator and
58 self.den == other._denominator)
59 else:
60 return NotImplemented
61
62 def __lt__(self, other):
63 return(self.num * other._denominator < self.den * other._numerator)
64
65 def __gt__(self, other):
66 return(self.num * other._denominator > self.den * other._numerator)
67
68 def __le__(self, other):
69 return(self.num * other._denominator <= self.den * other._numerator)
70
71 def __ge__(self, other):
72 return(self.num * other._denominator >= self.den * other._numerator)
73
74 # this class is for testing comparisons; conversion to float
75 # should never be used for a comparison, since it loses accuracy
76 def __float__(self):
77 assert False, "__float__ should not be invoked"
Christian Heimesaf98da12008-01-27 15:18:18 +000078
79class GcdTest(unittest.TestCase):
80
81 def testMisc(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +000082 self.assertEqual(0, gcd(0, 0))
83 self.assertEqual(1, gcd(1, 0))
84 self.assertEqual(-1, gcd(-1, 0))
85 self.assertEqual(1, gcd(0, 1))
86 self.assertEqual(-1, gcd(0, -1))
87 self.assertEqual(1, gcd(7, 1))
88 self.assertEqual(-1, gcd(7, -1))
89 self.assertEqual(1, gcd(-23, 15))
90 self.assertEqual(12, gcd(120, 84))
91 self.assertEqual(-12, gcd(84, -120))
Christian Heimesaf98da12008-01-27 15:18:18 +000092
Guido van Rossum7736b5b2008-01-15 21:44:53 +000093
94def _components(r):
95 return (r.numerator, r.denominator)
96
Christian Heimesaf98da12008-01-27 15:18:18 +000097
Christian Heimes3feef612008-02-11 06:19:17 +000098class FractionTest(unittest.TestCase):
Guido van Rossum7736b5b2008-01-15 21:44:53 +000099
100 def assertTypedEquals(self, expected, actual):
101 """Asserts that both the types and values are the same."""
Ezio Melottib3aedd42010-11-20 19:04:17 +0000102 self.assertEqual(type(expected), type(actual))
103 self.assertEqual(expected, actual)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000104
105 def assertRaisesMessage(self, exc_type, message,
106 callable, *args, **kwargs):
107 """Asserts that callable(*args, **kwargs) raises exc_type(message)."""
108 try:
109 callable(*args, **kwargs)
110 except exc_type as e:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000111 self.assertEqual(message, str(e))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000112 else:
113 self.fail("%s not raised" % exc_type.__name__)
114
115 def testInit(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000116 self.assertEqual((0, 1), _components(F()))
117 self.assertEqual((7, 1), _components(F(7)))
118 self.assertEqual((7, 3), _components(F(F(7, 3))))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000119
Ezio Melottib3aedd42010-11-20 19:04:17 +0000120 self.assertEqual((-1, 1), _components(F(-1, 1)))
121 self.assertEqual((-1, 1), _components(F(1, -1)))
122 self.assertEqual((1, 1), _components(F(-2, -2)))
123 self.assertEqual((1, 2), _components(F(5, 10)))
124 self.assertEqual((7, 15), _components(F(7, 15)))
125 self.assertEqual((10**23, 1), _components(F(10**23)))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000126
Ezio Melottib3aedd42010-11-20 19:04:17 +0000127 self.assertEqual((3, 77), _components(F(F(3, 7), 11)))
128 self.assertEqual((-9, 5), _components(F(2, F(-10, 9))))
129 self.assertEqual((2486, 2485), _components(F(F(22, 7), F(355, 113))))
Mark Dickinsond4d95f82009-04-24 14:06:19 +0000130
Christian Heimes3feef612008-02-11 06:19:17 +0000131 self.assertRaisesMessage(ZeroDivisionError, "Fraction(12, 0)",
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000132 F, 12, 0)
Georg Brandl86b2fb92008-07-16 03:43:04 +0000133 self.assertRaises(TypeError, F, 1.5 + 3j)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000134
Georg Brandl86b2fb92008-07-16 03:43:04 +0000135 self.assertRaises(TypeError, F, "3/2", 3)
Mark Dickinsond4d95f82009-04-24 14:06:19 +0000136 self.assertRaises(TypeError, F, 3, 0j)
137 self.assertRaises(TypeError, F, 3, 1j)
138
Mark Dickinson98127c32010-04-03 11:18:52 +0000139 @requires_IEEE_754
140 def testInitFromFloat(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000141 self.assertEqual((5, 2), _components(F(2.5)))
142 self.assertEqual((0, 1), _components(F(-0.0)))
143 self.assertEqual((3602879701896397, 36028797018963968),
144 _components(F(0.1)))
Mark Dickinson98127c32010-04-03 11:18:52 +0000145 self.assertRaises(TypeError, F, float('nan'))
146 self.assertRaises(TypeError, F, float('inf'))
147 self.assertRaises(TypeError, F, float('-inf'))
148
149 def testInitFromDecimal(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000150 self.assertEqual((11, 10),
151 _components(F(Decimal('1.1'))))
152 self.assertEqual((7, 200),
153 _components(F(Decimal('3.5e-2'))))
154 self.assertEqual((0, 1),
155 _components(F(Decimal('.000e20'))))
Mark Dickinson98127c32010-04-03 11:18:52 +0000156 self.assertRaises(TypeError, F, Decimal('nan'))
157 self.assertRaises(TypeError, F, Decimal('snan'))
158 self.assertRaises(TypeError, F, Decimal('inf'))
159 self.assertRaises(TypeError, F, Decimal('-inf'))
Christian Heimes587c2bf2008-01-19 16:21:02 +0000160
161 def testFromString(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000162 self.assertEqual((5, 1), _components(F("5")))
163 self.assertEqual((3, 2), _components(F("3/2")))
164 self.assertEqual((3, 2), _components(F(" \n +3/2")))
165 self.assertEqual((-3, 2), _components(F("-3/2 ")))
166 self.assertEqual((13, 2), _components(F(" 013/02 \n ")))
167 self.assertEqual((16, 5), _components(F(" 3.2 ")))
168 self.assertEqual((-16, 5), _components(F(" -3.2 ")))
169 self.assertEqual((-3, 1), _components(F(" -3. ")))
170 self.assertEqual((3, 5), _components(F(" .6 ")))
171 self.assertEqual((1, 3125), _components(F("32.e-5")))
172 self.assertEqual((1000000, 1), _components(F("1E+06")))
173 self.assertEqual((-12300, 1), _components(F("-1.23e4")))
174 self.assertEqual((0, 1), _components(F(" .0e+0\t")))
175 self.assertEqual((0, 1), _components(F("-0.000e0")))
Christian Heimes587c2bf2008-01-19 16:21:02 +0000176
177 self.assertRaisesMessage(
Christian Heimes3feef612008-02-11 06:19:17 +0000178 ZeroDivisionError, "Fraction(3, 0)",
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000179 F, "3/0")
Christian Heimes587c2bf2008-01-19 16:21:02 +0000180 self.assertRaisesMessage(
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000181 ValueError, "Invalid literal for Fraction: '3/'",
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000182 F, "3/")
Christian Heimes587c2bf2008-01-19 16:21:02 +0000183 self.assertRaisesMessage(
Mark Dickinsoncf63f2f2009-04-22 17:50:21 +0000184 ValueError, "Invalid literal for Fraction: '/2'",
185 F, "/2")
186 self.assertRaisesMessage(
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000187 ValueError, "Invalid literal for Fraction: '3 /2'",
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000188 F, "3 /2")
Christian Heimes587c2bf2008-01-19 16:21:02 +0000189 self.assertRaisesMessage(
190 # Denominators don't need a sign.
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000191 ValueError, "Invalid literal for Fraction: '3/+2'",
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000192 F, "3/+2")
Christian Heimes587c2bf2008-01-19 16:21:02 +0000193 self.assertRaisesMessage(
194 # Imitate float's parsing.
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000195 ValueError, "Invalid literal for Fraction: '+ 3/2'",
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000196 F, "+ 3/2")
Christian Heimes587c2bf2008-01-19 16:21:02 +0000197 self.assertRaisesMessage(
Christian Heimesaf98da12008-01-27 15:18:18 +0000198 # Avoid treating '.' as a regex special character.
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000199 ValueError, "Invalid literal for Fraction: '3a2'",
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000200 F, "3a2")
Christian Heimesaf98da12008-01-27 15:18:18 +0000201 self.assertRaisesMessage(
Christian Heimesaf98da12008-01-27 15:18:18 +0000202 # Don't accept combinations of decimals and rationals.
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000203 ValueError, "Invalid literal for Fraction: '3/7.2'",
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000204 F, "3/7.2")
Christian Heimesaf98da12008-01-27 15:18:18 +0000205 self.assertRaisesMessage(
206 # Don't accept combinations of decimals and rationals.
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000207 ValueError, "Invalid literal for Fraction: '3.2/7'",
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000208 F, "3.2/7")
Christian Heimes292d3512008-02-03 16:51:08 +0000209 self.assertRaisesMessage(
210 # Allow 3. and .3, but not .
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000211 ValueError, "Invalid literal for Fraction: '.'",
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000212 F, ".")
Christian Heimes587c2bf2008-01-19 16:21:02 +0000213
214 def testImmutable(self):
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000215 r = F(7, 3)
Christian Heimes587c2bf2008-01-19 16:21:02 +0000216 r.__init__(2, 15)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000217 self.assertEqual((7, 3), _components(r))
Christian Heimes587c2bf2008-01-19 16:21:02 +0000218
Christian Heimes400adb02008-02-01 08:12:03 +0000219 self.assertRaises(AttributeError, setattr, r, 'numerator', 12)
220 self.assertRaises(AttributeError, setattr, r, 'denominator', 6)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000221 self.assertEqual((7, 3), _components(r))
Christian Heimes400adb02008-02-01 08:12:03 +0000222
223 # But if you _really_ need to:
224 r._numerator = 4
225 r._denominator = 2
Ezio Melottib3aedd42010-11-20 19:04:17 +0000226 self.assertEqual((4, 2), _components(r))
Christian Heimes400adb02008-02-01 08:12:03 +0000227 # Which breaks some important operations:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000228 self.assertNotEqual(F(4, 2), r)
Christian Heimes400adb02008-02-01 08:12:03 +0000229
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000230 def testFromFloat(self):
Georg Brandl2ee470f2008-07-16 12:55:28 +0000231 self.assertRaises(TypeError, F.from_float, 3+4j)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000232 self.assertEqual((10, 1), _components(F.from_float(10)))
Georg Brandl3a9b0622009-01-03 22:07:57 +0000233 bigint = 1234567890123456789
Ezio Melottib3aedd42010-11-20 19:04:17 +0000234 self.assertEqual((bigint, 1), _components(F.from_float(bigint)))
235 self.assertEqual((0, 1), _components(F.from_float(-0.0)))
236 self.assertEqual((10, 1), _components(F.from_float(10.0)))
237 self.assertEqual((-5, 2), _components(F.from_float(-2.5)))
238 self.assertEqual((99999999999999991611392, 1),
239 _components(F.from_float(1e23)))
240 self.assertEqual(float(10**23), float(F.from_float(1e23)))
241 self.assertEqual((3602879701896397, 1125899906842624),
242 _components(F.from_float(3.2)))
243 self.assertEqual(3.2, float(F.from_float(3.2)))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000244
245 inf = 1e1000
246 nan = inf - inf
247 self.assertRaisesMessage(
Christian Heimes3feef612008-02-11 06:19:17 +0000248 TypeError, "Cannot convert inf to Fraction.",
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000249 F.from_float, inf)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000250 self.assertRaisesMessage(
Christian Heimes3feef612008-02-11 06:19:17 +0000251 TypeError, "Cannot convert -inf to Fraction.",
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000252 F.from_float, -inf)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000253 self.assertRaisesMessage(
Christian Heimes3feef612008-02-11 06:19:17 +0000254 TypeError, "Cannot convert nan to Fraction.",
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000255 F.from_float, nan)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000256
Christian Heimes587c2bf2008-01-19 16:21:02 +0000257 def testFromDecimal(self):
Georg Brandl2ee470f2008-07-16 12:55:28 +0000258 self.assertRaises(TypeError, F.from_decimal, 3+4j)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000259 self.assertEqual(F(10, 1), F.from_decimal(10))
260 self.assertEqual(F(0), F.from_decimal(Decimal("-0")))
261 self.assertEqual(F(5, 10), F.from_decimal(Decimal("0.5")))
262 self.assertEqual(F(5, 1000), F.from_decimal(Decimal("5e-3")))
263 self.assertEqual(F(5000), F.from_decimal(Decimal("5e3")))
264 self.assertEqual(1 - F(1, 10**30),
265 F.from_decimal(Decimal("0." + "9" * 30)))
Christian Heimes587c2bf2008-01-19 16:21:02 +0000266
267 self.assertRaisesMessage(
Christian Heimes3feef612008-02-11 06:19:17 +0000268 TypeError, "Cannot convert Infinity to Fraction.",
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000269 F.from_decimal, Decimal("inf"))
Christian Heimes587c2bf2008-01-19 16:21:02 +0000270 self.assertRaisesMessage(
Christian Heimes3feef612008-02-11 06:19:17 +0000271 TypeError, "Cannot convert -Infinity to Fraction.",
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000272 F.from_decimal, Decimal("-inf"))
Christian Heimes587c2bf2008-01-19 16:21:02 +0000273 self.assertRaisesMessage(
Christian Heimes3feef612008-02-11 06:19:17 +0000274 TypeError, "Cannot convert NaN to Fraction.",
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000275 F.from_decimal, Decimal("nan"))
Christian Heimes587c2bf2008-01-19 16:21:02 +0000276 self.assertRaisesMessage(
Christian Heimes3feef612008-02-11 06:19:17 +0000277 TypeError, "Cannot convert sNaN to Fraction.",
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000278 F.from_decimal, Decimal("snan"))
Christian Heimes587c2bf2008-01-19 16:21:02 +0000279
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000280 def testLimitDenominator(self):
281 rpi = F('3.1415926535897932')
282 self.assertEqual(rpi.limit_denominator(10000), F(355, 113))
283 self.assertEqual(-rpi.limit_denominator(10000), F(-355, 113))
284 self.assertEqual(rpi.limit_denominator(113), F(355, 113))
285 self.assertEqual(rpi.limit_denominator(112), F(333, 106))
286 self.assertEqual(F(201, 200).limit_denominator(100), F(1))
287 self.assertEqual(F(201, 200).limit_denominator(101), F(102, 101))
288 self.assertEqual(F(0).limit_denominator(10000), F(0))
Christian Heimesbbffeb62008-01-24 09:42:52 +0000289
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000290 def testConversions(self):
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000291 self.assertTypedEquals(-1, math.trunc(F(-11, 10)))
292 self.assertTypedEquals(-2, math.floor(F(-11, 10)))
293 self.assertTypedEquals(-1, math.ceil(F(-11, 10)))
294 self.assertTypedEquals(-1, math.ceil(F(-10, 10)))
295 self.assertTypedEquals(-1, int(F(-11, 10)))
296 self.assertTypedEquals(0, round(F(-1, 10)))
297 self.assertTypedEquals(0, round(F(-5, 10)))
298 self.assertTypedEquals(-2, round(F(-15, 10)))
299 self.assertTypedEquals(-1, round(F(-7, 10)))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000300
Ezio Melottib3aedd42010-11-20 19:04:17 +0000301 self.assertEqual(False, bool(F(0, 1)))
302 self.assertEqual(True, bool(F(3, 2)))
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000303 self.assertTypedEquals(0.1, float(F(1, 10)))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000304
305 # Check that __float__ isn't implemented by converting the
306 # numerator and denominator to float before dividing.
307 self.assertRaises(OverflowError, float, int('2'*400+'7'))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000308 self.assertAlmostEqual(2.0/3,
309 float(F(int('2'*400+'7'), int('3'*400+'1'))))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000310
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000311 self.assertTypedEquals(0.1+0j, complex(F(1,10)))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000312
313 def testRound(self):
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000314 self.assertTypedEquals(F(-200), round(F(-150), -2))
315 self.assertTypedEquals(F(-200), round(F(-250), -2))
316 self.assertTypedEquals(F(30), round(F(26), -1))
317 self.assertTypedEquals(F(-2, 10), round(F(-15, 100), 1))
318 self.assertTypedEquals(F(-2, 10), round(F(-25, 100), 1))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000319
320
321 def testArithmetic(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000322 self.assertEqual(F(1, 2), F(1, 10) + F(2, 5))
323 self.assertEqual(F(-3, 10), F(1, 10) - F(2, 5))
324 self.assertEqual(F(1, 25), F(1, 10) * F(2, 5))
325 self.assertEqual(F(1, 4), F(1, 10) / F(2, 5))
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000326 self.assertTypedEquals(2, F(9, 10) // F(2, 5))
327 self.assertTypedEquals(10**23, F(10**23, 1) // F(1))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000328 self.assertEqual(F(2, 3), F(-7, 3) % F(3, 2))
329 self.assertEqual(F(8, 27), F(2, 3) ** F(3))
330 self.assertEqual(F(27, 8), F(2, 3) ** F(-3))
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000331 self.assertTypedEquals(2.0, F(4) ** F(1, 2))
332 z = pow(F(-1), F(1, 2))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000333 self.assertAlmostEqual(z.real, 0)
334 self.assertEqual(z.imag, 1)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000335
336 def testMixedArithmetic(self):
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000337 self.assertTypedEquals(F(11, 10), F(1, 10) + 1)
338 self.assertTypedEquals(1.1, F(1, 10) + 1.0)
339 self.assertTypedEquals(1.1 + 0j, F(1, 10) + (1.0 + 0j))
340 self.assertTypedEquals(F(11, 10), 1 + F(1, 10))
341 self.assertTypedEquals(1.1, 1.0 + F(1, 10))
342 self.assertTypedEquals(1.1 + 0j, (1.0 + 0j) + F(1, 10))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000343
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000344 self.assertTypedEquals(F(-9, 10), F(1, 10) - 1)
345 self.assertTypedEquals(-0.9, F(1, 10) - 1.0)
346 self.assertTypedEquals(-0.9 + 0j, F(1, 10) - (1.0 + 0j))
347 self.assertTypedEquals(F(9, 10), 1 - F(1, 10))
348 self.assertTypedEquals(0.9, 1.0 - F(1, 10))
349 self.assertTypedEquals(0.9 + 0j, (1.0 + 0j) - F(1, 10))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000350
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000351 self.assertTypedEquals(F(1, 10), F(1, 10) * 1)
352 self.assertTypedEquals(0.1, F(1, 10) * 1.0)
353 self.assertTypedEquals(0.1 + 0j, F(1, 10) * (1.0 + 0j))
354 self.assertTypedEquals(F(1, 10), 1 * F(1, 10))
355 self.assertTypedEquals(0.1, 1.0 * F(1, 10))
356 self.assertTypedEquals(0.1 + 0j, (1.0 + 0j) * F(1, 10))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000357
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000358 self.assertTypedEquals(F(1, 10), F(1, 10) / 1)
359 self.assertTypedEquals(0.1, F(1, 10) / 1.0)
360 self.assertTypedEquals(0.1 + 0j, F(1, 10) / (1.0 + 0j))
361 self.assertTypedEquals(F(10, 1), 1 / F(1, 10))
362 self.assertTypedEquals(10.0, 1.0 / F(1, 10))
363 self.assertTypedEquals(10.0 + 0j, (1.0 + 0j) / F(1, 10))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000364
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000365 self.assertTypedEquals(0, F(1, 10) // 1)
366 self.assertTypedEquals(0, F(1, 10) // 1.0)
367 self.assertTypedEquals(10, 1 // F(1, 10))
368 self.assertTypedEquals(10**23, 10**22 // F(1, 10))
369 self.assertTypedEquals(10, 1.0 // F(1, 10))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000370
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000371 self.assertTypedEquals(F(1, 10), F(1, 10) % 1)
372 self.assertTypedEquals(0.1, F(1, 10) % 1.0)
373 self.assertTypedEquals(F(0, 1), 1 % F(1, 10))
374 self.assertTypedEquals(0.0, 1.0 % F(1, 10))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000375
376 # No need for divmod since we don't override it.
377
378 # ** has more interesting conversion rules.
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000379 self.assertTypedEquals(F(100, 1), F(1, 10) ** -2)
380 self.assertTypedEquals(F(100, 1), F(10, 1) ** 2)
381 self.assertTypedEquals(0.1, F(1, 10) ** 1.0)
382 self.assertTypedEquals(0.1 + 0j, F(1, 10) ** (1.0 + 0j))
383 self.assertTypedEquals(4 , 2 ** F(2, 1))
384 z = pow(-1, F(1, 2))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000385 self.assertAlmostEqual(0, z.real)
386 self.assertEqual(1, z.imag)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000387 self.assertTypedEquals(F(1, 4) , 2 ** F(-2, 1))
388 self.assertTypedEquals(2.0 , 4 ** F(1, 2))
389 self.assertTypedEquals(0.25, 2.0 ** F(-2, 1))
390 self.assertTypedEquals(1.0 + 0j, (1.0 + 0j) ** F(1, 10))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000391
392 def testMixingWithDecimal(self):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000393 # Decimal refuses mixed arithmetic (but not mixed comparisons)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000394 self.assertRaisesMessage(
395 TypeError,
Christian Heimes3feef612008-02-11 06:19:17 +0000396 "unsupported operand type(s) for +: 'Fraction' and 'Decimal'",
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000397 operator.add, F(3,11), Decimal('3.1415926'))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000398
399 def testComparisons(self):
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000400 self.assertTrue(F(1, 2) < F(2, 3))
401 self.assertFalse(F(1, 2) < F(1, 2))
402 self.assertTrue(F(1, 2) <= F(2, 3))
403 self.assertTrue(F(1, 2) <= F(1, 2))
404 self.assertFalse(F(2, 3) <= F(1, 2))
405 self.assertTrue(F(1, 2) == F(1, 2))
406 self.assertFalse(F(1, 2) == F(1, 3))
407 self.assertFalse(F(1, 2) != F(1, 2))
408 self.assertTrue(F(1, 2) != F(1, 3))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000409
Mark Dickinson85424c92009-07-18 14:41:42 +0000410 def testComparisonsDummyRational(self):
411 self.assertTrue(F(1, 2) == DummyRational(1, 2))
412 self.assertTrue(DummyRational(1, 2) == F(1, 2))
413 self.assertFalse(F(1, 2) == DummyRational(3, 4))
414 self.assertFalse(DummyRational(3, 4) == F(1, 2))
415
416 self.assertTrue(F(1, 2) < DummyRational(3, 4))
417 self.assertFalse(F(1, 2) < DummyRational(1, 2))
418 self.assertFalse(F(1, 2) < DummyRational(1, 7))
419 self.assertFalse(F(1, 2) > DummyRational(3, 4))
420 self.assertFalse(F(1, 2) > DummyRational(1, 2))
421 self.assertTrue(F(1, 2) > DummyRational(1, 7))
422 self.assertTrue(F(1, 2) <= DummyRational(3, 4))
423 self.assertTrue(F(1, 2) <= DummyRational(1, 2))
424 self.assertFalse(F(1, 2) <= DummyRational(1, 7))
425 self.assertFalse(F(1, 2) >= DummyRational(3, 4))
426 self.assertTrue(F(1, 2) >= DummyRational(1, 2))
427 self.assertTrue(F(1, 2) >= DummyRational(1, 7))
428
429 self.assertTrue(DummyRational(1, 2) < F(3, 4))
430 self.assertFalse(DummyRational(1, 2) < F(1, 2))
431 self.assertFalse(DummyRational(1, 2) < F(1, 7))
432 self.assertFalse(DummyRational(1, 2) > F(3, 4))
433 self.assertFalse(DummyRational(1, 2) > F(1, 2))
434 self.assertTrue(DummyRational(1, 2) > F(1, 7))
435 self.assertTrue(DummyRational(1, 2) <= F(3, 4))
436 self.assertTrue(DummyRational(1, 2) <= F(1, 2))
437 self.assertFalse(DummyRational(1, 2) <= F(1, 7))
438 self.assertFalse(DummyRational(1, 2) >= F(3, 4))
439 self.assertTrue(DummyRational(1, 2) >= F(1, 2))
440 self.assertTrue(DummyRational(1, 2) >= F(1, 7))
441
442 def testComparisonsDummyFloat(self):
443 x = DummyFloat(1./3.)
444 y = F(1, 3)
445 self.assertTrue(x != y)
446 self.assertTrue(x < y or x > y)
447 self.assertFalse(x == y)
448 self.assertFalse(x <= y and x >= y)
449 self.assertTrue(y != x)
450 self.assertTrue(y < x or y > x)
451 self.assertFalse(y == x)
452 self.assertFalse(y <= x and y >= x)
453
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000454 def testMixedLess(self):
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000455 self.assertTrue(2 < F(5, 2))
456 self.assertFalse(2 < F(4, 2))
457 self.assertTrue(F(5, 2) < 3)
458 self.assertFalse(F(4, 2) < 2)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000459
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000460 self.assertTrue(F(1, 2) < 0.6)
461 self.assertFalse(F(1, 2) < 0.4)
462 self.assertTrue(0.4 < F(1, 2))
463 self.assertFalse(0.5 < F(1, 2))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000464
Mark Dickinson85424c92009-07-18 14:41:42 +0000465 self.assertFalse(float('inf') < F(1, 2))
466 self.assertTrue(float('-inf') < F(0, 10))
467 self.assertFalse(float('nan') < F(-3, 7))
468 self.assertTrue(F(1, 2) < float('inf'))
469 self.assertFalse(F(17, 12) < float('-inf'))
470 self.assertFalse(F(144, -89) < float('nan'))
471
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000472 def testMixedLessEqual(self):
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000473 self.assertTrue(0.5 <= F(1, 2))
474 self.assertFalse(0.6 <= F(1, 2))
475 self.assertTrue(F(1, 2) <= 0.5)
476 self.assertFalse(F(1, 2) <= 0.4)
477 self.assertTrue(2 <= F(4, 2))
478 self.assertFalse(2 <= F(3, 2))
479 self.assertTrue(F(4, 2) <= 2)
480 self.assertFalse(F(5, 2) <= 2)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000481
Mark Dickinson85424c92009-07-18 14:41:42 +0000482 self.assertFalse(float('inf') <= F(1, 2))
483 self.assertTrue(float('-inf') <= F(0, 10))
484 self.assertFalse(float('nan') <= F(-3, 7))
485 self.assertTrue(F(1, 2) <= float('inf'))
486 self.assertFalse(F(17, 12) <= float('-inf'))
487 self.assertFalse(F(144, -89) <= float('nan'))
488
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000489 def testBigFloatComparisons(self):
490 # Because 10**23 can't be represented exactly as a float:
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000491 self.assertFalse(F(10**23) == float(10**23))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000492 # The first test demonstrates why these are important.
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000493 self.assertFalse(1e23 < float(F(math.trunc(1e23) + 1)))
494 self.assertTrue(1e23 < F(math.trunc(1e23) + 1))
495 self.assertFalse(1e23 <= F(math.trunc(1e23) - 1))
496 self.assertTrue(1e23 > F(math.trunc(1e23) - 1))
497 self.assertFalse(1e23 >= F(math.trunc(1e23) + 1))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000498
499 def testBigComplexComparisons(self):
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000500 self.assertFalse(F(10**23) == complex(10**23))
Mark Dickinson327f02c2010-03-27 11:11:13 +0000501 self.assertRaises(TypeError, operator.gt, F(10**23), complex(10**23))
502 self.assertRaises(TypeError, operator.le, F(10**23), complex(10**23))
503
504 x = F(3, 8)
505 z = complex(0.375, 0.0)
506 w = complex(0.375, 0.2)
507 self.assertTrue(x == z)
508 self.assertFalse(x != z)
509 self.assertFalse(x == w)
510 self.assertTrue(x != w)
511 for op in operator.lt, operator.le, operator.gt, operator.ge:
512 self.assertRaises(TypeError, op, x, z)
513 self.assertRaises(TypeError, op, z, x)
514 self.assertRaises(TypeError, op, x, w)
515 self.assertRaises(TypeError, op, w, x)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000516
517 def testMixedEqual(self):
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000518 self.assertTrue(0.5 == F(1, 2))
519 self.assertFalse(0.6 == F(1, 2))
520 self.assertTrue(F(1, 2) == 0.5)
521 self.assertFalse(F(1, 2) == 0.4)
522 self.assertTrue(2 == F(4, 2))
523 self.assertFalse(2 == F(3, 2))
524 self.assertTrue(F(4, 2) == 2)
525 self.assertFalse(F(5, 2) == 2)
Mark Dickinson85424c92009-07-18 14:41:42 +0000526 self.assertFalse(F(5, 2) == float('nan'))
527 self.assertFalse(float('nan') == F(3, 7))
528 self.assertFalse(F(5, 2) == float('inf'))
529 self.assertFalse(float('-inf') == F(2, 5))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000530
531 def testStringification(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000532 self.assertEqual("Fraction(7, 3)", repr(F(7, 3)))
533 self.assertEqual("Fraction(6283185307, 2000000000)",
534 repr(F('3.1415926535')))
535 self.assertEqual("Fraction(-1, 100000000000000000000)",
536 repr(F(1, -10**20)))
537 self.assertEqual("7/3", str(F(7, 3)))
538 self.assertEqual("7", str(F(7, 1)))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000539
540 def testHash(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000541 self.assertEqual(hash(2.5), hash(F(5, 2)))
542 self.assertEqual(hash(10**50), hash(F(10**50)))
543 self.assertNotEqual(hash(float(10**23)), hash(F(10**23)))
Mark Dickinsonfec66202010-11-13 10:27:38 +0000544 # Check that __hash__ produces the same value as hash(), for
545 # consistency with int and Decimal. (See issue #10356.)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000546 self.assertEqual(hash(F(-1)), F(-1).__hash__())
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000547
548 def testApproximatePi(self):
549 # Algorithm borrowed from
550 # http://docs.python.org/lib/decimal-recipes.html
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000551 three = F(3)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000552 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000553 while abs(s - lasts) > F(1, 10**9):
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000554 lasts = s
555 n, na = n+na, na+8
556 d, da = d+da, da+32
557 t = (t * n) / d
558 s += t
Ezio Melottib3aedd42010-11-20 19:04:17 +0000559 self.assertAlmostEqual(math.pi, s)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000560
561 def testApproximateCos1(self):
562 # Algorithm borrowed from
563 # http://docs.python.org/lib/decimal-recipes.html
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000564 x = F(1)
565 i, lasts, s, fact, num, sign = 0, 0, F(1), 1, 1, 1
566 while abs(s - lasts) > F(1, 10**9):
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000567 lasts = s
568 i += 2
569 fact *= i * (i-1)
570 num *= x * x
571 sign *= -1
572 s += num / fact * sign
Ezio Melottib3aedd42010-11-20 19:04:17 +0000573 self.assertAlmostEqual(math.cos(1), s)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000574
Christian Heimes969fe572008-01-25 11:23:10 +0000575 def test_copy_deepcopy_pickle(self):
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000576 r = F(13, 7)
Christian Heimes969fe572008-01-25 11:23:10 +0000577 self.assertEqual(r, loads(dumps(r)))
578 self.assertEqual(id(r), id(copy(r)))
579 self.assertEqual(id(r), id(deepcopy(r)))
580
Mark Dickinsonc28ad272009-02-12 17:58:36 +0000581 def test_slots(self):
582 # Issue 4998
583 r = F(13, 7)
584 self.assertRaises(AttributeError, setattr, r, 'a', 10)
585
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000586def test_main():
Christian Heimes3feef612008-02-11 06:19:17 +0000587 run_unittest(FractionTest, GcdTest)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000588
589if __name__ == '__main__':
590 test_main()