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