2008-01-15 03:46:24 -04:00
|
|
|
# Originally contributed by Sjoerd Mullender.
|
|
|
|
# Significantly modified by Jeffrey Yasskin <jyasskin at gmail.com>.
|
|
|
|
|
|
|
|
"""Rational, infinite-precision, real numbers."""
|
|
|
|
|
|
|
|
from __future__ import division
|
|
|
|
import math
|
|
|
|
import numbers
|
|
|
|
import operator
|
2008-01-19 05:56:06 -04:00
|
|
|
import re
|
2008-01-15 03:46:24 -04:00
|
|
|
|
2008-05-08 01:36:12 -03:00
|
|
|
__all__ = ['Fraction', 'gcd']
|
2008-01-15 03:46:24 -04:00
|
|
|
|
2008-02-10 17:29:51 -04:00
|
|
|
Rational = numbers.Rational
|
2008-01-15 03:46:24 -04:00
|
|
|
|
|
|
|
|
2008-01-27 01:40:35 -04:00
|
|
|
def gcd(a, b):
|
|
|
|
"""Calculate the Greatest Common Divisor of a and b.
|
2008-01-15 03:46:24 -04:00
|
|
|
|
|
|
|
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).
|
|
|
|
"""
|
|
|
|
while b:
|
|
|
|
a, b = b, a%b
|
|
|
|
return a
|
|
|
|
|
|
|
|
|
2008-02-02 13:16:13 -04:00
|
|
|
_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)
|
2009-04-22 15:15:25 -03:00
|
|
|
(?: # followed by
|
|
|
|
(?:/(?P<denom>\d+))? # an optional denominator
|
2008-02-02 13:16:13 -04:00
|
|
|
| # or
|
2009-04-22 15:15:25 -03:00
|
|
|
(?:\.(?P<decimal>\d*))? # an optional fractional part
|
|
|
|
(?:E(?P<exp>[-+]?\d+))? # and optional exponent
|
|
|
|
)
|
2008-02-02 13:16:13 -04:00
|
|
|
\s*\Z # and optional whitespace to finish
|
2009-04-22 15:15:25 -03:00
|
|
|
""", re.VERBOSE | re.IGNORECASE)
|
2008-01-19 05:56:06 -04:00
|
|
|
|
|
|
|
|
2008-02-10 17:29:51 -04:00
|
|
|
class Fraction(Rational):
|
2008-01-15 03:46:24 -04:00
|
|
|
"""This class implements rational numbers.
|
|
|
|
|
2008-02-10 17:29:51 -04:00
|
|
|
Fraction(8, 6) will produce a rational number equivalent to
|
2008-01-15 03:46:24 -04:00
|
|
|
4/3. Both arguments must be Integral. The numerator defaults to 0
|
2008-02-10 17:29:51 -04:00
|
|
|
and the denominator defaults to 1 so that Fraction(3) == 3 and
|
|
|
|
Fraction() == 0.
|
2008-01-15 03:46:24 -04:00
|
|
|
|
2008-02-10 17:29:51 -04:00
|
|
|
Fractions can also be constructed from strings of the form
|
2008-01-27 01:40:35 -04:00
|
|
|
'[-+]?[0-9]+((/|.)[0-9]+)?', optionally surrounded by spaces.
|
2008-01-19 05:56:06 -04:00
|
|
|
|
2008-01-15 03:46:24 -04:00
|
|
|
"""
|
|
|
|
|
2008-02-01 03:05:46 -04:00
|
|
|
__slots__ = ('_numerator', '_denominator')
|
2008-01-15 03:46:24 -04:00
|
|
|
|
2008-01-19 05:56:06 -04:00
|
|
|
# We're immutable, so use __new__ not __init__
|
2009-04-24 10:56:07 -03:00
|
|
|
def __new__(cls, numerator=0, denominator=None):
|
2008-02-10 17:29:51 -04:00
|
|
|
"""Constructs a Fraction.
|
2008-01-19 05:56:06 -04:00
|
|
|
|
2008-02-10 17:29:51 -04:00
|
|
|
Takes a string like '3/2' or '1.5', another Fraction, or a
|
2008-01-27 01:40:35 -04:00
|
|
|
numerator/denominator pair.
|
2008-01-19 05:56:06 -04:00
|
|
|
|
|
|
|
"""
|
2008-02-10 17:29:51 -04:00
|
|
|
self = super(Fraction, cls).__new__(cls)
|
2008-01-19 05:56:06 -04:00
|
|
|
|
2009-04-24 10:56:07 -03:00
|
|
|
if denominator is None:
|
|
|
|
if isinstance(numerator, Rational):
|
|
|
|
self._numerator = numerator.numerator
|
|
|
|
self._denominator = numerator.denominator
|
|
|
|
return self
|
|
|
|
|
|
|
|
elif isinstance(numerator, basestring):
|
2008-01-19 05:56:06 -04:00
|
|
|
# Handle construction from strings.
|
2009-04-22 15:15:25 -03:00
|
|
|
m = _RATIONAL_FORMAT.match(numerator)
|
2008-01-19 05:56:06 -04:00
|
|
|
if m is None:
|
2009-04-22 15:15:25 -03:00
|
|
|
raise ValueError('Invalid literal for Fraction: %r' %
|
|
|
|
numerator)
|
|
|
|
numerator = int(m.group('num') or '0')
|
|
|
|
denom = m.group('denom')
|
|
|
|
if denom:
|
|
|
|
denominator = int(denom)
|
2008-01-27 01:40:35 -04:00
|
|
|
else:
|
2009-04-22 15:15:25 -03:00
|
|
|
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
|
2008-01-19 05:56:06 -04:00
|
|
|
if m.group('sign') == '-':
|
|
|
|
numerator = -numerator
|
|
|
|
|
2009-04-24 10:56:07 -03:00
|
|
|
else:
|
|
|
|
raise TypeError("argument should be a string "
|
|
|
|
"or a Rational instance")
|
|
|
|
|
|
|
|
elif (isinstance(numerator, Rational) and
|
|
|
|
isinstance(denominator, Rational)):
|
|
|
|
numerator, denominator = (
|
|
|
|
numerator.numerator * denominator.denominator,
|
|
|
|
denominator.numerator * numerator.denominator
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
raise TypeError("both arguments should be "
|
|
|
|
"Rational instances")
|
2008-01-15 03:46:24 -04:00
|
|
|
|
|
|
|
if denominator == 0:
|
2008-02-10 17:29:51 -04:00
|
|
|
raise ZeroDivisionError('Fraction(%s, 0)' % numerator)
|
2008-01-27 01:40:35 -04:00
|
|
|
g = gcd(numerator, denominator)
|
2008-02-14 02:12:24 -04:00
|
|
|
self._numerator = numerator // g
|
|
|
|
self._denominator = denominator // g
|
2008-01-19 05:56:06 -04:00
|
|
|
return self
|
2008-01-15 03:46:24 -04:00
|
|
|
|
2008-02-12 17:40:53 -04:00
|
|
|
@classmethod
|
|
|
|
def from_float(cls, f):
|
2008-01-19 05:56:06 -04:00
|
|
|
"""Converts a finite float to a rational number, exactly.
|
|
|
|
|
2008-02-10 17:29:51 -04:00
|
|
|
Beware that Fraction.from_float(0.3) != Fraction(3, 10).
|
2008-01-19 05:56:06 -04:00
|
|
|
|
|
|
|
"""
|
2008-07-10 11:34:57 -03:00
|
|
|
if isinstance(f, numbers.Integral):
|
2009-01-03 18:03:11 -04:00
|
|
|
return cls(f)
|
2008-07-10 11:34:57 -03:00
|
|
|
elif not isinstance(f, float):
|
2008-02-12 17:40:53 -04:00
|
|
|
raise TypeError("%s.from_float() only takes floats, not %r (%s)" %
|
|
|
|
(cls.__name__, f, type(f).__name__))
|
2008-01-15 03:46:24 -04:00
|
|
|
if math.isnan(f) or math.isinf(f):
|
2008-02-12 17:40:53 -04:00
|
|
|
raise TypeError("Cannot convert %r to %s." % (f, cls.__name__))
|
|
|
|
return cls(*f.as_integer_ratio())
|
2008-01-15 03:46:24 -04:00
|
|
|
|
2008-02-12 17:40:53 -04:00
|
|
|
@classmethod
|
|
|
|
def from_decimal(cls, dec):
|
2008-01-19 05:56:06 -04:00
|
|
|
"""Converts a finite Decimal instance to a rational number, exactly."""
|
|
|
|
from decimal import Decimal
|
2008-07-10 11:34:57 -03:00
|
|
|
if isinstance(dec, numbers.Integral):
|
|
|
|
dec = Decimal(int(dec))
|
|
|
|
elif not isinstance(dec, Decimal):
|
2008-01-19 05:56:06 -04:00
|
|
|
raise TypeError(
|
2008-02-12 17:40:53 -04:00
|
|
|
"%s.from_decimal() only takes Decimals, not %r (%s)" %
|
|
|
|
(cls.__name__, dec, type(dec).__name__))
|
2008-01-19 05:56:06 -04:00
|
|
|
if not dec.is_finite():
|
|
|
|
# Catches infinities and nans.
|
2008-02-12 17:40:53 -04:00
|
|
|
raise TypeError("Cannot convert %s to %s." % (dec, cls.__name__))
|
2008-01-19 05:56:06 -04:00
|
|
|
sign, digits, exp = dec.as_tuple()
|
|
|
|
digits = int(''.join(map(str, digits)))
|
|
|
|
if sign:
|
|
|
|
digits = -digits
|
|
|
|
if exp >= 0:
|
2008-02-12 17:40:53 -04:00
|
|
|
return cls(digits * 10 ** exp)
|
2008-01-19 05:56:06 -04:00
|
|
|
else:
|
2008-02-12 17:40:53 -04:00
|
|
|
return cls(digits, 10 ** -exp)
|
2008-01-19 05:56:06 -04:00
|
|
|
|
2008-02-12 17:31:59 -04:00
|
|
|
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)
|
2009-11-23 12:23:43 -04:00
|
|
|
>>> Fraction(4321, 8765).limit_denominator(10000)
|
|
|
|
Fraction(4321, 8765)
|
2008-02-12 17:31:59 -04:00
|
|
|
|
|
|
|
"""
|
|
|
|
# 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")
|
2008-02-14 03:49:25 -04:00
|
|
|
if self._denominator <= max_denominator:
|
2008-02-12 17:31:59 -04:00
|
|
|
return Fraction(self)
|
|
|
|
|
|
|
|
p0, q0, p1, q1 = 0, 1, 1, 0
|
2008-02-14 03:49:25 -04:00
|
|
|
n, d = self._numerator, self._denominator
|
2008-02-12 17:31:59 -04:00
|
|
|
while True:
|
|
|
|
a = n//d
|
|
|
|
q2 = q0+a*q1
|
|
|
|
if q2 > max_denominator:
|
2008-01-23 20:54:21 -04:00
|
|
|
break
|
2008-02-12 17:31:59 -04:00
|
|
|
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
|
2008-01-23 20:54:21 -04:00
|
|
|
|
2008-02-01 03:05:46 -04:00
|
|
|
@property
|
|
|
|
def numerator(a):
|
|
|
|
return a._numerator
|
|
|
|
|
|
|
|
@property
|
|
|
|
def denominator(a):
|
|
|
|
return a._denominator
|
|
|
|
|
2008-01-15 03:46:24 -04:00
|
|
|
def __repr__(self):
|
|
|
|
"""repr(self)"""
|
2008-06-27 07:11:52 -03:00
|
|
|
return ('Fraction(%s, %s)' % (self._numerator, self._denominator))
|
2008-01-15 03:46:24 -04:00
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
"""str(self)"""
|
2008-02-14 03:49:25 -04:00
|
|
|
if self._denominator == 1:
|
|
|
|
return str(self._numerator)
|
2008-01-15 03:46:24 -04:00
|
|
|
else:
|
2008-02-14 03:49:25 -04:00
|
|
|
return '%s/%s' % (self._numerator, self._denominator)
|
2008-01-15 03:46:24 -04:00
|
|
|
|
|
|
|
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)
|
|
|
|
|
2008-01-31 03:44:11 -04:00
|
|
|
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
|
2008-02-10 17:29:51 -04:00
|
|
|
Fraction, that means that we define __add__ and __radd__ as:
|
2008-01-31 03:44:11 -04:00
|
|
|
|
|
|
|
def __add__(self, other):
|
2008-01-31 18:07:16 -04:00
|
|
|
# Both types have numerators/denominator attributes,
|
|
|
|
# so do the operation directly
|
2008-02-10 17:29:51 -04:00
|
|
|
if isinstance(other, (int, long, Fraction)):
|
|
|
|
return Fraction(self.numerator * other.denominator +
|
2008-01-31 03:44:11 -04:00
|
|
|
other.numerator * self.denominator,
|
|
|
|
self.denominator * other.denominator)
|
2008-01-31 18:07:16 -04:00
|
|
|
# float and complex don't have those operations, but we
|
|
|
|
# know about those types, so special case them.
|
2008-01-31 03:44:11 -04:00
|
|
|
elif isinstance(other, float):
|
|
|
|
return float(self) + other
|
|
|
|
elif isinstance(other, complex):
|
|
|
|
return complex(self) + other
|
2008-01-31 18:07:16 -04:00
|
|
|
# Let the other type take over.
|
|
|
|
return NotImplemented
|
2008-01-31 03:44:11 -04:00
|
|
|
|
|
|
|
def __radd__(self, other):
|
|
|
|
# radd handles more types than add because there's
|
|
|
|
# nothing left to fall back to.
|
2008-02-10 17:29:51 -04:00
|
|
|
if isinstance(other, Rational):
|
|
|
|
return Fraction(self.numerator * other.denominator +
|
2008-01-31 03:44:11 -04:00
|
|
|
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)
|
2008-01-31 18:07:16 -04:00
|
|
|
return NotImplemented
|
2008-01-31 03:44:11 -04:00
|
|
|
|
|
|
|
|
|
|
|
There are 5 different cases for a mixed-type addition on
|
2008-02-10 17:29:51 -04:00
|
|
|
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 <:
|
2008-01-31 03:44:11 -04:00
|
|
|
Complex. The first three involve 'r + b':
|
|
|
|
|
2008-02-10 17:29:51 -04:00
|
|
|
1. If B <: Fraction, int, float, or complex, we handle
|
2008-01-31 03:44:11 -04:00
|
|
|
that specially, and all is well.
|
2008-02-10 17:29:51 -04:00
|
|
|
2. If Fraction falls back to the boilerplate code, and it
|
2008-01-31 03:44:11 -04:00
|
|
|
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
|
2008-02-10 17:29:51 -04:00
|
|
|
__add__. In particular, we don't handle Rational
|
2008-01-31 03:44:11 -04:00
|
|
|
here, even though we could get an exact answer, in case
|
|
|
|
the other type wants to do something special.
|
2008-02-10 17:29:51 -04:00
|
|
|
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
|
2008-01-31 03:44:11 -04:00
|
|
|
handle those instances before delegating to Real or
|
|
|
|
Complex.
|
|
|
|
|
|
|
|
The next two situations describe 'b + r'. We assume that b
|
2008-02-10 17:29:51 -04:00
|
|
|
didn't know about Fraction in its implementation, and that it
|
2008-01-31 03:44:11 -04:00
|
|
|
uses similar boilerplate code:
|
|
|
|
|
2008-02-10 17:29:51 -04:00
|
|
|
4. If B <: Rational, then __radd_ converts both to the
|
2008-01-31 03:44:11 -04:00
|
|
|
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.
|
|
|
|
|
2008-01-15 03:46:24 -04:00
|
|
|
"""
|
|
|
|
def forward(a, b):
|
2008-02-10 17:29:51 -04:00
|
|
|
if isinstance(b, (int, long, Fraction)):
|
2008-01-15 03:46:24 -04:00
|
|
|
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):
|
2008-02-10 17:29:51 -04:00
|
|
|
if isinstance(a, Rational):
|
2008-01-15 03:46:24 -04:00
|
|
|
# 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"""
|
2008-02-10 17:29:51 -04:00
|
|
|
return Fraction(a.numerator * b.denominator +
|
2008-01-15 03:46:24 -04:00
|
|
|
b.numerator * a.denominator,
|
|
|
|
a.denominator * b.denominator)
|
|
|
|
|
|
|
|
__add__, __radd__ = _operator_fallbacks(_add, operator.add)
|
|
|
|
|
|
|
|
def _sub(a, b):
|
|
|
|
"""a - b"""
|
2008-02-10 17:29:51 -04:00
|
|
|
return Fraction(a.numerator * b.denominator -
|
2008-01-15 03:46:24 -04:00
|
|
|
b.numerator * a.denominator,
|
|
|
|
a.denominator * b.denominator)
|
|
|
|
|
|
|
|
__sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub)
|
|
|
|
|
|
|
|
def _mul(a, b):
|
|
|
|
"""a * b"""
|
2008-02-10 17:29:51 -04:00
|
|
|
return Fraction(a.numerator * b.numerator, a.denominator * b.denominator)
|
2008-01-15 03:46:24 -04:00
|
|
|
|
|
|
|
__mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul)
|
|
|
|
|
|
|
|
def _div(a, b):
|
|
|
|
"""a / b"""
|
2008-02-10 17:29:51 -04:00
|
|
|
return Fraction(a.numerator * b.denominator,
|
2008-01-15 03:46:24 -04:00
|
|
|
a.denominator * b.numerator)
|
|
|
|
|
|
|
|
__truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv)
|
|
|
|
__div__, __rdiv__ = _operator_fallbacks(_div, operator.div)
|
|
|
|
|
2008-01-24 19:50:26 -04:00
|
|
|
def __floordiv__(a, b):
|
|
|
|
"""a // b"""
|
|
|
|
# Will be math.floor(a / b) in 3.0.
|
2008-01-15 03:46:24 -04:00
|
|
|
div = a / b
|
2008-02-10 17:29:51 -04:00
|
|
|
if isinstance(div, Rational):
|
2008-01-15 03:46:24 -04:00
|
|
|
# trunc(math.floor(div)) doesn't work if the rational is
|
|
|
|
# more precise than a float because the intermediate
|
|
|
|
# rounding may cross an integer boundary.
|
|
|
|
return div.numerator // div.denominator
|
|
|
|
else:
|
|
|
|
return math.floor(div)
|
|
|
|
|
|
|
|
def __rfloordiv__(b, a):
|
|
|
|
"""a // b"""
|
|
|
|
# Will be math.floor(a / b) in 3.0.
|
2008-01-24 19:50:26 -04:00
|
|
|
div = a / b
|
2008-02-10 17:29:51 -04:00
|
|
|
if isinstance(div, Rational):
|
2008-01-24 19:50:26 -04:00
|
|
|
# trunc(math.floor(div)) doesn't work if the rational is
|
|
|
|
# more precise than a float because the intermediate
|
|
|
|
# rounding may cross an integer boundary.
|
|
|
|
return div.numerator // div.denominator
|
|
|
|
else:
|
|
|
|
return math.floor(div)
|
2008-01-15 03:46:24 -04:00
|
|
|
|
|
|
|
def __mod__(a, b):
|
|
|
|
"""a % b"""
|
2008-01-24 19:50:26 -04:00
|
|
|
div = a // b
|
|
|
|
return a - b * div
|
2008-01-15 03:46:24 -04:00
|
|
|
|
|
|
|
def __rmod__(b, a):
|
|
|
|
"""a % b"""
|
2008-01-24 19:50:26 -04:00
|
|
|
div = a // b
|
|
|
|
return a - b * div
|
2008-01-15 03:46:24 -04:00
|
|
|
|
|
|
|
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.
|
|
|
|
|
|
|
|
"""
|
2008-02-10 17:29:51 -04:00
|
|
|
if isinstance(b, Rational):
|
2008-01-15 03:46:24 -04:00
|
|
|
if b.denominator == 1:
|
|
|
|
power = b.numerator
|
|
|
|
if power >= 0:
|
2008-02-14 03:49:25 -04:00
|
|
|
return Fraction(a._numerator ** power,
|
|
|
|
a._denominator ** power)
|
2008-01-15 03:46:24 -04:00
|
|
|
else:
|
2008-02-14 03:49:25 -04:00
|
|
|
return Fraction(a._denominator ** -power,
|
|
|
|
a._numerator ** -power)
|
2008-01-15 03:46:24 -04:00
|
|
|
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"""
|
2008-02-14 03:49:25 -04:00
|
|
|
if b._denominator == 1 and b._numerator >= 0:
|
2008-01-15 03:46:24 -04:00
|
|
|
# If a is an int, keep it that way if possible.
|
2008-02-14 03:49:25 -04:00
|
|
|
return a ** b._numerator
|
2008-01-15 03:46:24 -04:00
|
|
|
|
2008-02-10 17:29:51 -04:00
|
|
|
if isinstance(a, Rational):
|
|
|
|
return Fraction(a.numerator, a.denominator) ** b
|
2008-01-15 03:46:24 -04:00
|
|
|
|
2008-02-14 03:49:25 -04:00
|
|
|
if b._denominator == 1:
|
|
|
|
return a ** b._numerator
|
2008-01-15 03:46:24 -04:00
|
|
|
|
|
|
|
return a ** float(b)
|
|
|
|
|
|
|
|
def __pos__(a):
|
2008-02-10 17:29:51 -04:00
|
|
|
"""+a: Coerces a subclass instance to Fraction"""
|
2008-02-14 03:49:25 -04:00
|
|
|
return Fraction(a._numerator, a._denominator)
|
2008-01-15 03:46:24 -04:00
|
|
|
|
|
|
|
def __neg__(a):
|
|
|
|
"""-a"""
|
2008-02-14 03:49:25 -04:00
|
|
|
return Fraction(-a._numerator, a._denominator)
|
2008-01-15 03:46:24 -04:00
|
|
|
|
|
|
|
def __abs__(a):
|
|
|
|
"""abs(a)"""
|
2008-02-14 03:49:25 -04:00
|
|
|
return Fraction(abs(a._numerator), a._denominator)
|
2008-01-15 03:46:24 -04:00
|
|
|
|
|
|
|
def __trunc__(a):
|
|
|
|
"""trunc(a)"""
|
2008-02-14 03:49:25 -04:00
|
|
|
if a._numerator < 0:
|
|
|
|
return -(-a._numerator // a._denominator)
|
2008-01-15 03:46:24 -04:00
|
|
|
else:
|
2008-02-14 03:49:25 -04:00
|
|
|
return a._numerator // a._denominator
|
2008-01-15 03:46:24 -04:00
|
|
|
|
|
|
|
def __hash__(self):
|
|
|
|
"""hash(self)
|
|
|
|
|
|
|
|
Tricky because values that are exactly representable as a
|
|
|
|
float must have the same hash as that float.
|
|
|
|
|
|
|
|
"""
|
2008-01-24 20:33:45 -04:00
|
|
|
# XXX since this method is expensive, consider caching the result
|
2008-02-14 03:49:25 -04:00
|
|
|
if self._denominator == 1:
|
2008-01-15 03:46:24 -04:00
|
|
|
# Get integers right.
|
2008-02-14 03:49:25 -04:00
|
|
|
return hash(self._numerator)
|
2008-01-15 03:46:24 -04:00
|
|
|
# Expensive check, but definitely correct.
|
|
|
|
if self == float(self):
|
|
|
|
return hash(float(self))
|
|
|
|
else:
|
|
|
|
# Use tuple's hash to avoid a high collision rate on
|
|
|
|
# simple fractions.
|
2008-02-14 03:49:25 -04:00
|
|
|
return hash((self._numerator, self._denominator))
|
2008-01-15 03:46:24 -04:00
|
|
|
|
|
|
|
def __eq__(a, b):
|
|
|
|
"""a == b"""
|
2008-02-10 17:29:51 -04:00
|
|
|
if isinstance(b, Rational):
|
2008-02-14 03:49:25 -04:00
|
|
|
return (a._numerator == b.numerator and
|
|
|
|
a._denominator == b.denominator)
|
2008-01-15 03:46:24 -04:00
|
|
|
if isinstance(b, numbers.Complex) and b.imag == 0:
|
|
|
|
b = b.real
|
|
|
|
if isinstance(b, float):
|
2009-07-18 12:18:18 -03:00
|
|
|
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)
|
2008-01-15 03:46:24 -04:00
|
|
|
else:
|
2009-07-18 12:18:18 -03:00
|
|
|
# Since a doesn't know how to compare with b, let's give b
|
|
|
|
# a chance to compare itself with a.
|
|
|
|
return NotImplemented
|
2008-01-15 03:46:24 -04:00
|
|
|
|
2009-07-18 12:18:18 -03:00
|
|
|
def _richcmp(self, other, op):
|
|
|
|
"""Helper for comparison operators, for internal use only.
|
2008-01-15 03:46:24 -04:00
|
|
|
|
2009-07-18 12:18:18 -03:00
|
|
|
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.
|
2008-01-15 03:46:24 -04:00
|
|
|
|
|
|
|
"""
|
2009-07-18 12:18:18 -03:00
|
|
|
# convert other to a Rational instance where reasonable.
|
|
|
|
if isinstance(other, Rational):
|
|
|
|
return op(self._numerator * other.denominator,
|
|
|
|
self._denominator * other.numerator)
|
2010-03-27 08:09:29 -03:00
|
|
|
# comparisons with complex should raise a TypeError, for consistency
|
|
|
|
# with int<->complex, float<->complex, and complex<->complex comparisons.
|
|
|
|
if isinstance(other, complex):
|
|
|
|
raise TypeError("no ordering relation is defined for complex numbers")
|
2009-07-18 12:18:18 -03:00
|
|
|
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:
|
2008-01-15 03:46:24 -04:00
|
|
|
return NotImplemented
|
|
|
|
|
|
|
|
def __lt__(a, b):
|
|
|
|
"""a < b"""
|
2009-07-18 12:18:18 -03:00
|
|
|
return a._richcmp(b, operator.lt)
|
2008-01-15 03:46:24 -04:00
|
|
|
|
|
|
|
def __gt__(a, b):
|
|
|
|
"""a > b"""
|
2009-07-18 12:18:18 -03:00
|
|
|
return a._richcmp(b, operator.gt)
|
2008-01-15 03:46:24 -04:00
|
|
|
|
|
|
|
def __le__(a, b):
|
|
|
|
"""a <= b"""
|
2009-07-18 12:18:18 -03:00
|
|
|
return a._richcmp(b, operator.le)
|
2008-01-15 03:46:24 -04:00
|
|
|
|
|
|
|
def __ge__(a, b):
|
|
|
|
"""a >= b"""
|
2009-07-18 12:18:18 -03:00
|
|
|
return a._richcmp(b, operator.ge)
|
2008-01-15 03:46:24 -04:00
|
|
|
|
|
|
|
def __nonzero__(a):
|
|
|
|
"""a != 0"""
|
2008-02-14 03:49:25 -04:00
|
|
|
return a._numerator != 0
|
2008-01-24 20:21:54 -04:00
|
|
|
|
|
|
|
# support for pickling, copy, and deepcopy
|
|
|
|
|
|
|
|
def __reduce__(self):
|
|
|
|
return (self.__class__, (str(self),))
|
|
|
|
|
|
|
|
def __copy__(self):
|
2008-02-10 17:29:51 -04:00
|
|
|
if type(self) == Fraction:
|
2008-01-24 20:21:54 -04:00
|
|
|
return self # I'm immutable; therefore I am my own clone
|
2008-02-14 03:49:25 -04:00
|
|
|
return self.__class__(self._numerator, self._denominator)
|
2008-01-24 20:21:54 -04:00
|
|
|
|
|
|
|
def __deepcopy__(self, memo):
|
2008-02-10 17:29:51 -04:00
|
|
|
if type(self) == Fraction:
|
2008-01-24 20:21:54 -04:00
|
|
|
return self # My components are also immutable
|
2008-02-14 03:49:25 -04:00
|
|
|
return self.__class__(self._numerator, self._denominator)
|