fractions.py 23.4 KB
Newer Older
1 2 3
# Originally contributed by Sjoerd Mullender.
# Significantly modified by Jeffrey Yasskin <jyasskin at gmail.com>.

Christian Heimes's avatar
Christian Heimes committed
4
"""Fraction, infinite-precision, real numbers."""
5

6
from decimal import Decimal
7 8 9
import math
import numbers
import operator
10
import re
11
import sys
12

Raymond Hettinger's avatar
Raymond Hettinger committed
13
__all__ = ['Fraction', 'gcd']
14 15 16



17 18
def gcd(a, b):
    """Calculate the Greatest Common Divisor of a and b.
19 20 21 22

    Unless b==0, the result will have the same sign as b (so that when
    b is divided by it, the result comes out positive).
    """
23 24 25 26 27 28 29 30 31 32 33
    import warnings
    warnings.warn('fractions.gcd() is deprecated. Use math.gcd() instead.',
                  DeprecationWarning, 2)
    if type(a) is int is type(b):
        if (b or a) < 0:
            return -math.gcd(a, b)
        return math.gcd(a, b)
    return _gcd(a, b)

def _gcd(a, b):
    # Supports non-integers for backward compatibility.
34 35 36 37
    while b:
        a, b = b, a%b
    return a

38 39 40 41 42 43
# Constants related to the hash implementation;  hash(x) is based
# on the reduction of x modulo the prime _PyHASH_MODULUS.
_PyHASH_MODULUS = sys.hash_info.modulus
# Value to be used for rationals that reduce to infinity modulo
# _PyHASH_MODULUS.
_PyHASH_INF = sys.hash_info.inf
44

Christian Heimes's avatar
Christian Heimes committed
45 46 47 48 49
_RATIONAL_FORMAT = re.compile(r"""
    \A\s*                      # optional whitespace at the start, then
    (?P<sign>[-+]?)            # an optional sign, then
    (?=\d|\.\d)                # lookahead for digit or .digit
    (?P<num>\d*)               # numerator (possibly empty)
50 51
    (?:                        # followed by
       (?:/(?P<denom>\d+))?    # an optional denominator
Christian Heimes's avatar
Christian Heimes committed
52
    |                          # or
53 54 55
       (?:\.(?P<decimal>\d*))? # an optional fractional part
       (?:E(?P<exp>[-+]?\d+))? # and optional exponent
    )
Christian Heimes's avatar
Christian Heimes committed
56
    \s*\Z                      # and optional whitespace to finish
57
""", re.VERBOSE | re.IGNORECASE)
58 59


Christian Heimes's avatar
Christian Heimes committed
60
class Fraction(numbers.Rational):
61 62
    """This class implements rational numbers.

63 64 65 66
    In the two-argument form of the constructor, Fraction(8, 6) will
    produce a rational number equivalent to 4/3. Both arguments must
    be Rational. The numerator defaults to 0 and the denominator
    defaults to 1 so that Fraction(3) == 3 and Fraction() == 0.
67

68 69 70 71 72 73 74 75 76 77
    Fractions can also be constructed from:

      - numeric strings similar to those accepted by the
        float constructor (for example, '-2.3' or '1e10')

      - strings of the form '123/456'

      - float and Decimal instances

      - other Rational instances (including integers)
78

79 80
    """

81
    __slots__ = ('_numerator', '_denominator')
82

83
    # We're immutable, so use __new__ not __init__
84
    def __new__(cls, numerator=0, denominator=None, *, _normalize=True):
85 86
        """Constructs a Rational.

87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
        Takes a string like '3/2' or '1.5', another Rational instance, a
        numerator/denominator pair, or a float.

        Examples
        --------

        >>> Fraction(10, -8)
        Fraction(-5, 4)
        >>> Fraction(Fraction(1, 7), 5)
        Fraction(1, 35)
        >>> Fraction(Fraction(1, 7), Fraction(2, 3))
        Fraction(3, 14)
        >>> Fraction('314')
        Fraction(314, 1)
        >>> Fraction('-35/4')
        Fraction(-35, 4)
        >>> Fraction('3.1415') # conversion from numeric string
        Fraction(6283, 2000)
        >>> Fraction('-47e-2') # string may include a decimal exponent
        Fraction(-47, 100)
        >>> Fraction(1.47)  # direct construction from float (exact conversion)
        Fraction(6620291452234629, 4503599627370496)
        >>> Fraction(2.25)
        Fraction(9, 4)
        >>> Fraction(Decimal('1.47'))
        Fraction(147, 100)
113 114

        """
Christian Heimes's avatar
Christian Heimes committed
115
        self = super(Fraction, cls).__new__(cls)
116

117
        if denominator is None:
118 119 120 121 122 123
            if type(numerator) is int:
                self._numerator = numerator
                self._denominator = 1
                return self

            elif isinstance(numerator, numbers.Rational):
124 125 126 127
                self._numerator = numerator.numerator
                self._denominator = numerator.denominator
                return self

128 129 130
            elif isinstance(numerator, (float, Decimal)):
                # Exact conversion
                self._numerator, self._denominator = numerator.as_integer_ratio()
131 132
                return self

133
            elif isinstance(numerator, str):
134
                # Handle construction from strings.
135
                m = _RATIONAL_FORMAT.match(numerator)
136
                if m is None:
137 138 139 140 141 142
                    raise ValueError('Invalid literal for Fraction: %r' %
                                     numerator)
                numerator = int(m.group('num') or '0')
                denom = m.group('denom')
                if denom:
                    denominator = int(denom)
143
                else:
144 145 146 147 148 149 150 151 152 153 154 155 156
                    denominator = 1
                    decimal = m.group('decimal')
                    if decimal:
                        scale = 10**len(decimal)
                        numerator = numerator * scale + int(decimal)
                        denominator *= scale
                    exp = m.group('exp')
                    if exp:
                        exp = int(exp)
                        if exp >= 0:
                            numerator *= 10**exp
                        else:
                            denominator *= 10**-exp
157 158 159
                if m.group('sign') == '-':
                    numerator = -numerator

160 161 162 163
            else:
                raise TypeError("argument should be a string "
                                "or a Rational instance")

164
        elif type(numerator) is int is type(denominator):
165
            pass # *very* normal case
166

167 168 169 170 171 172 173 174 175
        elif (isinstance(numerator, numbers.Rational) and
            isinstance(denominator, numbers.Rational)):
            numerator, denominator = (
                numerator.numerator * denominator.denominator,
                denominator.numerator * numerator.denominator
                )
        else:
            raise TypeError("both arguments should be "
                            "Rational instances")
176 177

        if denominator == 0:
Christian Heimes's avatar
Christian Heimes committed
178
            raise ZeroDivisionError('Fraction(%s, 0)' % numerator)
179
        if _normalize:
180 181 182 183 184 185 186
            if type(numerator) is int is type(denominator):
                # *very* normal case
                g = math.gcd(numerator, denominator)
                if denominator < 0:
                    g = -g
            else:
                g = _gcd(numerator, denominator)
187 188 189 190
            numerator //= g
            denominator //= g
        self._numerator = numerator
        self._denominator = denominator
191
        return self
192 193 194

    @classmethod
    def from_float(cls, f):
195 196
        """Converts a finite float to a rational number, exactly.

Christian Heimes's avatar
Christian Heimes committed
197
        Beware that Fraction.from_float(0.3) != Fraction(3, 10).
198 199

        """
Georg Brandl's avatar
Georg Brandl committed
200
        if isinstance(f, numbers.Integral):
201
            return cls(f)
Georg Brandl's avatar
Georg Brandl committed
202
        elif not isinstance(f, float):
203 204
            raise TypeError("%s.from_float() only takes floats, not %r (%s)" %
                            (cls.__name__, f, type(f).__name__))
205
        return cls(*f.as_integer_ratio())
206

207 208 209 210
    @classmethod
    def from_decimal(cls, dec):
        """Converts a finite Decimal instance to a rational number, exactly."""
        from decimal import Decimal
Georg Brandl's avatar
Georg Brandl committed
211 212 213
        if isinstance(dec, numbers.Integral):
            dec = Decimal(int(dec))
        elif not isinstance(dec, Decimal):
214 215 216
            raise TypeError(
                "%s.from_decimal() only takes Decimals, not %r (%s)" %
                (cls.__name__, dec, type(dec).__name__))
217
        return cls(*dec.as_integer_ratio())
218

Christian Heimes's avatar
Christian Heimes committed
219 220 221 222 223 224 225
    def limit_denominator(self, max_denominator=1000000):
        """Closest Fraction to self with denominator at most max_denominator.

        >>> Fraction('3.141592653589793').limit_denominator(10)
        Fraction(22, 7)
        >>> Fraction('3.141592653589793').limit_denominator(100)
        Fraction(311, 99)
226 227
        >>> Fraction(4321, 8765).limit_denominator(10000)
        Fraction(4321, 8765)
Christian Heimes's avatar
Christian Heimes committed
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261

        """
        # Algorithm notes: For any real number x, define a *best upper
        # approximation* to x to be a rational number p/q such that:
        #
        #   (1) p/q >= x, and
        #   (2) if p/q > r/s >= x then s > q, for any rational r/s.
        #
        # Define *best lower approximation* similarly.  Then it can be
        # proved that a rational number is a best upper or lower
        # approximation to x if, and only if, it is a convergent or
        # semiconvergent of the (unique shortest) continued fraction
        # associated to x.
        #
        # To find a best rational approximation with denominator <= M,
        # we find the best upper and lower approximations with
        # denominator <= M and take whichever of these is closer to x.
        # In the event of a tie, the bound with smaller denominator is
        # chosen.  If both denominators are equal (which can happen
        # only when max_denominator == 1 and self is midway between
        # two integers) the lower bound---i.e., the floor of self, is
        # taken.

        if max_denominator < 1:
            raise ValueError("max_denominator should be at least 1")
        if self._denominator <= max_denominator:
            return Fraction(self)

        p0, q0, p1, q1 = 0, 1, 1, 0
        n, d = self._numerator, self._denominator
        while True:
            a = n//d
            q2 = q0+a*q1
            if q2 > max_denominator:
262
                break
Christian Heimes's avatar
Christian Heimes committed
263 264 265 266 267 268 269 270 271 272
            p0, q0, p1, q1 = p1, q1, p0+a*p1, q2
            n, d = d, n-a*d

        k = (max_denominator-q0)//q1
        bound1 = Fraction(p0+k*p1, q0+k*q1)
        bound2 = Fraction(p1, q1)
        if abs(bound2 - self) <= abs(bound1-self):
            return bound2
        else:
            return bound1
273

274 275 276 277 278 279 280 281
    @property
    def numerator(a):
        return a._numerator

    @property
    def denominator(a):
        return a._denominator

282 283
    def __repr__(self):
        """repr(self)"""
284 285
        return '%s(%s, %s)' % (self.__class__.__name__,
                               self._numerator, self._denominator)
286 287 288

    def __str__(self):
        """str(self)"""
Christian Heimes's avatar
Christian Heimes committed
289 290
        if self._denominator == 1:
            return str(self._numerator)
291
        else:
Christian Heimes's avatar
Christian Heimes committed
292
            return '%s/%s' % (self._numerator, self._denominator)
293 294 295 296 297 298 299 300

    def _operator_fallbacks(monomorphic_operator, fallback_operator):
        """Generates forward and reverse operators given a purely-rational
        operator and a function from the operator module.

        Use this like:
        __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op)

301 302 303 304
        In general, we want to implement the arithmetic operations so
        that mixed-mode operations either call an implementation whose
        author knew about the types of both arguments, or convert both
        to the nearest built in type and do the operation there. In
Christian Heimes's avatar
Christian Heimes committed
305
        Fraction, that means that we define __add__ and __radd__ as:
306 307

            def __add__(self, other):
308 309
                # Both types have numerators/denominator attributes,
                # so do the operation directly
Christian Heimes's avatar
Christian Heimes committed
310 311
                if isinstance(other, (int, Fraction)):
                    return Fraction(self.numerator * other.denominator +
312 313
                                    other.numerator * self.denominator,
                                    self.denominator * other.denominator)
314 315
                # float and complex don't have those operations, but we
                # know about those types, so special case them.
316 317 318 319
                elif isinstance(other, float):
                    return float(self) + other
                elif isinstance(other, complex):
                    return complex(self) + other
320 321
                # Let the other type take over.
                return NotImplemented
322 323 324 325

            def __radd__(self, other):
                # radd handles more types than add because there's
                # nothing left to fall back to.
Christian Heimes's avatar
Christian Heimes committed
326 327
                if isinstance(other, numbers.Rational):
                    return Fraction(self.numerator * other.denominator +
328 329 330 331 332 333
                                    other.numerator * self.denominator,
                                    self.denominator * other.denominator)
                elif isinstance(other, Real):
                    return float(other) + float(self)
                elif isinstance(other, Complex):
                    return complex(other) + complex(self)
334
                return NotImplemented
335 336 337


        There are 5 different cases for a mixed-type addition on
Christian Heimes's avatar
Christian Heimes committed
338 339 340 341
        Fraction. I'll refer to all of the above code that doesn't
        refer to Fraction, float, or complex as "boilerplate". 'r'
        will be an instance of Fraction, which is a subtype of
        Rational (r : Fraction <: Rational), and b : B <:
342 343
        Complex. The first three involve 'r + b':

Christian Heimes's avatar
Christian Heimes committed
344
            1. If B <: Fraction, int, float, or complex, we handle
345
               that specially, and all is well.
Christian Heimes's avatar
Christian Heimes committed
346
            2. If Fraction falls back to the boilerplate code, and it
347 348 349
               were to return a value from __add__, we'd miss the
               possibility that B defines a more intelligent __radd__,
               so the boilerplate should return NotImplemented from
Christian Heimes's avatar
Christian Heimes committed
350
               __add__. In particular, we don't handle Rational
351 352
               here, even though we could get an exact answer, in case
               the other type wants to do something special.
Christian Heimes's avatar
Christian Heimes committed
353 354 355
            3. If B <: Fraction, Python tries B.__radd__ before
               Fraction.__add__. This is ok, because it was
               implemented with knowledge of Fraction, so it can
356 357 358 359
               handle those instances before delegating to Real or
               Complex.

        The next two situations describe 'b + r'. We assume that b
Christian Heimes's avatar
Christian Heimes committed
360
        didn't know about Fraction in its implementation, and that it
361 362
        uses similar boilerplate code:

Christian Heimes's avatar
Christian Heimes committed
363
            4. If B <: Rational, then __radd_ converts both to the
364 365 366 367 368 369 370 371 372
               builtin rational type (hey look, that's us) and
               proceeds.
            5. Otherwise, __radd__ tries to find the nearest common
               base ABC, and fall back to its builtin type. Since this
               class doesn't subclass a concrete type, there's no
               implementation to fall back to, so we need to try as
               hard as possible to return an actual value, or the user
               will get a TypeError.

373 374
        """
        def forward(a, b):
Christian Heimes's avatar
Christian Heimes committed
375
            if isinstance(b, (int, Fraction)):
376 377 378 379 380 381 382 383 384 385 386
                return monomorphic_operator(a, b)
            elif isinstance(b, float):
                return fallback_operator(float(a), b)
            elif isinstance(b, complex):
                return fallback_operator(complex(a), b)
            else:
                return NotImplemented
        forward.__name__ = '__' + fallback_operator.__name__ + '__'
        forward.__doc__ = monomorphic_operator.__doc__

        def reverse(b, a):
Christian Heimes's avatar
Christian Heimes committed
387
            if isinstance(a, numbers.Rational):
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
                # Includes ints.
                return monomorphic_operator(a, b)
            elif isinstance(a, numbers.Real):
                return fallback_operator(float(a), float(b))
            elif isinstance(a, numbers.Complex):
                return fallback_operator(complex(a), complex(b))
            else:
                return NotImplemented
        reverse.__name__ = '__r' + fallback_operator.__name__ + '__'
        reverse.__doc__ = monomorphic_operator.__doc__

        return forward, reverse

    def _add(a, b):
        """a + b"""
403 404 405
        da, db = a.denominator, b.denominator
        return Fraction(a.numerator * db + b.numerator * da,
                        da * db)
406 407 408 409 410

    __add__, __radd__ = _operator_fallbacks(_add, operator.add)

    def _sub(a, b):
        """a - b"""
411 412 413
        da, db = a.denominator, b.denominator
        return Fraction(a.numerator * db - b.numerator * da,
                        da * db)
414 415 416 417 418

    __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub)

    def _mul(a, b):
        """a * b"""
Christian Heimes's avatar
Christian Heimes committed
419
        return Fraction(a.numerator * b.numerator, a.denominator * b.denominator)
420 421 422 423 424

    __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul)

    def _div(a, b):
        """a / b"""
Christian Heimes's avatar
Christian Heimes committed
425
        return Fraction(a.numerator * b.denominator,
426 427 428 429
                        a.denominator * b.numerator)

    __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv)

430
    def _floordiv(a, b):
431
        """a // b"""
432
        return (a.numerator * b.denominator) // (a.denominator * b.numerator)
433

434
    __floordiv__, __rfloordiv__ = _operator_fallbacks(_floordiv, operator.floordiv)
435

436 437 438 439 440 441 442 443
    def _divmod(a, b):
        """(a // b, a % b)"""
        da, db = a.denominator, b.denominator
        div, n_mod = divmod(a.numerator * db, da * b.numerator)
        return div, Fraction(n_mod, da * db)

    __divmod__, __rdivmod__ = _operator_fallbacks(_divmod, divmod)

444
    def _mod(a, b):
445
        """a % b"""
446 447
        da, db = a.denominator, b.denominator
        return Fraction((a.numerator * db) % (b.numerator * da), da * db)
448

449
    __mod__, __rmod__ = _operator_fallbacks(_mod, operator.mod)
450 451 452 453 454 455 456 457 458

    def __pow__(a, b):
        """a ** b

        If b is not an integer, the result will be a float or complex
        since roots are generally irrational. If b is an integer, the
        result will be rational.

        """
Christian Heimes's avatar
Christian Heimes committed
459
        if isinstance(b, numbers.Rational):
460 461 462
            if b.denominator == 1:
                power = b.numerator
                if power >= 0:
Christian Heimes's avatar
Christian Heimes committed
463
                    return Fraction(a._numerator ** power,
464 465
                                    a._denominator ** power,
                                    _normalize=False)
466
                elif a._numerator >= 0:
Christian Heimes's avatar
Christian Heimes committed
467
                    return Fraction(a._denominator ** -power,
468 469
                                    a._numerator ** -power,
                                    _normalize=False)
470 471 472 473
                else:
                    return Fraction((-a._denominator) ** -power,
                                    (-a._numerator) ** -power,
                                    _normalize=False)
474 475 476 477 478 479 480 481 482
            else:
                # A fractional power will generally produce an
                # irrational number.
                return float(a) ** float(b)
        else:
            return float(a) ** b

    def __rpow__(b, a):
        """a ** b"""
Christian Heimes's avatar
Christian Heimes committed
483
        if b._denominator == 1 and b._numerator >= 0:
484
            # If a is an int, keep it that way if possible.
Christian Heimes's avatar
Christian Heimes committed
485
            return a ** b._numerator
486

Christian Heimes's avatar
Christian Heimes committed
487 488
        if isinstance(a, numbers.Rational):
            return Fraction(a.numerator, a.denominator) ** b
489

Christian Heimes's avatar
Christian Heimes committed
490 491
        if b._denominator == 1:
            return a ** b._numerator
492 493 494 495

        return a ** float(b)

    def __pos__(a):
Christian Heimes's avatar
Christian Heimes committed
496
        """+a: Coerces a subclass instance to Fraction"""
497
        return Fraction(a._numerator, a._denominator, _normalize=False)
498 499 500

    def __neg__(a):
        """-a"""
501
        return Fraction(-a._numerator, a._denominator, _normalize=False)
502 503 504

    def __abs__(a):
        """abs(a)"""
505
        return Fraction(abs(a._numerator), a._denominator, _normalize=False)
506 507 508

    def __trunc__(a):
        """trunc(a)"""
Christian Heimes's avatar
Christian Heimes committed
509 510
        if a._numerator < 0:
            return -(-a._numerator // a._denominator)
511
        else:
Christian Heimes's avatar
Christian Heimes committed
512
            return a._numerator // a._denominator
513 514

    def __floor__(a):
515
        """math.floor(a)"""
516 517 518
        return a.numerator // a.denominator

    def __ceil__(a):
519
        """math.ceil(a)"""
520 521 522 523
        # The negations cleverly convince floordiv to return the ceiling.
        return -(-a.numerator // a.denominator)

    def __round__(self, ndigits=None):
524
        """round(self, ndigits)
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540

        Rounds half toward even.
        """
        if ndigits is None:
            floor, remainder = divmod(self.numerator, self.denominator)
            if remainder * 2 < self.denominator:
                return floor
            elif remainder * 2 > self.denominator:
                return floor + 1
            # Deal with the half case:
            elif floor % 2 == 0:
                return floor
            else:
                return floor + 1
        shift = 10**abs(ndigits)
        # See _operator_fallbacks.forward to check that the results of
Christian Heimes's avatar
Christian Heimes committed
541
        # these operations will always be Fraction and therefore have
542
        # round().
543
        if ndigits > 0:
Christian Heimes's avatar
Christian Heimes committed
544
            return Fraction(round(self * shift), shift)
545
        else:
Christian Heimes's avatar
Christian Heimes committed
546
            return Fraction(round(self / shift) * shift)
547 548

    def __hash__(self):
549
        """hash(self)"""
550

551
        # XXX since this method is expensive, consider caching the result
552 553 554 555 556 557 558 559 560 561 562 563 564

        # In order to make sure that the hash of a Fraction agrees
        # with the hash of a numerically equal integer, float or
        # Decimal instance, we follow the rules for numeric hashes
        # outlined in the documentation.  (See library docs, 'Built-in
        # Types').

        # dinv is the inverse of self._denominator modulo the prime
        # _PyHASH_MODULUS, or 0 if self._denominator is divisible by
        # _PyHASH_MODULUS.
        dinv = pow(self._denominator, _PyHASH_MODULUS - 2, _PyHASH_MODULUS)
        if not dinv:
            hash_ = _PyHASH_INF
565
        else:
566
            hash_ = abs(self._numerator) * dinv % _PyHASH_MODULUS
567 568
        result = hash_ if self >= 0 else -hash_
        return -2 if result == -1 else result
569 570 571

    def __eq__(a, b):
        """a == b"""
572 573
        if type(b) is int:
            return a._numerator == b and a._denominator == 1
Christian Heimes's avatar
Christian Heimes committed
574
        if isinstance(b, numbers.Rational):
Christian Heimes's avatar
Christian Heimes committed
575 576
            return (a._numerator == b.numerator and
                    a._denominator == b.denominator)
577 578 579
        if isinstance(b, numbers.Complex) and b.imag == 0:
            b = b.real
        if isinstance(b, float):
580 581 582 583 584 585
            if math.isnan(b) or math.isinf(b):
                # comparisons with an infinity or nan should behave in
                # the same way for any finite a, so treat a as zero.
                return 0.0 == b
            else:
                return a == a.from_float(b)
586
        else:
587 588 589
            # Since a doesn't know how to compare with b, let's give b
            # a chance to compare itself with a.
            return NotImplemented
590

591 592
    def _richcmp(self, other, op):
        """Helper for comparison operators, for internal use only.
593

594 595 596 597 598
        Implement comparison between a Rational instance `self`, and
        either another Rational instance or a float `other`.  If
        `other` is not a Rational instance or a float, return
        NotImplemented. `op` should be one of the six standard
        comparison operators.
599 600

        """
601 602 603 604 605 606 607 608 609 610
        # convert other to a Rational instance where reasonable.
        if isinstance(other, numbers.Rational):
            return op(self._numerator * other.denominator,
                      self._denominator * other.numerator)
        if isinstance(other, float):
            if math.isnan(other) or math.isinf(other):
                return op(0.0, other)
            else:
                return op(self, self.from_float(other))
        else:
611 612 613 614
            return NotImplemented

    def __lt__(a, b):
        """a < b"""
615
        return a._richcmp(b, operator.lt)
616 617 618

    def __gt__(a, b):
        """a > b"""
619
        return a._richcmp(b, operator.gt)
620 621 622

    def __le__(a, b):
        """a <= b"""
623
        return a._richcmp(b, operator.le)
624 625 626

    def __ge__(a, b):
        """a >= b"""
627
        return a._richcmp(b, operator.ge)
628 629 630

    def __bool__(a):
        """a != 0"""
Christian Heimes's avatar
Christian Heimes committed
631
        return a._numerator != 0
632 633 634 635 636 637 638

    # support for pickling, copy, and deepcopy

    def __reduce__(self):
        return (self.__class__, (str(self),))

    def __copy__(self):
Christian Heimes's avatar
Christian Heimes committed
639
        if type(self) == Fraction:
640
            return self     # I'm immutable; therefore I am my own clone
Christian Heimes's avatar
Christian Heimes committed
641
        return self.__class__(self._numerator, self._denominator)
642 643

    def __deepcopy__(self, memo):
Christian Heimes's avatar
Christian Heimes committed
644
        if type(self) == Fraction:
645
            return self     # My components are also immutable
Christian Heimes's avatar
Christian Heimes committed
646
        return self.__class__(self._numerator, self._denominator)