Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 1 | # Originally contributed by Sjoerd Mullender. |
| 2 | # Significantly modified by Jeffrey Yasskin <jyasskin at gmail.com>. |
| 3 | |
| 4 | """Rational, infinite-precision, real numbers.""" |
| 5 | |
| 6 | from __future__ import division |
| 7 | import math |
| 8 | import numbers |
| 9 | import operator |
Jeffrey Yasskin | 45169fb | 2008-01-19 09:56:06 +0000 | [diff] [blame] | 10 | import re |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 11 | |
Raymond Hettinger | cf98f03 | 2008-05-08 04:36:12 +0000 | [diff] [blame] | 12 | __all__ = ['Fraction', 'gcd'] |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 13 | |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 14 | Rational = numbers.Rational |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 15 | |
| 16 | |
Jeffrey Yasskin | 3e1a373 | 2008-01-27 05:40:35 +0000 | [diff] [blame] | 17 | def gcd(a, b): |
| 18 | """Calculate the Greatest Common Divisor of a and b. |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 19 | |
| 20 | Unless b==0, the result will have the same sign as b (so that when |
| 21 | b is divided by it, the result comes out positive). |
| 22 | """ |
| 23 | while b: |
| 24 | a, b = b, a%b |
| 25 | return a |
| 26 | |
| 27 | |
Mark Dickinson | 1dabdb2 | 2008-02-02 17:16:13 +0000 | [diff] [blame] | 28 | _RATIONAL_FORMAT = re.compile(r""" |
| 29 | \A\s* # optional whitespace at the start, then |
| 30 | (?P<sign>[-+]?) # an optional sign, then |
| 31 | (?=\d|\.\d) # lookahead for digit or .digit |
| 32 | (?P<num>\d*) # numerator (possibly empty) |
Mark Dickinson | 8100bd8 | 2009-04-22 18:15:25 +0000 | [diff] [blame] | 33 | (?: # followed by |
| 34 | (?:/(?P<denom>\d+))? # an optional denominator |
Mark Dickinson | 1dabdb2 | 2008-02-02 17:16:13 +0000 | [diff] [blame] | 35 | | # or |
Mark Dickinson | 8100bd8 | 2009-04-22 18:15:25 +0000 | [diff] [blame] | 36 | (?:\.(?P<decimal>\d*))? # an optional fractional part |
| 37 | (?:E(?P<exp>[-+]?\d+))? # and optional exponent |
| 38 | ) |
Mark Dickinson | 1dabdb2 | 2008-02-02 17:16:13 +0000 | [diff] [blame] | 39 | \s*\Z # and optional whitespace to finish |
Mark Dickinson | 8100bd8 | 2009-04-22 18:15:25 +0000 | [diff] [blame] | 40 | """, re.VERBOSE | re.IGNORECASE) |
Jeffrey Yasskin | 45169fb | 2008-01-19 09:56:06 +0000 | [diff] [blame] | 41 | |
| 42 | |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 43 | class Fraction(Rational): |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 44 | """This class implements rational numbers. |
| 45 | |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 46 | Fraction(8, 6) will produce a rational number equivalent to |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 47 | 4/3. Both arguments must be Integral. The numerator defaults to 0 |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 48 | and the denominator defaults to 1 so that Fraction(3) == 3 and |
| 49 | Fraction() == 0. |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 50 | |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 51 | Fractions can also be constructed from strings of the form |
Jeffrey Yasskin | 3e1a373 | 2008-01-27 05:40:35 +0000 | [diff] [blame] | 52 | '[-+]?[0-9]+((/|.)[0-9]+)?', optionally surrounded by spaces. |
Jeffrey Yasskin | 45169fb | 2008-01-19 09:56:06 +0000 | [diff] [blame] | 53 | |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 54 | """ |
| 55 | |
Jeffrey Yasskin | dc2964b | 2008-02-01 07:05:46 +0000 | [diff] [blame] | 56 | __slots__ = ('_numerator', '_denominator') |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 57 | |
Jeffrey Yasskin | 45169fb | 2008-01-19 09:56:06 +0000 | [diff] [blame] | 58 | # We're immutable, so use __new__ not __init__ |
Mark Dickinson | 4af8e74 | 2009-04-24 13:56:07 +0000 | [diff] [blame^] | 59 | def __new__(cls, numerator=0, denominator=None): |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 60 | """Constructs a Fraction. |
Jeffrey Yasskin | 45169fb | 2008-01-19 09:56:06 +0000 | [diff] [blame] | 61 | |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 62 | Takes a string like '3/2' or '1.5', another Fraction, or a |
Jeffrey Yasskin | 3e1a373 | 2008-01-27 05:40:35 +0000 | [diff] [blame] | 63 | numerator/denominator pair. |
Jeffrey Yasskin | 45169fb | 2008-01-19 09:56:06 +0000 | [diff] [blame] | 64 | |
| 65 | """ |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 66 | self = super(Fraction, cls).__new__(cls) |
Jeffrey Yasskin | 45169fb | 2008-01-19 09:56:06 +0000 | [diff] [blame] | 67 | |
Mark Dickinson | 4af8e74 | 2009-04-24 13:56:07 +0000 | [diff] [blame^] | 68 | if denominator is None: |
| 69 | if isinstance(numerator, Rational): |
| 70 | self._numerator = numerator.numerator |
| 71 | self._denominator = numerator.denominator |
| 72 | return self |
| 73 | |
| 74 | elif isinstance(numerator, basestring): |
Jeffrey Yasskin | 45169fb | 2008-01-19 09:56:06 +0000 | [diff] [blame] | 75 | # Handle construction from strings. |
Mark Dickinson | 8100bd8 | 2009-04-22 18:15:25 +0000 | [diff] [blame] | 76 | m = _RATIONAL_FORMAT.match(numerator) |
Jeffrey Yasskin | 45169fb | 2008-01-19 09:56:06 +0000 | [diff] [blame] | 77 | if m is None: |
Mark Dickinson | 8100bd8 | 2009-04-22 18:15:25 +0000 | [diff] [blame] | 78 | raise ValueError('Invalid literal for Fraction: %r' % |
| 79 | numerator) |
| 80 | numerator = int(m.group('num') or '0') |
| 81 | denom = m.group('denom') |
| 82 | if denom: |
| 83 | denominator = int(denom) |
Jeffrey Yasskin | 3e1a373 | 2008-01-27 05:40:35 +0000 | [diff] [blame] | 84 | else: |
Mark Dickinson | 8100bd8 | 2009-04-22 18:15:25 +0000 | [diff] [blame] | 85 | denominator = 1 |
| 86 | decimal = m.group('decimal') |
| 87 | if decimal: |
| 88 | scale = 10**len(decimal) |
| 89 | numerator = numerator * scale + int(decimal) |
| 90 | denominator *= scale |
| 91 | exp = m.group('exp') |
| 92 | if exp: |
| 93 | exp = int(exp) |
| 94 | if exp >= 0: |
| 95 | numerator *= 10**exp |
| 96 | else: |
| 97 | denominator *= 10**-exp |
Jeffrey Yasskin | 45169fb | 2008-01-19 09:56:06 +0000 | [diff] [blame] | 98 | if m.group('sign') == '-': |
| 99 | numerator = -numerator |
| 100 | |
Mark Dickinson | 4af8e74 | 2009-04-24 13:56:07 +0000 | [diff] [blame^] | 101 | else: |
| 102 | raise TypeError("argument should be a string " |
| 103 | "or a Rational instance") |
| 104 | |
| 105 | elif (isinstance(numerator, Rational) and |
| 106 | isinstance(denominator, Rational)): |
| 107 | numerator, denominator = ( |
| 108 | numerator.numerator * denominator.denominator, |
| 109 | denominator.numerator * numerator.denominator |
| 110 | ) |
| 111 | else: |
| 112 | raise TypeError("both arguments should be " |
| 113 | "Rational instances") |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 114 | |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 115 | if denominator == 0: |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 116 | raise ZeroDivisionError('Fraction(%s, 0)' % numerator) |
Jeffrey Yasskin | 3e1a373 | 2008-01-27 05:40:35 +0000 | [diff] [blame] | 117 | g = gcd(numerator, denominator) |
Jeffrey Yasskin | 1c214d6 | 2008-02-14 06:12:24 +0000 | [diff] [blame] | 118 | self._numerator = numerator // g |
| 119 | self._denominator = denominator // g |
Jeffrey Yasskin | 45169fb | 2008-01-19 09:56:06 +0000 | [diff] [blame] | 120 | return self |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 121 | |
Mark Dickinson | 0aa52a1 | 2008-02-12 21:40:53 +0000 | [diff] [blame] | 122 | @classmethod |
| 123 | def from_float(cls, f): |
Jeffrey Yasskin | 45169fb | 2008-01-19 09:56:06 +0000 | [diff] [blame] | 124 | """Converts a finite float to a rational number, exactly. |
| 125 | |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 126 | Beware that Fraction.from_float(0.3) != Fraction(3, 10). |
Jeffrey Yasskin | 45169fb | 2008-01-19 09:56:06 +0000 | [diff] [blame] | 127 | |
| 128 | """ |
Raymond Hettinger | b01713e | 2008-07-10 14:34:57 +0000 | [diff] [blame] | 129 | if isinstance(f, numbers.Integral): |
Georg Brandl | fe42789 | 2009-01-03 22:03:11 +0000 | [diff] [blame] | 130 | return cls(f) |
Raymond Hettinger | b01713e | 2008-07-10 14:34:57 +0000 | [diff] [blame] | 131 | elif not isinstance(f, float): |
Mark Dickinson | 0aa52a1 | 2008-02-12 21:40:53 +0000 | [diff] [blame] | 132 | raise TypeError("%s.from_float() only takes floats, not %r (%s)" % |
| 133 | (cls.__name__, f, type(f).__name__)) |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 134 | if math.isnan(f) or math.isinf(f): |
Mark Dickinson | 0aa52a1 | 2008-02-12 21:40:53 +0000 | [diff] [blame] | 135 | raise TypeError("Cannot convert %r to %s." % (f, cls.__name__)) |
| 136 | return cls(*f.as_integer_ratio()) |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 137 | |
Mark Dickinson | 0aa52a1 | 2008-02-12 21:40:53 +0000 | [diff] [blame] | 138 | @classmethod |
| 139 | def from_decimal(cls, dec): |
Jeffrey Yasskin | 45169fb | 2008-01-19 09:56:06 +0000 | [diff] [blame] | 140 | """Converts a finite Decimal instance to a rational number, exactly.""" |
| 141 | from decimal import Decimal |
Raymond Hettinger | b01713e | 2008-07-10 14:34:57 +0000 | [diff] [blame] | 142 | if isinstance(dec, numbers.Integral): |
| 143 | dec = Decimal(int(dec)) |
| 144 | elif not isinstance(dec, Decimal): |
Jeffrey Yasskin | 45169fb | 2008-01-19 09:56:06 +0000 | [diff] [blame] | 145 | raise TypeError( |
Mark Dickinson | 0aa52a1 | 2008-02-12 21:40:53 +0000 | [diff] [blame] | 146 | "%s.from_decimal() only takes Decimals, not %r (%s)" % |
| 147 | (cls.__name__, dec, type(dec).__name__)) |
Jeffrey Yasskin | 45169fb | 2008-01-19 09:56:06 +0000 | [diff] [blame] | 148 | if not dec.is_finite(): |
| 149 | # Catches infinities and nans. |
Mark Dickinson | 0aa52a1 | 2008-02-12 21:40:53 +0000 | [diff] [blame] | 150 | raise TypeError("Cannot convert %s to %s." % (dec, cls.__name__)) |
Jeffrey Yasskin | 45169fb | 2008-01-19 09:56:06 +0000 | [diff] [blame] | 151 | sign, digits, exp = dec.as_tuple() |
| 152 | digits = int(''.join(map(str, digits))) |
| 153 | if sign: |
| 154 | digits = -digits |
| 155 | if exp >= 0: |
Mark Dickinson | 0aa52a1 | 2008-02-12 21:40:53 +0000 | [diff] [blame] | 156 | return cls(digits * 10 ** exp) |
Jeffrey Yasskin | 45169fb | 2008-01-19 09:56:06 +0000 | [diff] [blame] | 157 | else: |
Mark Dickinson | 0aa52a1 | 2008-02-12 21:40:53 +0000 | [diff] [blame] | 158 | return cls(digits, 10 ** -exp) |
Jeffrey Yasskin | 45169fb | 2008-01-19 09:56:06 +0000 | [diff] [blame] | 159 | |
Mark Dickinson | e1b8247 | 2008-02-12 21:31:59 +0000 | [diff] [blame] | 160 | def limit_denominator(self, max_denominator=1000000): |
| 161 | """Closest Fraction to self with denominator at most max_denominator. |
Raymond Hettinger | cf10926 | 2008-01-24 00:54:21 +0000 | [diff] [blame] | 162 | |
Mark Dickinson | e1b8247 | 2008-02-12 21:31:59 +0000 | [diff] [blame] | 163 | >>> Fraction('3.141592653589793').limit_denominator(10) |
| 164 | Fraction(22, 7) |
| 165 | >>> Fraction('3.141592653589793').limit_denominator(100) |
| 166 | Fraction(311, 99) |
| 167 | >>> Fraction(1234, 5678).limit_denominator(10000) |
| 168 | Fraction(1234, 5678) |
Raymond Hettinger | cf10926 | 2008-01-24 00:54:21 +0000 | [diff] [blame] | 169 | |
Mark Dickinson | e1b8247 | 2008-02-12 21:31:59 +0000 | [diff] [blame] | 170 | """ |
| 171 | # Algorithm notes: For any real number x, define a *best upper |
| 172 | # approximation* to x to be a rational number p/q such that: |
| 173 | # |
| 174 | # (1) p/q >= x, and |
| 175 | # (2) if p/q > r/s >= x then s > q, for any rational r/s. |
| 176 | # |
| 177 | # Define *best lower approximation* similarly. Then it can be |
| 178 | # proved that a rational number is a best upper or lower |
| 179 | # approximation to x if, and only if, it is a convergent or |
| 180 | # semiconvergent of the (unique shortest) continued fraction |
| 181 | # associated to x. |
| 182 | # |
| 183 | # To find a best rational approximation with denominator <= M, |
| 184 | # we find the best upper and lower approximations with |
| 185 | # denominator <= M and take whichever of these is closer to x. |
| 186 | # In the event of a tie, the bound with smaller denominator is |
| 187 | # chosen. If both denominators are equal (which can happen |
| 188 | # only when max_denominator == 1 and self is midway between |
| 189 | # two integers) the lower bound---i.e., the floor of self, is |
| 190 | # taken. |
| 191 | |
| 192 | if max_denominator < 1: |
| 193 | raise ValueError("max_denominator should be at least 1") |
Jeffrey Yasskin | 339f5e3 | 2008-02-14 07:49:25 +0000 | [diff] [blame] | 194 | if self._denominator <= max_denominator: |
Mark Dickinson | e1b8247 | 2008-02-12 21:31:59 +0000 | [diff] [blame] | 195 | return Fraction(self) |
| 196 | |
| 197 | p0, q0, p1, q1 = 0, 1, 1, 0 |
Jeffrey Yasskin | 339f5e3 | 2008-02-14 07:49:25 +0000 | [diff] [blame] | 198 | n, d = self._numerator, self._denominator |
Mark Dickinson | e1b8247 | 2008-02-12 21:31:59 +0000 | [diff] [blame] | 199 | while True: |
| 200 | a = n//d |
| 201 | q2 = q0+a*q1 |
| 202 | if q2 > max_denominator: |
Raymond Hettinger | cf10926 | 2008-01-24 00:54:21 +0000 | [diff] [blame] | 203 | break |
Mark Dickinson | e1b8247 | 2008-02-12 21:31:59 +0000 | [diff] [blame] | 204 | p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 |
| 205 | n, d = d, n-a*d |
| 206 | |
| 207 | k = (max_denominator-q0)//q1 |
| 208 | bound1 = Fraction(p0+k*p1, q0+k*q1) |
| 209 | bound2 = Fraction(p1, q1) |
| 210 | if abs(bound2 - self) <= abs(bound1-self): |
| 211 | return bound2 |
| 212 | else: |
| 213 | return bound1 |
Raymond Hettinger | cf10926 | 2008-01-24 00:54:21 +0000 | [diff] [blame] | 214 | |
Jeffrey Yasskin | dc2964b | 2008-02-01 07:05:46 +0000 | [diff] [blame] | 215 | @property |
| 216 | def numerator(a): |
| 217 | return a._numerator |
| 218 | |
| 219 | @property |
| 220 | def denominator(a): |
| 221 | return a._denominator |
| 222 | |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 223 | def __repr__(self): |
| 224 | """repr(self)""" |
Mark Dickinson | 3af386a | 2008-06-27 10:11:52 +0000 | [diff] [blame] | 225 | return ('Fraction(%s, %s)' % (self._numerator, self._denominator)) |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 226 | |
| 227 | def __str__(self): |
| 228 | """str(self)""" |
Jeffrey Yasskin | 339f5e3 | 2008-02-14 07:49:25 +0000 | [diff] [blame] | 229 | if self._denominator == 1: |
| 230 | return str(self._numerator) |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 231 | else: |
Jeffrey Yasskin | 339f5e3 | 2008-02-14 07:49:25 +0000 | [diff] [blame] | 232 | return '%s/%s' % (self._numerator, self._denominator) |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 233 | |
| 234 | def _operator_fallbacks(monomorphic_operator, fallback_operator): |
| 235 | """Generates forward and reverse operators given a purely-rational |
| 236 | operator and a function from the operator module. |
| 237 | |
| 238 | Use this like: |
| 239 | __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) |
| 240 | |
Jeffrey Yasskin | b23dea6 | 2008-01-31 07:44:11 +0000 | [diff] [blame] | 241 | In general, we want to implement the arithmetic operations so |
| 242 | that mixed-mode operations either call an implementation whose |
| 243 | author knew about the types of both arguments, or convert both |
| 244 | to the nearest built in type and do the operation there. In |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 245 | Fraction, that means that we define __add__ and __radd__ as: |
Jeffrey Yasskin | b23dea6 | 2008-01-31 07:44:11 +0000 | [diff] [blame] | 246 | |
| 247 | def __add__(self, other): |
Raymond Hettinger | 2df20a3 | 2008-01-31 22:07:16 +0000 | [diff] [blame] | 248 | # Both types have numerators/denominator attributes, |
| 249 | # so do the operation directly |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 250 | if isinstance(other, (int, long, Fraction)): |
| 251 | return Fraction(self.numerator * other.denominator + |
Jeffrey Yasskin | b23dea6 | 2008-01-31 07:44:11 +0000 | [diff] [blame] | 252 | other.numerator * self.denominator, |
| 253 | self.denominator * other.denominator) |
Raymond Hettinger | 2df20a3 | 2008-01-31 22:07:16 +0000 | [diff] [blame] | 254 | # float and complex don't have those operations, but we |
| 255 | # know about those types, so special case them. |
Jeffrey Yasskin | b23dea6 | 2008-01-31 07:44:11 +0000 | [diff] [blame] | 256 | elif isinstance(other, float): |
| 257 | return float(self) + other |
| 258 | elif isinstance(other, complex): |
| 259 | return complex(self) + other |
Raymond Hettinger | 2df20a3 | 2008-01-31 22:07:16 +0000 | [diff] [blame] | 260 | # Let the other type take over. |
| 261 | return NotImplemented |
Jeffrey Yasskin | b23dea6 | 2008-01-31 07:44:11 +0000 | [diff] [blame] | 262 | |
| 263 | def __radd__(self, other): |
| 264 | # radd handles more types than add because there's |
| 265 | # nothing left to fall back to. |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 266 | if isinstance(other, Rational): |
| 267 | return Fraction(self.numerator * other.denominator + |
Jeffrey Yasskin | b23dea6 | 2008-01-31 07:44:11 +0000 | [diff] [blame] | 268 | other.numerator * self.denominator, |
| 269 | self.denominator * other.denominator) |
| 270 | elif isinstance(other, Real): |
| 271 | return float(other) + float(self) |
| 272 | elif isinstance(other, Complex): |
| 273 | return complex(other) + complex(self) |
Raymond Hettinger | 2df20a3 | 2008-01-31 22:07:16 +0000 | [diff] [blame] | 274 | return NotImplemented |
Jeffrey Yasskin | b23dea6 | 2008-01-31 07:44:11 +0000 | [diff] [blame] | 275 | |
| 276 | |
| 277 | There are 5 different cases for a mixed-type addition on |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 278 | Fraction. I'll refer to all of the above code that doesn't |
| 279 | refer to Fraction, float, or complex as "boilerplate". 'r' |
| 280 | will be an instance of Fraction, which is a subtype of |
| 281 | Rational (r : Fraction <: Rational), and b : B <: |
Jeffrey Yasskin | b23dea6 | 2008-01-31 07:44:11 +0000 | [diff] [blame] | 282 | Complex. The first three involve 'r + b': |
| 283 | |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 284 | 1. If B <: Fraction, int, float, or complex, we handle |
Jeffrey Yasskin | b23dea6 | 2008-01-31 07:44:11 +0000 | [diff] [blame] | 285 | that specially, and all is well. |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 286 | 2. If Fraction falls back to the boilerplate code, and it |
Jeffrey Yasskin | b23dea6 | 2008-01-31 07:44:11 +0000 | [diff] [blame] | 287 | were to return a value from __add__, we'd miss the |
| 288 | possibility that B defines a more intelligent __radd__, |
| 289 | so the boilerplate should return NotImplemented from |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 290 | __add__. In particular, we don't handle Rational |
Jeffrey Yasskin | b23dea6 | 2008-01-31 07:44:11 +0000 | [diff] [blame] | 291 | here, even though we could get an exact answer, in case |
| 292 | the other type wants to do something special. |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 293 | 3. If B <: Fraction, Python tries B.__radd__ before |
| 294 | Fraction.__add__. This is ok, because it was |
| 295 | implemented with knowledge of Fraction, so it can |
Jeffrey Yasskin | b23dea6 | 2008-01-31 07:44:11 +0000 | [diff] [blame] | 296 | handle those instances before delegating to Real or |
| 297 | Complex. |
| 298 | |
| 299 | The next two situations describe 'b + r'. We assume that b |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 300 | didn't know about Fraction in its implementation, and that it |
Jeffrey Yasskin | b23dea6 | 2008-01-31 07:44:11 +0000 | [diff] [blame] | 301 | uses similar boilerplate code: |
| 302 | |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 303 | 4. If B <: Rational, then __radd_ converts both to the |
Jeffrey Yasskin | b23dea6 | 2008-01-31 07:44:11 +0000 | [diff] [blame] | 304 | builtin rational type (hey look, that's us) and |
| 305 | proceeds. |
| 306 | 5. Otherwise, __radd__ tries to find the nearest common |
| 307 | base ABC, and fall back to its builtin type. Since this |
| 308 | class doesn't subclass a concrete type, there's no |
| 309 | implementation to fall back to, so we need to try as |
| 310 | hard as possible to return an actual value, or the user |
| 311 | will get a TypeError. |
| 312 | |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 313 | """ |
| 314 | def forward(a, b): |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 315 | if isinstance(b, (int, long, Fraction)): |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 316 | return monomorphic_operator(a, b) |
| 317 | elif isinstance(b, float): |
| 318 | return fallback_operator(float(a), b) |
| 319 | elif isinstance(b, complex): |
| 320 | return fallback_operator(complex(a), b) |
| 321 | else: |
| 322 | return NotImplemented |
| 323 | forward.__name__ = '__' + fallback_operator.__name__ + '__' |
| 324 | forward.__doc__ = monomorphic_operator.__doc__ |
| 325 | |
| 326 | def reverse(b, a): |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 327 | if isinstance(a, Rational): |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 328 | # Includes ints. |
| 329 | return monomorphic_operator(a, b) |
| 330 | elif isinstance(a, numbers.Real): |
| 331 | return fallback_operator(float(a), float(b)) |
| 332 | elif isinstance(a, numbers.Complex): |
| 333 | return fallback_operator(complex(a), complex(b)) |
| 334 | else: |
| 335 | return NotImplemented |
| 336 | reverse.__name__ = '__r' + fallback_operator.__name__ + '__' |
| 337 | reverse.__doc__ = monomorphic_operator.__doc__ |
| 338 | |
| 339 | return forward, reverse |
| 340 | |
| 341 | def _add(a, b): |
| 342 | """a + b""" |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 343 | return Fraction(a.numerator * b.denominator + |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 344 | b.numerator * a.denominator, |
| 345 | a.denominator * b.denominator) |
| 346 | |
| 347 | __add__, __radd__ = _operator_fallbacks(_add, operator.add) |
| 348 | |
| 349 | def _sub(a, b): |
| 350 | """a - b""" |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 351 | return Fraction(a.numerator * b.denominator - |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 352 | b.numerator * a.denominator, |
| 353 | a.denominator * b.denominator) |
| 354 | |
| 355 | __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) |
| 356 | |
| 357 | def _mul(a, b): |
| 358 | """a * b""" |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 359 | return Fraction(a.numerator * b.numerator, a.denominator * b.denominator) |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 360 | |
| 361 | __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) |
| 362 | |
| 363 | def _div(a, b): |
| 364 | """a / b""" |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 365 | return Fraction(a.numerator * b.denominator, |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 366 | a.denominator * b.numerator) |
| 367 | |
| 368 | __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) |
| 369 | __div__, __rdiv__ = _operator_fallbacks(_div, operator.div) |
| 370 | |
Raymond Hettinger | 909e334 | 2008-01-24 23:50:26 +0000 | [diff] [blame] | 371 | def __floordiv__(a, b): |
| 372 | """a // b""" |
| 373 | # Will be math.floor(a / b) in 3.0. |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 374 | div = a / b |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 375 | if isinstance(div, Rational): |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 376 | # trunc(math.floor(div)) doesn't work if the rational is |
| 377 | # more precise than a float because the intermediate |
| 378 | # rounding may cross an integer boundary. |
| 379 | return div.numerator // div.denominator |
| 380 | else: |
| 381 | return math.floor(div) |
| 382 | |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 383 | def __rfloordiv__(b, a): |
| 384 | """a // b""" |
| 385 | # Will be math.floor(a / b) in 3.0. |
Raymond Hettinger | 909e334 | 2008-01-24 23:50:26 +0000 | [diff] [blame] | 386 | div = a / b |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 387 | if isinstance(div, Rational): |
Raymond Hettinger | 909e334 | 2008-01-24 23:50:26 +0000 | [diff] [blame] | 388 | # trunc(math.floor(div)) doesn't work if the rational is |
| 389 | # more precise than a float because the intermediate |
| 390 | # rounding may cross an integer boundary. |
| 391 | return div.numerator // div.denominator |
| 392 | else: |
| 393 | return math.floor(div) |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 394 | |
| 395 | def __mod__(a, b): |
| 396 | """a % b""" |
Raymond Hettinger | 909e334 | 2008-01-24 23:50:26 +0000 | [diff] [blame] | 397 | div = a // b |
| 398 | return a - b * div |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 399 | |
| 400 | def __rmod__(b, a): |
| 401 | """a % b""" |
Raymond Hettinger | 909e334 | 2008-01-24 23:50:26 +0000 | [diff] [blame] | 402 | div = a // b |
| 403 | return a - b * div |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 404 | |
| 405 | def __pow__(a, b): |
| 406 | """a ** b |
| 407 | |
| 408 | If b is not an integer, the result will be a float or complex |
| 409 | since roots are generally irrational. If b is an integer, the |
| 410 | result will be rational. |
| 411 | |
| 412 | """ |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 413 | if isinstance(b, Rational): |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 414 | if b.denominator == 1: |
| 415 | power = b.numerator |
| 416 | if power >= 0: |
Jeffrey Yasskin | 339f5e3 | 2008-02-14 07:49:25 +0000 | [diff] [blame] | 417 | return Fraction(a._numerator ** power, |
| 418 | a._denominator ** power) |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 419 | else: |
Jeffrey Yasskin | 339f5e3 | 2008-02-14 07:49:25 +0000 | [diff] [blame] | 420 | return Fraction(a._denominator ** -power, |
| 421 | a._numerator ** -power) |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 422 | else: |
| 423 | # A fractional power will generally produce an |
| 424 | # irrational number. |
| 425 | return float(a) ** float(b) |
| 426 | else: |
| 427 | return float(a) ** b |
| 428 | |
| 429 | def __rpow__(b, a): |
| 430 | """a ** b""" |
Jeffrey Yasskin | 339f5e3 | 2008-02-14 07:49:25 +0000 | [diff] [blame] | 431 | if b._denominator == 1 and b._numerator >= 0: |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 432 | # If a is an int, keep it that way if possible. |
Jeffrey Yasskin | 339f5e3 | 2008-02-14 07:49:25 +0000 | [diff] [blame] | 433 | return a ** b._numerator |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 434 | |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 435 | if isinstance(a, Rational): |
| 436 | return Fraction(a.numerator, a.denominator) ** b |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 437 | |
Jeffrey Yasskin | 339f5e3 | 2008-02-14 07:49:25 +0000 | [diff] [blame] | 438 | if b._denominator == 1: |
| 439 | return a ** b._numerator |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 440 | |
| 441 | return a ** float(b) |
| 442 | |
| 443 | def __pos__(a): |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 444 | """+a: Coerces a subclass instance to Fraction""" |
Jeffrey Yasskin | 339f5e3 | 2008-02-14 07:49:25 +0000 | [diff] [blame] | 445 | return Fraction(a._numerator, a._denominator) |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 446 | |
| 447 | def __neg__(a): |
| 448 | """-a""" |
Jeffrey Yasskin | 339f5e3 | 2008-02-14 07:49:25 +0000 | [diff] [blame] | 449 | return Fraction(-a._numerator, a._denominator) |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 450 | |
| 451 | def __abs__(a): |
| 452 | """abs(a)""" |
Jeffrey Yasskin | 339f5e3 | 2008-02-14 07:49:25 +0000 | [diff] [blame] | 453 | return Fraction(abs(a._numerator), a._denominator) |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 454 | |
| 455 | def __trunc__(a): |
| 456 | """trunc(a)""" |
Jeffrey Yasskin | 339f5e3 | 2008-02-14 07:49:25 +0000 | [diff] [blame] | 457 | if a._numerator < 0: |
| 458 | return -(-a._numerator // a._denominator) |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 459 | else: |
Jeffrey Yasskin | 339f5e3 | 2008-02-14 07:49:25 +0000 | [diff] [blame] | 460 | return a._numerator // a._denominator |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 461 | |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 462 | def __hash__(self): |
| 463 | """hash(self) |
| 464 | |
| 465 | Tricky because values that are exactly representable as a |
| 466 | float must have the same hash as that float. |
| 467 | |
| 468 | """ |
Raymond Hettinger | 921cb5d | 2008-01-25 00:33:45 +0000 | [diff] [blame] | 469 | # XXX since this method is expensive, consider caching the result |
Jeffrey Yasskin | 339f5e3 | 2008-02-14 07:49:25 +0000 | [diff] [blame] | 470 | if self._denominator == 1: |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 471 | # Get integers right. |
Jeffrey Yasskin | 339f5e3 | 2008-02-14 07:49:25 +0000 | [diff] [blame] | 472 | return hash(self._numerator) |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 473 | # Expensive check, but definitely correct. |
| 474 | if self == float(self): |
| 475 | return hash(float(self)) |
| 476 | else: |
| 477 | # Use tuple's hash to avoid a high collision rate on |
| 478 | # simple fractions. |
Jeffrey Yasskin | 339f5e3 | 2008-02-14 07:49:25 +0000 | [diff] [blame] | 479 | return hash((self._numerator, self._denominator)) |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 480 | |
| 481 | def __eq__(a, b): |
| 482 | """a == b""" |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 483 | if isinstance(b, Rational): |
Jeffrey Yasskin | 339f5e3 | 2008-02-14 07:49:25 +0000 | [diff] [blame] | 484 | return (a._numerator == b.numerator and |
| 485 | a._denominator == b.denominator) |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 486 | if isinstance(b, numbers.Complex) and b.imag == 0: |
| 487 | b = b.real |
| 488 | if isinstance(b, float): |
| 489 | return a == a.from_float(b) |
| 490 | else: |
| 491 | # XXX: If b.__eq__ is implemented like this method, it may |
| 492 | # give the wrong answer after float(a) changes a's |
| 493 | # value. Better ways of doing this are welcome. |
| 494 | return float(a) == b |
| 495 | |
| 496 | def _subtractAndCompareToZero(a, b, op): |
| 497 | """Helper function for comparison operators. |
| 498 | |
| 499 | Subtracts b from a, exactly if possible, and compares the |
| 500 | result with 0 using op, in such a way that the comparison |
| 501 | won't recurse. If the difference raises a TypeError, returns |
| 502 | NotImplemented instead. |
| 503 | |
| 504 | """ |
| 505 | if isinstance(b, numbers.Complex) and b.imag == 0: |
| 506 | b = b.real |
| 507 | if isinstance(b, float): |
| 508 | b = a.from_float(b) |
| 509 | try: |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 510 | # XXX: If b <: Real but not <: Rational, this is likely |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 511 | # to fall back to a float. If the actual values differ by |
| 512 | # less than MIN_FLOAT, this could falsely call them equal, |
| 513 | # which would make <= inconsistent with ==. Better ways of |
| 514 | # doing this are welcome. |
| 515 | diff = a - b |
| 516 | except TypeError: |
| 517 | return NotImplemented |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 518 | if isinstance(diff, Rational): |
Jeffrey Yasskin | d7b0033 | 2008-01-15 07:46:24 +0000 | [diff] [blame] | 519 | return op(diff.numerator, 0) |
| 520 | return op(diff, 0) |
| 521 | |
| 522 | def __lt__(a, b): |
| 523 | """a < b""" |
| 524 | return a._subtractAndCompareToZero(b, operator.lt) |
| 525 | |
| 526 | def __gt__(a, b): |
| 527 | """a > b""" |
| 528 | return a._subtractAndCompareToZero(b, operator.gt) |
| 529 | |
| 530 | def __le__(a, b): |
| 531 | """a <= b""" |
| 532 | return a._subtractAndCompareToZero(b, operator.le) |
| 533 | |
| 534 | def __ge__(a, b): |
| 535 | """a >= b""" |
| 536 | return a._subtractAndCompareToZero(b, operator.ge) |
| 537 | |
| 538 | def __nonzero__(a): |
| 539 | """a != 0""" |
Jeffrey Yasskin | 339f5e3 | 2008-02-14 07:49:25 +0000 | [diff] [blame] | 540 | return a._numerator != 0 |
Raymond Hettinger | a621674 | 2008-01-25 00:21:54 +0000 | [diff] [blame] | 541 | |
| 542 | # support for pickling, copy, and deepcopy |
| 543 | |
| 544 | def __reduce__(self): |
| 545 | return (self.__class__, (str(self),)) |
| 546 | |
| 547 | def __copy__(self): |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 548 | if type(self) == Fraction: |
Raymond Hettinger | a621674 | 2008-01-25 00:21:54 +0000 | [diff] [blame] | 549 | return self # I'm immutable; therefore I am my own clone |
Jeffrey Yasskin | 339f5e3 | 2008-02-14 07:49:25 +0000 | [diff] [blame] | 550 | return self.__class__(self._numerator, self._denominator) |
Raymond Hettinger | a621674 | 2008-01-25 00:21:54 +0000 | [diff] [blame] | 551 | |
| 552 | def __deepcopy__(self, memo): |
Mark Dickinson | d058cd2 | 2008-02-10 21:29:51 +0000 | [diff] [blame] | 553 | if type(self) == Fraction: |
Raymond Hettinger | a621674 | 2008-01-25 00:21:54 +0000 | [diff] [blame] | 554 | return self # My components are also immutable |
Jeffrey Yasskin | 339f5e3 | 2008-02-14 07:49:25 +0000 | [diff] [blame] | 555 | return self.__class__(self._numerator, self._denominator) |