• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1"""Tests for Lib/fractions.py."""
2
3from decimal import Decimal
4from test.support import requires_IEEE_754
5import math
6import numbers
7import operator
8import fractions
9import sys
10import unittest
11import warnings
12from copy import copy, deepcopy
13from pickle import dumps, loads
14F = fractions.Fraction
15gcd = fractions.gcd
16
17class DummyFloat(object):
18    """Dummy float class for testing comparisons with Fractions"""
19
20    def __init__(self, value):
21        if not isinstance(value, float):
22            raise TypeError("DummyFloat can only be initialized from float")
23        self.value = value
24
25    def _richcmp(self, other, op):
26        if isinstance(other, numbers.Rational):
27            return op(F.from_float(self.value), other)
28        elif isinstance(other, DummyFloat):
29            return op(self.value, other.value)
30        else:
31            return NotImplemented
32
33    def __eq__(self, other): return self._richcmp(other, operator.eq)
34    def __le__(self, other): return self._richcmp(other, operator.le)
35    def __lt__(self, other): return self._richcmp(other, operator.lt)
36    def __ge__(self, other): return self._richcmp(other, operator.ge)
37    def __gt__(self, other): return self._richcmp(other, operator.gt)
38
39    # shouldn't be calling __float__ at all when doing comparisons
40    def __float__(self):
41        assert False, "__float__ should not be invoked for comparisons"
42
43    # same goes for subtraction
44    def __sub__(self, other):
45        assert False, "__sub__ should not be invoked for comparisons"
46    __rsub__ = __sub__
47
48
49class DummyRational(object):
50    """Test comparison of Fraction with a naive rational implementation."""
51
52    def __init__(self, num, den):
53        g = math.gcd(num, den)
54        self.num = num // g
55        self.den = den // g
56
57    def __eq__(self, other):
58        if isinstance(other, fractions.Fraction):
59            return (self.num == other._numerator and
60                    self.den == other._denominator)
61        else:
62            return NotImplemented
63
64    def __lt__(self, other):
65        return(self.num * other._denominator < self.den * other._numerator)
66
67    def __gt__(self, other):
68        return(self.num * other._denominator > self.den * other._numerator)
69
70    def __le__(self, other):
71        return(self.num * other._denominator <= self.den * other._numerator)
72
73    def __ge__(self, other):
74        return(self.num * other._denominator >= self.den * other._numerator)
75
76    # this class is for testing comparisons; conversion to float
77    # should never be used for a comparison, since it loses accuracy
78    def __float__(self):
79        assert False, "__float__ should not be invoked"
80
81class DummyFraction(fractions.Fraction):
82    """Dummy Fraction subclass for copy and deepcopy testing."""
83
84class GcdTest(unittest.TestCase):
85
86    def testMisc(self):
87        # fractions.gcd() is deprecated
88        with self.assertWarnsRegex(DeprecationWarning, r'fractions\.gcd'):
89            gcd(1, 1)
90        with warnings.catch_warnings():
91            warnings.filterwarnings('ignore', r'fractions\.gcd',
92                                    DeprecationWarning)
93            self.assertEqual(0, gcd(0, 0))
94            self.assertEqual(1, gcd(1, 0))
95            self.assertEqual(-1, gcd(-1, 0))
96            self.assertEqual(1, gcd(0, 1))
97            self.assertEqual(-1, gcd(0, -1))
98            self.assertEqual(1, gcd(7, 1))
99            self.assertEqual(-1, gcd(7, -1))
100            self.assertEqual(1, gcd(-23, 15))
101            self.assertEqual(12, gcd(120, 84))
102            self.assertEqual(-12, gcd(84, -120))
103            self.assertEqual(gcd(120.0, 84), 12.0)
104            self.assertEqual(gcd(120, 84.0), 12.0)
105            self.assertEqual(gcd(F(120), F(84)), F(12))
106            self.assertEqual(gcd(F(120, 77), F(84, 55)), F(12, 385))
107
108
109def _components(r):
110    return (r.numerator, r.denominator)
111
112
113class FractionTest(unittest.TestCase):
114
115    def assertTypedEquals(self, expected, actual):
116        """Asserts that both the types and values are the same."""
117        self.assertEqual(type(expected), type(actual))
118        self.assertEqual(expected, actual)
119
120    def assertRaisesMessage(self, exc_type, message,
121                            callable, *args, **kwargs):
122        """Asserts that callable(*args, **kwargs) raises exc_type(message)."""
123        try:
124            callable(*args, **kwargs)
125        except exc_type as e:
126            self.assertEqual(message, str(e))
127        else:
128            self.fail("%s not raised" % exc_type.__name__)
129
130    def testInit(self):
131        self.assertEqual((0, 1), _components(F()))
132        self.assertEqual((7, 1), _components(F(7)))
133        self.assertEqual((7, 3), _components(F(F(7, 3))))
134
135        self.assertEqual((-1, 1), _components(F(-1, 1)))
136        self.assertEqual((-1, 1), _components(F(1, -1)))
137        self.assertEqual((1, 1), _components(F(-2, -2)))
138        self.assertEqual((1, 2), _components(F(5, 10)))
139        self.assertEqual((7, 15), _components(F(7, 15)))
140        self.assertEqual((10**23, 1), _components(F(10**23)))
141
142        self.assertEqual((3, 77), _components(F(F(3, 7), 11)))
143        self.assertEqual((-9, 5), _components(F(2, F(-10, 9))))
144        self.assertEqual((2486, 2485), _components(F(F(22, 7), F(355, 113))))
145
146        self.assertRaisesMessage(ZeroDivisionError, "Fraction(12, 0)",
147                                 F, 12, 0)
148        self.assertRaises(TypeError, F, 1.5 + 3j)
149
150        self.assertRaises(TypeError, F, "3/2", 3)
151        self.assertRaises(TypeError, F, 3, 0j)
152        self.assertRaises(TypeError, F, 3, 1j)
153        self.assertRaises(TypeError, F, 1, 2, 3)
154
155    @requires_IEEE_754
156    def testInitFromFloat(self):
157        self.assertEqual((5, 2), _components(F(2.5)))
158        self.assertEqual((0, 1), _components(F(-0.0)))
159        self.assertEqual((3602879701896397, 36028797018963968),
160                         _components(F(0.1)))
161        # bug 16469: error types should be consistent with float -> int
162        self.assertRaises(ValueError, F, float('nan'))
163        self.assertRaises(OverflowError, F, float('inf'))
164        self.assertRaises(OverflowError, F, float('-inf'))
165
166    def testInitFromDecimal(self):
167        self.assertEqual((11, 10),
168                         _components(F(Decimal('1.1'))))
169        self.assertEqual((7, 200),
170                         _components(F(Decimal('3.5e-2'))))
171        self.assertEqual((0, 1),
172                         _components(F(Decimal('.000e20'))))
173        # bug 16469: error types should be consistent with decimal -> int
174        self.assertRaises(ValueError, F, Decimal('nan'))
175        self.assertRaises(ValueError, F, Decimal('snan'))
176        self.assertRaises(OverflowError, F, Decimal('inf'))
177        self.assertRaises(OverflowError, F, Decimal('-inf'))
178
179    def testFromString(self):
180        self.assertEqual((5, 1), _components(F("5")))
181        self.assertEqual((3, 2), _components(F("3/2")))
182        self.assertEqual((3, 2), _components(F(" \n  +3/2")))
183        self.assertEqual((-3, 2), _components(F("-3/2  ")))
184        self.assertEqual((13, 2), _components(F("    013/02 \n  ")))
185        self.assertEqual((16, 5), _components(F(" 3.2 ")))
186        self.assertEqual((-16, 5), _components(F(" -3.2 ")))
187        self.assertEqual((-3, 1), _components(F(" -3. ")))
188        self.assertEqual((3, 5), _components(F(" .6 ")))
189        self.assertEqual((1, 3125), _components(F("32.e-5")))
190        self.assertEqual((1000000, 1), _components(F("1E+06")))
191        self.assertEqual((-12300, 1), _components(F("-1.23e4")))
192        self.assertEqual((0, 1), _components(F(" .0e+0\t")))
193        self.assertEqual((0, 1), _components(F("-0.000e0")))
194
195        self.assertRaisesMessage(
196            ZeroDivisionError, "Fraction(3, 0)",
197            F, "3/0")
198        self.assertRaisesMessage(
199            ValueError, "Invalid literal for Fraction: '3/'",
200            F, "3/")
201        self.assertRaisesMessage(
202            ValueError, "Invalid literal for Fraction: '/2'",
203            F, "/2")
204        self.assertRaisesMessage(
205            ValueError, "Invalid literal for Fraction: '3 /2'",
206            F, "3 /2")
207        self.assertRaisesMessage(
208            # Denominators don't need a sign.
209            ValueError, "Invalid literal for Fraction: '3/+2'",
210            F, "3/+2")
211        self.assertRaisesMessage(
212            # Imitate float's parsing.
213            ValueError, "Invalid literal for Fraction: '+ 3/2'",
214            F, "+ 3/2")
215        self.assertRaisesMessage(
216            # Avoid treating '.' as a regex special character.
217            ValueError, "Invalid literal for Fraction: '3a2'",
218            F, "3a2")
219        self.assertRaisesMessage(
220            # Don't accept combinations of decimals and rationals.
221            ValueError, "Invalid literal for Fraction: '3/7.2'",
222            F, "3/7.2")
223        self.assertRaisesMessage(
224            # Don't accept combinations of decimals and rationals.
225            ValueError, "Invalid literal for Fraction: '3.2/7'",
226            F, "3.2/7")
227        self.assertRaisesMessage(
228            # Allow 3. and .3, but not .
229            ValueError, "Invalid literal for Fraction: '.'",
230            F, ".")
231
232    def testImmutable(self):
233        r = F(7, 3)
234        r.__init__(2, 15)
235        self.assertEqual((7, 3), _components(r))
236
237        self.assertRaises(AttributeError, setattr, r, 'numerator', 12)
238        self.assertRaises(AttributeError, setattr, r, 'denominator', 6)
239        self.assertEqual((7, 3), _components(r))
240
241        # But if you _really_ need to:
242        r._numerator = 4
243        r._denominator = 2
244        self.assertEqual((4, 2), _components(r))
245        # Which breaks some important operations:
246        self.assertNotEqual(F(4, 2), r)
247
248    def testFromFloat(self):
249        self.assertRaises(TypeError, F.from_float, 3+4j)
250        self.assertEqual((10, 1), _components(F.from_float(10)))
251        bigint = 1234567890123456789
252        self.assertEqual((bigint, 1), _components(F.from_float(bigint)))
253        self.assertEqual((0, 1), _components(F.from_float(-0.0)))
254        self.assertEqual((10, 1), _components(F.from_float(10.0)))
255        self.assertEqual((-5, 2), _components(F.from_float(-2.5)))
256        self.assertEqual((99999999999999991611392, 1),
257                         _components(F.from_float(1e23)))
258        self.assertEqual(float(10**23), float(F.from_float(1e23)))
259        self.assertEqual((3602879701896397, 1125899906842624),
260                         _components(F.from_float(3.2)))
261        self.assertEqual(3.2, float(F.from_float(3.2)))
262
263        inf = 1e1000
264        nan = inf - inf
265        # bug 16469: error types should be consistent with float -> int
266        self.assertRaisesMessage(
267            OverflowError, "cannot convert Infinity to integer ratio",
268            F.from_float, inf)
269        self.assertRaisesMessage(
270            OverflowError, "cannot convert Infinity to integer ratio",
271            F.from_float, -inf)
272        self.assertRaisesMessage(
273            ValueError, "cannot convert NaN to integer ratio",
274            F.from_float, nan)
275
276    def testFromDecimal(self):
277        self.assertRaises(TypeError, F.from_decimal, 3+4j)
278        self.assertEqual(F(10, 1), F.from_decimal(10))
279        self.assertEqual(F(0), F.from_decimal(Decimal("-0")))
280        self.assertEqual(F(5, 10), F.from_decimal(Decimal("0.5")))
281        self.assertEqual(F(5, 1000), F.from_decimal(Decimal("5e-3")))
282        self.assertEqual(F(5000), F.from_decimal(Decimal("5e3")))
283        self.assertEqual(1 - F(1, 10**30),
284                         F.from_decimal(Decimal("0." + "9" * 30)))
285
286        # bug 16469: error types should be consistent with decimal -> int
287        self.assertRaisesMessage(
288            OverflowError, "cannot convert Infinity to integer ratio",
289            F.from_decimal, Decimal("inf"))
290        self.assertRaisesMessage(
291            OverflowError, "cannot convert Infinity to integer ratio",
292            F.from_decimal, Decimal("-inf"))
293        self.assertRaisesMessage(
294            ValueError, "cannot convert NaN to integer ratio",
295            F.from_decimal, Decimal("nan"))
296        self.assertRaisesMessage(
297            ValueError, "cannot convert NaN to integer ratio",
298            F.from_decimal, Decimal("snan"))
299
300    def testLimitDenominator(self):
301        rpi = F('3.1415926535897932')
302        self.assertEqual(rpi.limit_denominator(10000), F(355, 113))
303        self.assertEqual(-rpi.limit_denominator(10000), F(-355, 113))
304        self.assertEqual(rpi.limit_denominator(113), F(355, 113))
305        self.assertEqual(rpi.limit_denominator(112), F(333, 106))
306        self.assertEqual(F(201, 200).limit_denominator(100), F(1))
307        self.assertEqual(F(201, 200).limit_denominator(101), F(102, 101))
308        self.assertEqual(F(0).limit_denominator(10000), F(0))
309        for i in (0, -1):
310            self.assertRaisesMessage(
311                ValueError, "max_denominator should be at least 1",
312                F(1).limit_denominator, i)
313
314    def testConversions(self):
315        self.assertTypedEquals(-1, math.trunc(F(-11, 10)))
316        self.assertTypedEquals(1, math.trunc(F(11, 10)))
317        self.assertTypedEquals(-2, math.floor(F(-11, 10)))
318        self.assertTypedEquals(-1, math.ceil(F(-11, 10)))
319        self.assertTypedEquals(-1, math.ceil(F(-10, 10)))
320        self.assertTypedEquals(-1, int(F(-11, 10)))
321        self.assertTypedEquals(0, round(F(-1, 10)))
322        self.assertTypedEquals(0, round(F(-5, 10)))
323        self.assertTypedEquals(-2, round(F(-15, 10)))
324        self.assertTypedEquals(-1, round(F(-7, 10)))
325
326        self.assertEqual(False, bool(F(0, 1)))
327        self.assertEqual(True, bool(F(3, 2)))
328        self.assertTypedEquals(0.1, float(F(1, 10)))
329
330        # Check that __float__ isn't implemented by converting the
331        # numerator and denominator to float before dividing.
332        self.assertRaises(OverflowError, float, int('2'*400+'7'))
333        self.assertAlmostEqual(2.0/3,
334                               float(F(int('2'*400+'7'), int('3'*400+'1'))))
335
336        self.assertTypedEquals(0.1+0j, complex(F(1,10)))
337
338    def testRound(self):
339        self.assertTypedEquals(F(-200), round(F(-150), -2))
340        self.assertTypedEquals(F(-200), round(F(-250), -2))
341        self.assertTypedEquals(F(30), round(F(26), -1))
342        self.assertTypedEquals(F(-2, 10), round(F(-15, 100), 1))
343        self.assertTypedEquals(F(-2, 10), round(F(-25, 100), 1))
344
345    def testArithmetic(self):
346        self.assertEqual(F(1, 2), F(1, 10) + F(2, 5))
347        self.assertEqual(F(-3, 10), F(1, 10) - F(2, 5))
348        self.assertEqual(F(1, 25), F(1, 10) * F(2, 5))
349        self.assertEqual(F(1, 4), F(1, 10) / F(2, 5))
350        self.assertTypedEquals(2, F(9, 10) // F(2, 5))
351        self.assertTypedEquals(10**23, F(10**23, 1) // F(1))
352        self.assertEqual(F(2, 3), F(-7, 3) % F(3, 2))
353        self.assertEqual(F(8, 27), F(2, 3) ** F(3))
354        self.assertEqual(F(27, 8), F(2, 3) ** F(-3))
355        self.assertTypedEquals(2.0, F(4) ** F(1, 2))
356        self.assertEqual(F(1, 1), +F(1, 1))
357        z = pow(F(-1), F(1, 2))
358        self.assertAlmostEqual(z.real, 0)
359        self.assertEqual(z.imag, 1)
360        # Regression test for #27539.
361        p = F(-1, 2) ** 0
362        self.assertEqual(p, F(1, 1))
363        self.assertEqual(p.numerator, 1)
364        self.assertEqual(p.denominator, 1)
365        p = F(-1, 2) ** -1
366        self.assertEqual(p, F(-2, 1))
367        self.assertEqual(p.numerator, -2)
368        self.assertEqual(p.denominator, 1)
369        p = F(-1, 2) ** -2
370        self.assertEqual(p, F(4, 1))
371        self.assertEqual(p.numerator, 4)
372        self.assertEqual(p.denominator, 1)
373
374    def testMixedArithmetic(self):
375        self.assertTypedEquals(F(11, 10), F(1, 10) + 1)
376        self.assertTypedEquals(1.1, F(1, 10) + 1.0)
377        self.assertTypedEquals(1.1 + 0j, F(1, 10) + (1.0 + 0j))
378        self.assertTypedEquals(F(11, 10), 1 + F(1, 10))
379        self.assertTypedEquals(1.1, 1.0 + F(1, 10))
380        self.assertTypedEquals(1.1 + 0j, (1.0 + 0j) + F(1, 10))
381
382        self.assertTypedEquals(F(-9, 10), F(1, 10) - 1)
383        self.assertTypedEquals(-0.9, F(1, 10) - 1.0)
384        self.assertTypedEquals(-0.9 + 0j, F(1, 10) - (1.0 + 0j))
385        self.assertTypedEquals(F(9, 10), 1 - F(1, 10))
386        self.assertTypedEquals(0.9, 1.0 - F(1, 10))
387        self.assertTypedEquals(0.9 + 0j, (1.0 + 0j) - F(1, 10))
388
389        self.assertTypedEquals(F(1, 10), F(1, 10) * 1)
390        self.assertTypedEquals(0.1, F(1, 10) * 1.0)
391        self.assertTypedEquals(0.1 + 0j, F(1, 10) * (1.0 + 0j))
392        self.assertTypedEquals(F(1, 10), 1 * F(1, 10))
393        self.assertTypedEquals(0.1, 1.0 * F(1, 10))
394        self.assertTypedEquals(0.1 + 0j, (1.0 + 0j) * F(1, 10))
395
396        self.assertTypedEquals(F(1, 10), F(1, 10) / 1)
397        self.assertTypedEquals(0.1, F(1, 10) / 1.0)
398        self.assertTypedEquals(0.1 + 0j, F(1, 10) / (1.0 + 0j))
399        self.assertTypedEquals(F(10, 1), 1 / F(1, 10))
400        self.assertTypedEquals(10.0, 1.0 / F(1, 10))
401        self.assertTypedEquals(10.0 + 0j, (1.0 + 0j) / F(1, 10))
402
403        self.assertTypedEquals(0, F(1, 10) // 1)
404        self.assertTypedEquals(0, F(1, 10) // 1.0)
405        self.assertTypedEquals(10, 1 // F(1, 10))
406        self.assertTypedEquals(10**23, 10**22 // F(1, 10))
407        self.assertTypedEquals(10, 1.0 // F(1, 10))
408
409        self.assertTypedEquals(F(1, 10), F(1, 10) % 1)
410        self.assertTypedEquals(0.1, F(1, 10) % 1.0)
411        self.assertTypedEquals(F(0, 1), 1 % F(1, 10))
412        self.assertTypedEquals(0.0, 1.0 % F(1, 10))
413
414        # No need for divmod since we don't override it.
415
416        # ** has more interesting conversion rules.
417        self.assertTypedEquals(F(100, 1), F(1, 10) ** -2)
418        self.assertTypedEquals(F(100, 1), F(10, 1) ** 2)
419        self.assertTypedEquals(0.1, F(1, 10) ** 1.0)
420        self.assertTypedEquals(0.1 + 0j, F(1, 10) ** (1.0 + 0j))
421        self.assertTypedEquals(4 , 2 ** F(2, 1))
422        z = pow(-1, F(1, 2))
423        self.assertAlmostEqual(0, z.real)
424        self.assertEqual(1, z.imag)
425        self.assertTypedEquals(F(1, 4) , 2 ** F(-2, 1))
426        self.assertTypedEquals(2.0 , 4 ** F(1, 2))
427        self.assertTypedEquals(0.25, 2.0 ** F(-2, 1))
428        self.assertTypedEquals(1.0 + 0j, (1.0 + 0j) ** F(1, 10))
429        self.assertRaises(ZeroDivisionError, operator.pow,
430                          F(0, 1), -2)
431
432    def testMixingWithDecimal(self):
433        # Decimal refuses mixed arithmetic (but not mixed comparisons)
434        self.assertRaises(TypeError, operator.add,
435                          F(3,11), Decimal('3.1415926'))
436        self.assertRaises(TypeError, operator.add,
437                          Decimal('3.1415926'), F(3,11))
438
439    def testComparisons(self):
440        self.assertTrue(F(1, 2) < F(2, 3))
441        self.assertFalse(F(1, 2) < F(1, 2))
442        self.assertTrue(F(1, 2) <= F(2, 3))
443        self.assertTrue(F(1, 2) <= F(1, 2))
444        self.assertFalse(F(2, 3) <= F(1, 2))
445        self.assertTrue(F(1, 2) == F(1, 2))
446        self.assertFalse(F(1, 2) == F(1, 3))
447        self.assertFalse(F(1, 2) != F(1, 2))
448        self.assertTrue(F(1, 2) != F(1, 3))
449
450    def testComparisonsDummyRational(self):
451        self.assertTrue(F(1, 2) == DummyRational(1, 2))
452        self.assertTrue(DummyRational(1, 2) == F(1, 2))
453        self.assertFalse(F(1, 2) == DummyRational(3, 4))
454        self.assertFalse(DummyRational(3, 4) == F(1, 2))
455
456        self.assertTrue(F(1, 2) < DummyRational(3, 4))
457        self.assertFalse(F(1, 2) < DummyRational(1, 2))
458        self.assertFalse(F(1, 2) < DummyRational(1, 7))
459        self.assertFalse(F(1, 2) > DummyRational(3, 4))
460        self.assertFalse(F(1, 2) > DummyRational(1, 2))
461        self.assertTrue(F(1, 2) > DummyRational(1, 7))
462        self.assertTrue(F(1, 2) <= DummyRational(3, 4))
463        self.assertTrue(F(1, 2) <= DummyRational(1, 2))
464        self.assertFalse(F(1, 2) <= DummyRational(1, 7))
465        self.assertFalse(F(1, 2) >= DummyRational(3, 4))
466        self.assertTrue(F(1, 2) >= DummyRational(1, 2))
467        self.assertTrue(F(1, 2) >= DummyRational(1, 7))
468
469        self.assertTrue(DummyRational(1, 2) < F(3, 4))
470        self.assertFalse(DummyRational(1, 2) < F(1, 2))
471        self.assertFalse(DummyRational(1, 2) < F(1, 7))
472        self.assertFalse(DummyRational(1, 2) > F(3, 4))
473        self.assertFalse(DummyRational(1, 2) > F(1, 2))
474        self.assertTrue(DummyRational(1, 2) > F(1, 7))
475        self.assertTrue(DummyRational(1, 2) <= F(3, 4))
476        self.assertTrue(DummyRational(1, 2) <= F(1, 2))
477        self.assertFalse(DummyRational(1, 2) <= F(1, 7))
478        self.assertFalse(DummyRational(1, 2) >= F(3, 4))
479        self.assertTrue(DummyRational(1, 2) >= F(1, 2))
480        self.assertTrue(DummyRational(1, 2) >= F(1, 7))
481
482    def testComparisonsDummyFloat(self):
483        x = DummyFloat(1./3.)
484        y = F(1, 3)
485        self.assertTrue(x != y)
486        self.assertTrue(x < y or x > y)
487        self.assertFalse(x == y)
488        self.assertFalse(x <= y and x >= y)
489        self.assertTrue(y != x)
490        self.assertTrue(y < x or y > x)
491        self.assertFalse(y == x)
492        self.assertFalse(y <= x and y >= x)
493
494    def testMixedLess(self):
495        self.assertTrue(2 < F(5, 2))
496        self.assertFalse(2 < F(4, 2))
497        self.assertTrue(F(5, 2) < 3)
498        self.assertFalse(F(4, 2) < 2)
499
500        self.assertTrue(F(1, 2) < 0.6)
501        self.assertFalse(F(1, 2) < 0.4)
502        self.assertTrue(0.4 < F(1, 2))
503        self.assertFalse(0.5 < F(1, 2))
504
505        self.assertFalse(float('inf') < F(1, 2))
506        self.assertTrue(float('-inf') < F(0, 10))
507        self.assertFalse(float('nan') < F(-3, 7))
508        self.assertTrue(F(1, 2) < float('inf'))
509        self.assertFalse(F(17, 12) < float('-inf'))
510        self.assertFalse(F(144, -89) < float('nan'))
511
512    def testMixedLessEqual(self):
513        self.assertTrue(0.5 <= F(1, 2))
514        self.assertFalse(0.6 <= F(1, 2))
515        self.assertTrue(F(1, 2) <= 0.5)
516        self.assertFalse(F(1, 2) <= 0.4)
517        self.assertTrue(2 <= F(4, 2))
518        self.assertFalse(2 <= F(3, 2))
519        self.assertTrue(F(4, 2) <= 2)
520        self.assertFalse(F(5, 2) <= 2)
521
522        self.assertFalse(float('inf') <= F(1, 2))
523        self.assertTrue(float('-inf') <= F(0, 10))
524        self.assertFalse(float('nan') <= F(-3, 7))
525        self.assertTrue(F(1, 2) <= float('inf'))
526        self.assertFalse(F(17, 12) <= float('-inf'))
527        self.assertFalse(F(144, -89) <= float('nan'))
528
529    def testBigFloatComparisons(self):
530        # Because 10**23 can't be represented exactly as a float:
531        self.assertFalse(F(10**23) == float(10**23))
532        # The first test demonstrates why these are important.
533        self.assertFalse(1e23 < float(F(math.trunc(1e23) + 1)))
534        self.assertTrue(1e23 < F(math.trunc(1e23) + 1))
535        self.assertFalse(1e23 <= F(math.trunc(1e23) - 1))
536        self.assertTrue(1e23 > F(math.trunc(1e23) - 1))
537        self.assertFalse(1e23 >= F(math.trunc(1e23) + 1))
538
539    def testBigComplexComparisons(self):
540        self.assertFalse(F(10**23) == complex(10**23))
541        self.assertRaises(TypeError, operator.gt, F(10**23), complex(10**23))
542        self.assertRaises(TypeError, operator.le, F(10**23), complex(10**23))
543
544        x = F(3, 8)
545        z = complex(0.375, 0.0)
546        w = complex(0.375, 0.2)
547        self.assertTrue(x == z)
548        self.assertFalse(x != z)
549        self.assertFalse(x == w)
550        self.assertTrue(x != w)
551        for op in operator.lt, operator.le, operator.gt, operator.ge:
552            self.assertRaises(TypeError, op, x, z)
553            self.assertRaises(TypeError, op, z, x)
554            self.assertRaises(TypeError, op, x, w)
555            self.assertRaises(TypeError, op, w, x)
556
557    def testMixedEqual(self):
558        self.assertTrue(0.5 == F(1, 2))
559        self.assertFalse(0.6 == F(1, 2))
560        self.assertTrue(F(1, 2) == 0.5)
561        self.assertFalse(F(1, 2) == 0.4)
562        self.assertTrue(2 == F(4, 2))
563        self.assertFalse(2 == F(3, 2))
564        self.assertTrue(F(4, 2) == 2)
565        self.assertFalse(F(5, 2) == 2)
566        self.assertFalse(F(5, 2) == float('nan'))
567        self.assertFalse(float('nan') == F(3, 7))
568        self.assertFalse(F(5, 2) == float('inf'))
569        self.assertFalse(float('-inf') == F(2, 5))
570
571    def testStringification(self):
572        self.assertEqual("Fraction(7, 3)", repr(F(7, 3)))
573        self.assertEqual("Fraction(6283185307, 2000000000)",
574                         repr(F('3.1415926535')))
575        self.assertEqual("Fraction(-1, 100000000000000000000)",
576                         repr(F(1, -10**20)))
577        self.assertEqual("7/3", str(F(7, 3)))
578        self.assertEqual("7", str(F(7, 1)))
579
580    def testHash(self):
581        hmod = sys.hash_info.modulus
582        hinf = sys.hash_info.inf
583        self.assertEqual(hash(2.5), hash(F(5, 2)))
584        self.assertEqual(hash(10**50), hash(F(10**50)))
585        self.assertNotEqual(hash(float(10**23)), hash(F(10**23)))
586        self.assertEqual(hinf, hash(F(1, hmod)))
587        # Check that __hash__ produces the same value as hash(), for
588        # consistency with int and Decimal.  (See issue #10356.)
589        self.assertEqual(hash(F(-1)), F(-1).__hash__())
590
591    def testApproximatePi(self):
592        # Algorithm borrowed from
593        # http://docs.python.org/lib/decimal-recipes.html
594        three = F(3)
595        lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
596        while abs(s - lasts) > F(1, 10**9):
597            lasts = s
598            n, na = n+na, na+8
599            d, da = d+da, da+32
600            t = (t * n) / d
601            s += t
602        self.assertAlmostEqual(math.pi, s)
603
604    def testApproximateCos1(self):
605        # Algorithm borrowed from
606        # http://docs.python.org/lib/decimal-recipes.html
607        x = F(1)
608        i, lasts, s, fact, num, sign = 0, 0, F(1), 1, 1, 1
609        while abs(s - lasts) > F(1, 10**9):
610            lasts = s
611            i += 2
612            fact *= i * (i-1)
613            num *= x * x
614            sign *= -1
615            s += num / fact * sign
616        self.assertAlmostEqual(math.cos(1), s)
617
618    def test_copy_deepcopy_pickle(self):
619        r = F(13, 7)
620        dr = DummyFraction(13, 7)
621        self.assertEqual(r, loads(dumps(r)))
622        self.assertEqual(id(r), id(copy(r)))
623        self.assertEqual(id(r), id(deepcopy(r)))
624        self.assertNotEqual(id(dr), id(copy(dr)))
625        self.assertNotEqual(id(dr), id(deepcopy(dr)))
626        self.assertTypedEquals(dr, copy(dr))
627        self.assertTypedEquals(dr, deepcopy(dr))
628
629    def test_slots(self):
630        # Issue 4998
631        r = F(13, 7)
632        self.assertRaises(AttributeError, setattr, r, 'a', 10)
633
634if __name__ == '__main__':
635    unittest.main()
636