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