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