blob: 084ae0cce5dd56adad0518f99798e6d2d2cd205f [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
Ezio Melotti682d3742012-02-29 14:05:53 +02009import sys
Guido van Rossum7736b5b2008-01-15 21:44:53 +000010import unittest
Christian Heimes969fe572008-01-25 11:23:10 +000011from copy import copy, deepcopy
Neal Norwitz6ff93fe2008-01-26 21:52:30 +000012from pickle import dumps, loads
Christian Heimes68f5fbe2008-02-14 08:27:37 +000013F = fractions.Fraction
Christian Heimes3feef612008-02-11 06:19:17 +000014gcd = fractions.gcd
Christian Heimesaf98da12008-01-27 15:18:18 +000015
Mark Dickinson85424c92009-07-18 14:41:42 +000016class DummyFloat(object):
17 """Dummy float class for testing comparisons with Fractions"""
18
19 def __init__(self, value):
20 if not isinstance(value, float):
21 raise TypeError("DummyFloat can only be initialized from float")
22 self.value = value
23
24 def _richcmp(self, other, op):
25 if isinstance(other, numbers.Rational):
26 return op(F.from_float(self.value), other)
27 elif isinstance(other, DummyFloat):
28 return op(self.value, other.value)
29 else:
30 return NotImplemented
31
32 def __eq__(self, other): return self._richcmp(other, operator.eq)
33 def __le__(self, other): return self._richcmp(other, operator.le)
34 def __lt__(self, other): return self._richcmp(other, operator.lt)
35 def __ge__(self, other): return self._richcmp(other, operator.ge)
36 def __gt__(self, other): return self._richcmp(other, operator.gt)
37
38 # shouldn't be calling __float__ at all when doing comparisons
39 def __float__(self):
40 assert False, "__float__ should not be invoked for comparisons"
41
42 # same goes for subtraction
43 def __sub__(self, other):
44 assert False, "__sub__ should not be invoked for comparisons"
45 __rsub__ = __sub__
46
47
48class DummyRational(object):
49 """Test comparison of Fraction with a naive rational implementation."""
50
51 def __init__(self, num, den):
52 g = gcd(num, den)
53 self.num = num // g
54 self.den = den // g
55
56 def __eq__(self, other):
57 if isinstance(other, fractions.Fraction):
58 return (self.num == other._numerator and
59 self.den == other._denominator)
60 else:
61 return NotImplemented
62
63 def __lt__(self, other):
64 return(self.num * other._denominator < self.den * other._numerator)
65
66 def __gt__(self, other):
67 return(self.num * other._denominator > self.den * other._numerator)
68
69 def __le__(self, other):
70 return(self.num * other._denominator <= self.den * other._numerator)
71
72 def __ge__(self, other):
73 return(self.num * other._denominator >= self.den * other._numerator)
74
75 # this class is for testing comparisons; conversion to float
76 # should never be used for a comparison, since it loses accuracy
77 def __float__(self):
78 assert False, "__float__ should not be invoked"
Christian Heimesaf98da12008-01-27 15:18:18 +000079
Ezio Melotti682d3742012-02-29 14:05:53 +020080class DummyFraction(fractions.Fraction):
81 """Dummy Fraction subclass for copy and deepcopy testing."""
82
Christian Heimesaf98da12008-01-27 15:18:18 +000083class GcdTest(unittest.TestCase):
84
85 def testMisc(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +000086 self.assertEqual(0, gcd(0, 0))
87 self.assertEqual(1, gcd(1, 0))
88 self.assertEqual(-1, gcd(-1, 0))
89 self.assertEqual(1, gcd(0, 1))
90 self.assertEqual(-1, gcd(0, -1))
91 self.assertEqual(1, gcd(7, 1))
92 self.assertEqual(-1, gcd(7, -1))
93 self.assertEqual(1, gcd(-23, 15))
94 self.assertEqual(12, gcd(120, 84))
95 self.assertEqual(-12, gcd(84, -120))
Christian Heimesaf98da12008-01-27 15:18:18 +000096
Guido van Rossum7736b5b2008-01-15 21:44:53 +000097
98def _components(r):
99 return (r.numerator, r.denominator)
100
Christian Heimesaf98da12008-01-27 15:18:18 +0000101
Christian Heimes3feef612008-02-11 06:19:17 +0000102class FractionTest(unittest.TestCase):
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000103
104 def assertTypedEquals(self, expected, actual):
105 """Asserts that both the types and values are the same."""
Ezio Melottib3aedd42010-11-20 19:04:17 +0000106 self.assertEqual(type(expected), type(actual))
107 self.assertEqual(expected, actual)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000108
109 def assertRaisesMessage(self, exc_type, message,
110 callable, *args, **kwargs):
111 """Asserts that callable(*args, **kwargs) raises exc_type(message)."""
112 try:
113 callable(*args, **kwargs)
114 except exc_type as e:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000115 self.assertEqual(message, str(e))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000116 else:
117 self.fail("%s not raised" % exc_type.__name__)
118
119 def testInit(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000120 self.assertEqual((0, 1), _components(F()))
121 self.assertEqual((7, 1), _components(F(7)))
122 self.assertEqual((7, 3), _components(F(F(7, 3))))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000123
Ezio Melottib3aedd42010-11-20 19:04:17 +0000124 self.assertEqual((-1, 1), _components(F(-1, 1)))
125 self.assertEqual((-1, 1), _components(F(1, -1)))
126 self.assertEqual((1, 1), _components(F(-2, -2)))
127 self.assertEqual((1, 2), _components(F(5, 10)))
128 self.assertEqual((7, 15), _components(F(7, 15)))
129 self.assertEqual((10**23, 1), _components(F(10**23)))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000130
Ezio Melottib3aedd42010-11-20 19:04:17 +0000131 self.assertEqual((3, 77), _components(F(F(3, 7), 11)))
132 self.assertEqual((-9, 5), _components(F(2, F(-10, 9))))
133 self.assertEqual((2486, 2485), _components(F(F(22, 7), F(355, 113))))
Mark Dickinsond4d95f82009-04-24 14:06:19 +0000134
Christian Heimes3feef612008-02-11 06:19:17 +0000135 self.assertRaisesMessage(ZeroDivisionError, "Fraction(12, 0)",
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000136 F, 12, 0)
Georg Brandl86b2fb92008-07-16 03:43:04 +0000137 self.assertRaises(TypeError, F, 1.5 + 3j)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000138
Georg Brandl86b2fb92008-07-16 03:43:04 +0000139 self.assertRaises(TypeError, F, "3/2", 3)
Mark Dickinsond4d95f82009-04-24 14:06:19 +0000140 self.assertRaises(TypeError, F, 3, 0j)
141 self.assertRaises(TypeError, F, 3, 1j)
142
Mark Dickinson98127c32010-04-03 11:18:52 +0000143 @requires_IEEE_754
144 def testInitFromFloat(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000145 self.assertEqual((5, 2), _components(F(2.5)))
146 self.assertEqual((0, 1), _components(F(-0.0)))
147 self.assertEqual((3602879701896397, 36028797018963968),
148 _components(F(0.1)))
Mark Dickinson98127c32010-04-03 11:18:52 +0000149 self.assertRaises(TypeError, F, float('nan'))
150 self.assertRaises(TypeError, F, float('inf'))
151 self.assertRaises(TypeError, F, float('-inf'))
152
153 def testInitFromDecimal(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000154 self.assertEqual((11, 10),
155 _components(F(Decimal('1.1'))))
156 self.assertEqual((7, 200),
157 _components(F(Decimal('3.5e-2'))))
158 self.assertEqual((0, 1),
159 _components(F(Decimal('.000e20'))))
Mark Dickinson98127c32010-04-03 11:18:52 +0000160 self.assertRaises(TypeError, F, Decimal('nan'))
161 self.assertRaises(TypeError, F, Decimal('snan'))
162 self.assertRaises(TypeError, F, Decimal('inf'))
163 self.assertRaises(TypeError, F, Decimal('-inf'))
Christian Heimes587c2bf2008-01-19 16:21:02 +0000164
165 def testFromString(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000166 self.assertEqual((5, 1), _components(F("5")))
167 self.assertEqual((3, 2), _components(F("3/2")))
168 self.assertEqual((3, 2), _components(F(" \n +3/2")))
169 self.assertEqual((-3, 2), _components(F("-3/2 ")))
170 self.assertEqual((13, 2), _components(F(" 013/02 \n ")))
171 self.assertEqual((16, 5), _components(F(" 3.2 ")))
172 self.assertEqual((-16, 5), _components(F(" -3.2 ")))
173 self.assertEqual((-3, 1), _components(F(" -3. ")))
174 self.assertEqual((3, 5), _components(F(" .6 ")))
175 self.assertEqual((1, 3125), _components(F("32.e-5")))
176 self.assertEqual((1000000, 1), _components(F("1E+06")))
177 self.assertEqual((-12300, 1), _components(F("-1.23e4")))
178 self.assertEqual((0, 1), _components(F(" .0e+0\t")))
179 self.assertEqual((0, 1), _components(F("-0.000e0")))
Christian Heimes587c2bf2008-01-19 16:21:02 +0000180
181 self.assertRaisesMessage(
Christian Heimes3feef612008-02-11 06:19:17 +0000182 ZeroDivisionError, "Fraction(3, 0)",
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000183 F, "3/0")
Christian Heimes587c2bf2008-01-19 16:21:02 +0000184 self.assertRaisesMessage(
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000185 ValueError, "Invalid literal for Fraction: '3/'",
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000186 F, "3/")
Christian Heimes587c2bf2008-01-19 16:21:02 +0000187 self.assertRaisesMessage(
Mark Dickinsoncf63f2f2009-04-22 17:50:21 +0000188 ValueError, "Invalid literal for Fraction: '/2'",
189 F, "/2")
190 self.assertRaisesMessage(
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 # Denominators don't need a sign.
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(
198 # Imitate float's parsing.
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000199 ValueError, "Invalid literal for Fraction: '+ 3/2'",
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000200 F, "+ 3/2")
Christian Heimes587c2bf2008-01-19 16:21:02 +0000201 self.assertRaisesMessage(
Christian Heimesaf98da12008-01-27 15:18:18 +0000202 # Avoid treating '.' as a regex special character.
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000203 ValueError, "Invalid literal for Fraction: '3a2'",
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000204 F, "3a2")
Christian Heimesaf98da12008-01-27 15:18:18 +0000205 self.assertRaisesMessage(
Christian Heimesaf98da12008-01-27 15:18:18 +0000206 # Don't accept combinations of decimals and rationals.
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000207 ValueError, "Invalid literal for Fraction: '3/7.2'",
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000208 F, "3/7.2")
Christian Heimesaf98da12008-01-27 15:18:18 +0000209 self.assertRaisesMessage(
210 # Don't accept combinations of decimals and rationals.
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000211 ValueError, "Invalid literal for Fraction: '3.2/7'",
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000212 F, "3.2/7")
Christian Heimes292d3512008-02-03 16:51:08 +0000213 self.assertRaisesMessage(
214 # Allow 3. and .3, but not .
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000215 ValueError, "Invalid literal for Fraction: '.'",
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000216 F, ".")
Christian Heimes587c2bf2008-01-19 16:21:02 +0000217
218 def testImmutable(self):
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000219 r = F(7, 3)
Christian Heimes587c2bf2008-01-19 16:21:02 +0000220 r.__init__(2, 15)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000221 self.assertEqual((7, 3), _components(r))
Christian Heimes587c2bf2008-01-19 16:21:02 +0000222
Christian Heimes400adb02008-02-01 08:12:03 +0000223 self.assertRaises(AttributeError, setattr, r, 'numerator', 12)
224 self.assertRaises(AttributeError, setattr, r, 'denominator', 6)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000225 self.assertEqual((7, 3), _components(r))
Christian Heimes400adb02008-02-01 08:12:03 +0000226
227 # But if you _really_ need to:
228 r._numerator = 4
229 r._denominator = 2
Ezio Melottib3aedd42010-11-20 19:04:17 +0000230 self.assertEqual((4, 2), _components(r))
Christian Heimes400adb02008-02-01 08:12:03 +0000231 # Which breaks some important operations:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000232 self.assertNotEqual(F(4, 2), r)
Christian Heimes400adb02008-02-01 08:12:03 +0000233
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000234 def testFromFloat(self):
Georg Brandl2ee470f2008-07-16 12:55:28 +0000235 self.assertRaises(TypeError, F.from_float, 3+4j)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000236 self.assertEqual((10, 1), _components(F.from_float(10)))
Georg Brandl3a9b0622009-01-03 22:07:57 +0000237 bigint = 1234567890123456789
Ezio Melottib3aedd42010-11-20 19:04:17 +0000238 self.assertEqual((bigint, 1), _components(F.from_float(bigint)))
239 self.assertEqual((0, 1), _components(F.from_float(-0.0)))
240 self.assertEqual((10, 1), _components(F.from_float(10.0)))
241 self.assertEqual((-5, 2), _components(F.from_float(-2.5)))
242 self.assertEqual((99999999999999991611392, 1),
243 _components(F.from_float(1e23)))
244 self.assertEqual(float(10**23), float(F.from_float(1e23)))
245 self.assertEqual((3602879701896397, 1125899906842624),
246 _components(F.from_float(3.2)))
247 self.assertEqual(3.2, float(F.from_float(3.2)))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000248
249 inf = 1e1000
250 nan = inf - inf
251 self.assertRaisesMessage(
Christian Heimes3feef612008-02-11 06:19:17 +0000252 TypeError, "Cannot convert inf to Fraction.",
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000253 F.from_float, inf)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000254 self.assertRaisesMessage(
Christian Heimes3feef612008-02-11 06:19:17 +0000255 TypeError, "Cannot convert -inf to Fraction.",
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000256 F.from_float, -inf)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000257 self.assertRaisesMessage(
Christian Heimes3feef612008-02-11 06:19:17 +0000258 TypeError, "Cannot convert nan to Fraction.",
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000259 F.from_float, nan)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000260
Christian Heimes587c2bf2008-01-19 16:21:02 +0000261 def testFromDecimal(self):
Georg Brandl2ee470f2008-07-16 12:55:28 +0000262 self.assertRaises(TypeError, F.from_decimal, 3+4j)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000263 self.assertEqual(F(10, 1), F.from_decimal(10))
264 self.assertEqual(F(0), F.from_decimal(Decimal("-0")))
265 self.assertEqual(F(5, 10), F.from_decimal(Decimal("0.5")))
266 self.assertEqual(F(5, 1000), F.from_decimal(Decimal("5e-3")))
267 self.assertEqual(F(5000), F.from_decimal(Decimal("5e3")))
268 self.assertEqual(1 - F(1, 10**30),
269 F.from_decimal(Decimal("0." + "9" * 30)))
Christian Heimes587c2bf2008-01-19 16:21:02 +0000270
271 self.assertRaisesMessage(
Christian Heimes3feef612008-02-11 06:19:17 +0000272 TypeError, "Cannot convert Infinity to Fraction.",
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000273 F.from_decimal, Decimal("inf"))
Christian Heimes587c2bf2008-01-19 16:21:02 +0000274 self.assertRaisesMessage(
Christian Heimes3feef612008-02-11 06:19:17 +0000275 TypeError, "Cannot convert -Infinity to Fraction.",
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000276 F.from_decimal, Decimal("-inf"))
Christian Heimes587c2bf2008-01-19 16:21:02 +0000277 self.assertRaisesMessage(
Christian Heimes3feef612008-02-11 06:19:17 +0000278 TypeError, "Cannot convert NaN to Fraction.",
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000279 F.from_decimal, Decimal("nan"))
Christian Heimes587c2bf2008-01-19 16:21:02 +0000280 self.assertRaisesMessage(
Christian Heimes3feef612008-02-11 06:19:17 +0000281 TypeError, "Cannot convert sNaN to Fraction.",
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000282 F.from_decimal, Decimal("snan"))
Christian Heimes587c2bf2008-01-19 16:21:02 +0000283
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000284 def testLimitDenominator(self):
285 rpi = F('3.1415926535897932')
286 self.assertEqual(rpi.limit_denominator(10000), F(355, 113))
287 self.assertEqual(-rpi.limit_denominator(10000), F(-355, 113))
288 self.assertEqual(rpi.limit_denominator(113), F(355, 113))
289 self.assertEqual(rpi.limit_denominator(112), F(333, 106))
290 self.assertEqual(F(201, 200).limit_denominator(100), F(1))
291 self.assertEqual(F(201, 200).limit_denominator(101), F(102, 101))
292 self.assertEqual(F(0).limit_denominator(10000), F(0))
Ezio Melotti682d3742012-02-29 14:05:53 +0200293 for i in (0, -1):
294 self.assertRaisesMessage(
295 ValueError, "max_denominator should be at least 1",
296 F(1).limit_denominator, i)
Christian Heimesbbffeb62008-01-24 09:42:52 +0000297
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000298 def testConversions(self):
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000299 self.assertTypedEquals(-1, math.trunc(F(-11, 10)))
Ezio Melotti682d3742012-02-29 14:05:53 +0200300 self.assertTypedEquals(1, math.trunc(F(11, 10)))
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000301 self.assertTypedEquals(-2, math.floor(F(-11, 10)))
302 self.assertTypedEquals(-1, math.ceil(F(-11, 10)))
303 self.assertTypedEquals(-1, math.ceil(F(-10, 10)))
304 self.assertTypedEquals(-1, int(F(-11, 10)))
305 self.assertTypedEquals(0, round(F(-1, 10)))
306 self.assertTypedEquals(0, round(F(-5, 10)))
307 self.assertTypedEquals(-2, round(F(-15, 10)))
308 self.assertTypedEquals(-1, round(F(-7, 10)))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000309
Ezio Melottib3aedd42010-11-20 19:04:17 +0000310 self.assertEqual(False, bool(F(0, 1)))
311 self.assertEqual(True, bool(F(3, 2)))
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000312 self.assertTypedEquals(0.1, float(F(1, 10)))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000313
314 # Check that __float__ isn't implemented by converting the
315 # numerator and denominator to float before dividing.
316 self.assertRaises(OverflowError, float, int('2'*400+'7'))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000317 self.assertAlmostEqual(2.0/3,
318 float(F(int('2'*400+'7'), int('3'*400+'1'))))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000319
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000320 self.assertTypedEquals(0.1+0j, complex(F(1,10)))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000321
322 def testRound(self):
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000323 self.assertTypedEquals(F(-200), round(F(-150), -2))
324 self.assertTypedEquals(F(-200), round(F(-250), -2))
325 self.assertTypedEquals(F(30), round(F(26), -1))
326 self.assertTypedEquals(F(-2, 10), round(F(-15, 100), 1))
327 self.assertTypedEquals(F(-2, 10), round(F(-25, 100), 1))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000328
329
330 def testArithmetic(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000331 self.assertEqual(F(1, 2), F(1, 10) + F(2, 5))
332 self.assertEqual(F(-3, 10), F(1, 10) - F(2, 5))
333 self.assertEqual(F(1, 25), F(1, 10) * F(2, 5))
334 self.assertEqual(F(1, 4), F(1, 10) / F(2, 5))
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000335 self.assertTypedEquals(2, F(9, 10) // F(2, 5))
336 self.assertTypedEquals(10**23, F(10**23, 1) // F(1))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000337 self.assertEqual(F(2, 3), F(-7, 3) % F(3, 2))
338 self.assertEqual(F(8, 27), F(2, 3) ** F(3))
339 self.assertEqual(F(27, 8), F(2, 3) ** F(-3))
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000340 self.assertTypedEquals(2.0, F(4) ** F(1, 2))
Ezio Melotti682d3742012-02-29 14:05:53 +0200341 self.assertEqual(F(1, 1), +F(1, 1))
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000342 z = pow(F(-1), F(1, 2))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000343 self.assertAlmostEqual(z.real, 0)
344 self.assertEqual(z.imag, 1)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000345
346 def testMixedArithmetic(self):
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000347 self.assertTypedEquals(F(11, 10), F(1, 10) + 1)
348 self.assertTypedEquals(1.1, F(1, 10) + 1.0)
349 self.assertTypedEquals(1.1 + 0j, F(1, 10) + (1.0 + 0j))
350 self.assertTypedEquals(F(11, 10), 1 + F(1, 10))
351 self.assertTypedEquals(1.1, 1.0 + F(1, 10))
352 self.assertTypedEquals(1.1 + 0j, (1.0 + 0j) + F(1, 10))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000353
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000354 self.assertTypedEquals(F(-9, 10), F(1, 10) - 1)
355 self.assertTypedEquals(-0.9, F(1, 10) - 1.0)
356 self.assertTypedEquals(-0.9 + 0j, F(1, 10) - (1.0 + 0j))
357 self.assertTypedEquals(F(9, 10), 1 - F(1, 10))
358 self.assertTypedEquals(0.9, 1.0 - F(1, 10))
359 self.assertTypedEquals(0.9 + 0j, (1.0 + 0j) - F(1, 10))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000360
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000361 self.assertTypedEquals(F(1, 10), F(1, 10) * 1)
362 self.assertTypedEquals(0.1, F(1, 10) * 1.0)
363 self.assertTypedEquals(0.1 + 0j, F(1, 10) * (1.0 + 0j))
364 self.assertTypedEquals(F(1, 10), 1 * F(1, 10))
365 self.assertTypedEquals(0.1, 1.0 * F(1, 10))
366 self.assertTypedEquals(0.1 + 0j, (1.0 + 0j) * F(1, 10))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000367
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000368 self.assertTypedEquals(F(1, 10), F(1, 10) / 1)
369 self.assertTypedEquals(0.1, F(1, 10) / 1.0)
370 self.assertTypedEquals(0.1 + 0j, F(1, 10) / (1.0 + 0j))
371 self.assertTypedEquals(F(10, 1), 1 / F(1, 10))
372 self.assertTypedEquals(10.0, 1.0 / F(1, 10))
373 self.assertTypedEquals(10.0 + 0j, (1.0 + 0j) / F(1, 10))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000374
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000375 self.assertTypedEquals(0, F(1, 10) // 1)
376 self.assertTypedEquals(0, F(1, 10) // 1.0)
377 self.assertTypedEquals(10, 1 // F(1, 10))
378 self.assertTypedEquals(10**23, 10**22 // F(1, 10))
379 self.assertTypedEquals(10, 1.0 // F(1, 10))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000380
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000381 self.assertTypedEquals(F(1, 10), F(1, 10) % 1)
382 self.assertTypedEquals(0.1, F(1, 10) % 1.0)
383 self.assertTypedEquals(F(0, 1), 1 % F(1, 10))
384 self.assertTypedEquals(0.0, 1.0 % F(1, 10))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000385
386 # No need for divmod since we don't override it.
387
388 # ** has more interesting conversion rules.
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000389 self.assertTypedEquals(F(100, 1), F(1, 10) ** -2)
390 self.assertTypedEquals(F(100, 1), F(10, 1) ** 2)
391 self.assertTypedEquals(0.1, F(1, 10) ** 1.0)
392 self.assertTypedEquals(0.1 + 0j, F(1, 10) ** (1.0 + 0j))
393 self.assertTypedEquals(4 , 2 ** F(2, 1))
394 z = pow(-1, F(1, 2))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000395 self.assertAlmostEqual(0, z.real)
396 self.assertEqual(1, z.imag)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000397 self.assertTypedEquals(F(1, 4) , 2 ** F(-2, 1))
398 self.assertTypedEquals(2.0 , 4 ** F(1, 2))
399 self.assertTypedEquals(0.25, 2.0 ** F(-2, 1))
400 self.assertTypedEquals(1.0 + 0j, (1.0 + 0j) ** F(1, 10))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000401
402 def testMixingWithDecimal(self):
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000403 # Decimal refuses mixed arithmetic (but not mixed comparisons)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000404 self.assertRaisesMessage(
405 TypeError,
Christian Heimes3feef612008-02-11 06:19:17 +0000406 "unsupported operand type(s) for +: 'Fraction' and 'Decimal'",
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000407 operator.add, F(3,11), Decimal('3.1415926'))
Ezio Melotti682d3742012-02-29 14:05:53 +0200408 self.assertRaisesMessage(
409 TypeError,
410 "unsupported operand type(s) for +: 'Decimal' and 'Fraction'",
411 operator.add, Decimal('3.1415926'), F(3,11))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000412
413 def testComparisons(self):
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000414 self.assertTrue(F(1, 2) < F(2, 3))
415 self.assertFalse(F(1, 2) < F(1, 2))
416 self.assertTrue(F(1, 2) <= F(2, 3))
417 self.assertTrue(F(1, 2) <= F(1, 2))
418 self.assertFalse(F(2, 3) <= F(1, 2))
419 self.assertTrue(F(1, 2) == F(1, 2))
420 self.assertFalse(F(1, 2) == F(1, 3))
421 self.assertFalse(F(1, 2) != F(1, 2))
422 self.assertTrue(F(1, 2) != F(1, 3))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000423
Mark Dickinson85424c92009-07-18 14:41:42 +0000424 def testComparisonsDummyRational(self):
425 self.assertTrue(F(1, 2) == DummyRational(1, 2))
426 self.assertTrue(DummyRational(1, 2) == F(1, 2))
427 self.assertFalse(F(1, 2) == DummyRational(3, 4))
428 self.assertFalse(DummyRational(3, 4) == F(1, 2))
429
430 self.assertTrue(F(1, 2) < DummyRational(3, 4))
431 self.assertFalse(F(1, 2) < DummyRational(1, 2))
432 self.assertFalse(F(1, 2) < DummyRational(1, 7))
433 self.assertFalse(F(1, 2) > DummyRational(3, 4))
434 self.assertFalse(F(1, 2) > DummyRational(1, 2))
435 self.assertTrue(F(1, 2) > DummyRational(1, 7))
436 self.assertTrue(F(1, 2) <= DummyRational(3, 4))
437 self.assertTrue(F(1, 2) <= DummyRational(1, 2))
438 self.assertFalse(F(1, 2) <= DummyRational(1, 7))
439 self.assertFalse(F(1, 2) >= DummyRational(3, 4))
440 self.assertTrue(F(1, 2) >= DummyRational(1, 2))
441 self.assertTrue(F(1, 2) >= DummyRational(1, 7))
442
443 self.assertTrue(DummyRational(1, 2) < F(3, 4))
444 self.assertFalse(DummyRational(1, 2) < F(1, 2))
445 self.assertFalse(DummyRational(1, 2) < F(1, 7))
446 self.assertFalse(DummyRational(1, 2) > F(3, 4))
447 self.assertFalse(DummyRational(1, 2) > F(1, 2))
448 self.assertTrue(DummyRational(1, 2) > F(1, 7))
449 self.assertTrue(DummyRational(1, 2) <= F(3, 4))
450 self.assertTrue(DummyRational(1, 2) <= F(1, 2))
451 self.assertFalse(DummyRational(1, 2) <= F(1, 7))
452 self.assertFalse(DummyRational(1, 2) >= F(3, 4))
453 self.assertTrue(DummyRational(1, 2) >= F(1, 2))
454 self.assertTrue(DummyRational(1, 2) >= F(1, 7))
455
456 def testComparisonsDummyFloat(self):
457 x = DummyFloat(1./3.)
458 y = F(1, 3)
459 self.assertTrue(x != y)
460 self.assertTrue(x < y or x > y)
461 self.assertFalse(x == y)
462 self.assertFalse(x <= y and x >= y)
463 self.assertTrue(y != x)
464 self.assertTrue(y < x or y > x)
465 self.assertFalse(y == x)
466 self.assertFalse(y <= x and y >= x)
467
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000468 def testMixedLess(self):
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000469 self.assertTrue(2 < F(5, 2))
470 self.assertFalse(2 < F(4, 2))
471 self.assertTrue(F(5, 2) < 3)
472 self.assertFalse(F(4, 2) < 2)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000473
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000474 self.assertTrue(F(1, 2) < 0.6)
475 self.assertFalse(F(1, 2) < 0.4)
476 self.assertTrue(0.4 < F(1, 2))
477 self.assertFalse(0.5 < F(1, 2))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000478
Mark Dickinson85424c92009-07-18 14:41:42 +0000479 self.assertFalse(float('inf') < F(1, 2))
480 self.assertTrue(float('-inf') < F(0, 10))
481 self.assertFalse(float('nan') < F(-3, 7))
482 self.assertTrue(F(1, 2) < float('inf'))
483 self.assertFalse(F(17, 12) < float('-inf'))
484 self.assertFalse(F(144, -89) < float('nan'))
485
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000486 def testMixedLessEqual(self):
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000487 self.assertTrue(0.5 <= F(1, 2))
488 self.assertFalse(0.6 <= F(1, 2))
489 self.assertTrue(F(1, 2) <= 0.5)
490 self.assertFalse(F(1, 2) <= 0.4)
491 self.assertTrue(2 <= F(4, 2))
492 self.assertFalse(2 <= F(3, 2))
493 self.assertTrue(F(4, 2) <= 2)
494 self.assertFalse(F(5, 2) <= 2)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000495
Mark Dickinson85424c92009-07-18 14:41:42 +0000496 self.assertFalse(float('inf') <= F(1, 2))
497 self.assertTrue(float('-inf') <= F(0, 10))
498 self.assertFalse(float('nan') <= F(-3, 7))
499 self.assertTrue(F(1, 2) <= float('inf'))
500 self.assertFalse(F(17, 12) <= float('-inf'))
501 self.assertFalse(F(144, -89) <= float('nan'))
502
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000503 def testBigFloatComparisons(self):
504 # Because 10**23 can't be represented exactly as a float:
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000505 self.assertFalse(F(10**23) == float(10**23))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000506 # The first test demonstrates why these are important.
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000507 self.assertFalse(1e23 < float(F(math.trunc(1e23) + 1)))
508 self.assertTrue(1e23 < F(math.trunc(1e23) + 1))
509 self.assertFalse(1e23 <= F(math.trunc(1e23) - 1))
510 self.assertTrue(1e23 > F(math.trunc(1e23) - 1))
511 self.assertFalse(1e23 >= F(math.trunc(1e23) + 1))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000512
513 def testBigComplexComparisons(self):
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000514 self.assertFalse(F(10**23) == complex(10**23))
Mark Dickinson327f02c2010-03-27 11:11:13 +0000515 self.assertRaises(TypeError, operator.gt, F(10**23), complex(10**23))
516 self.assertRaises(TypeError, operator.le, F(10**23), complex(10**23))
517
518 x = F(3, 8)
519 z = complex(0.375, 0.0)
520 w = complex(0.375, 0.2)
521 self.assertTrue(x == z)
522 self.assertFalse(x != z)
523 self.assertFalse(x == w)
524 self.assertTrue(x != w)
525 for op in operator.lt, operator.le, operator.gt, operator.ge:
526 self.assertRaises(TypeError, op, x, z)
527 self.assertRaises(TypeError, op, z, x)
528 self.assertRaises(TypeError, op, x, w)
529 self.assertRaises(TypeError, op, w, x)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000530
531 def testMixedEqual(self):
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000532 self.assertTrue(0.5 == F(1, 2))
533 self.assertFalse(0.6 == F(1, 2))
534 self.assertTrue(F(1, 2) == 0.5)
535 self.assertFalse(F(1, 2) == 0.4)
536 self.assertTrue(2 == F(4, 2))
537 self.assertFalse(2 == F(3, 2))
538 self.assertTrue(F(4, 2) == 2)
539 self.assertFalse(F(5, 2) == 2)
Mark Dickinson85424c92009-07-18 14:41:42 +0000540 self.assertFalse(F(5, 2) == float('nan'))
541 self.assertFalse(float('nan') == F(3, 7))
542 self.assertFalse(F(5, 2) == float('inf'))
543 self.assertFalse(float('-inf') == F(2, 5))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000544
545 def testStringification(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000546 self.assertEqual("Fraction(7, 3)", repr(F(7, 3)))
547 self.assertEqual("Fraction(6283185307, 2000000000)",
548 repr(F('3.1415926535')))
549 self.assertEqual("Fraction(-1, 100000000000000000000)",
550 repr(F(1, -10**20)))
551 self.assertEqual("7/3", str(F(7, 3)))
552 self.assertEqual("7", str(F(7, 1)))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000553
554 def testHash(self):
Ezio Melotti682d3742012-02-29 14:05:53 +0200555 hmod = sys.hash_info.modulus
556 hinf = sys.hash_info.inf
Ezio Melottib3aedd42010-11-20 19:04:17 +0000557 self.assertEqual(hash(2.5), hash(F(5, 2)))
558 self.assertEqual(hash(10**50), hash(F(10**50)))
559 self.assertNotEqual(hash(float(10**23)), hash(F(10**23)))
Ezio Melotti682d3742012-02-29 14:05:53 +0200560 self.assertEqual(hinf, hash(F(1, hmod)))
Mark Dickinsonfec66202010-11-13 10:27:38 +0000561 # Check that __hash__ produces the same value as hash(), for
562 # consistency with int and Decimal. (See issue #10356.)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000563 self.assertEqual(hash(F(-1)), F(-1).__hash__())
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000564
565 def testApproximatePi(self):
566 # Algorithm borrowed from
567 # http://docs.python.org/lib/decimal-recipes.html
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000568 three = F(3)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000569 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000570 while abs(s - lasts) > F(1, 10**9):
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000571 lasts = s
572 n, na = n+na, na+8
573 d, da = d+da, da+32
574 t = (t * n) / d
575 s += t
Ezio Melottib3aedd42010-11-20 19:04:17 +0000576 self.assertAlmostEqual(math.pi, s)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000577
578 def testApproximateCos1(self):
579 # Algorithm borrowed from
580 # http://docs.python.org/lib/decimal-recipes.html
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000581 x = F(1)
582 i, lasts, s, fact, num, sign = 0, 0, F(1), 1, 1, 1
583 while abs(s - lasts) > F(1, 10**9):
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000584 lasts = s
585 i += 2
586 fact *= i * (i-1)
587 num *= x * x
588 sign *= -1
589 s += num / fact * sign
Ezio Melottib3aedd42010-11-20 19:04:17 +0000590 self.assertAlmostEqual(math.cos(1), s)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000591
Christian Heimes969fe572008-01-25 11:23:10 +0000592 def test_copy_deepcopy_pickle(self):
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000593 r = F(13, 7)
Ezio Melotti682d3742012-02-29 14:05:53 +0200594 dr = DummyFraction(13, 7)
Christian Heimes969fe572008-01-25 11:23:10 +0000595 self.assertEqual(r, loads(dumps(r)))
596 self.assertEqual(id(r), id(copy(r)))
597 self.assertEqual(id(r), id(deepcopy(r)))
Ezio Melotti682d3742012-02-29 14:05:53 +0200598 self.assertNotEqual(id(dr), id(copy(dr)))
599 self.assertNotEqual(id(dr), id(deepcopy(dr)))
600 self.assertTypedEquals(dr, copy(dr))
601 self.assertTypedEquals(dr, deepcopy(dr))
Christian Heimes969fe572008-01-25 11:23:10 +0000602
Mark Dickinsonc28ad272009-02-12 17:58:36 +0000603 def test_slots(self):
604 # Issue 4998
605 r = F(13, 7)
606 self.assertRaises(AttributeError, setattr, r, 'a', 10)
607
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000608def test_main():
Christian Heimes3feef612008-02-11 06:19:17 +0000609 run_unittest(FractionTest, GcdTest)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000610
611if __name__ == '__main__':
612 test_main()