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