blob: 5ddc84c1a5959cd480c869799ffbd2f2b012d676 [file] [log] [blame]
Guido van Rossum7736b5b2008-01-15 21:44:53 +00001# Originally contributed by Sjoerd Mullender.
2# Significantly modified by Jeffrey Yasskin <jyasskin at gmail.com>.
3
Christian Heimes3feef612008-02-11 06:19:17 +00004"""Fraction, infinite-precision, real numbers."""
Guido van Rossum7736b5b2008-01-15 21:44:53 +00005
Mark Dickinson98127c32010-04-03 11:18:52 +00006from decimal import Decimal
Guido van Rossum7736b5b2008-01-15 21:44:53 +00007import math
8import numbers
9import operator
Christian Heimes587c2bf2008-01-19 16:21:02 +000010import re
Mark Dickinsondc787d22010-05-23 13:33:13 +000011import sys
Guido van Rossum7736b5b2008-01-15 21:44:53 +000012
Raymond Hettingere580f5c2008-05-08 16:03:04 +000013__all__ = ['Fraction', 'gcd']
Guido van Rossum7736b5b2008-01-15 21:44:53 +000014
Guido van Rossum7736b5b2008-01-15 21:44:53 +000015
16
Christian Heimesaf98da12008-01-27 15:18:18 +000017def gcd(a, b):
18 """Calculate the Greatest Common Divisor of a and b.
Guido van Rossum7736b5b2008-01-15 21:44:53 +000019
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 Dickinsondc787d22010-05-23 13:33:13 +000027# 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 Rossum7736b5b2008-01-15 21:44:53 +000033
Christian Heimes292d3512008-02-03 16:51:08 +000034_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 Dickinsoncf63f2f2009-04-22 17:50:21 +000039 (?: # followed by
40 (?:/(?P<denom>\d+))? # an optional denominator
Christian Heimes292d3512008-02-03 16:51:08 +000041 | # or
Mark Dickinsoncf63f2f2009-04-22 17:50:21 +000042 (?:\.(?P<decimal>\d*))? # an optional fractional part
43 (?:E(?P<exp>[-+]?\d+))? # and optional exponent
44 )
Christian Heimes292d3512008-02-03 16:51:08 +000045 \s*\Z # and optional whitespace to finish
Mark Dickinsoncf63f2f2009-04-22 17:50:21 +000046""", re.VERBOSE | re.IGNORECASE)
Christian Heimes587c2bf2008-01-19 16:21:02 +000047
48
Christian Heimes3feef612008-02-11 06:19:17 +000049class Fraction(numbers.Rational):
Guido van Rossum7736b5b2008-01-15 21:44:53 +000050 """This class implements rational numbers.
51
Mark Dickinson98127c32010-04-03 11:18:52 +000052 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 Rossum7736b5b2008-01-15 21:44:53 +000056
Mark Dickinson98127c32010-04-03 11:18:52 +000057 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 Heimes587c2bf2008-01-19 16:21:02 +000067
Guido van Rossum7736b5b2008-01-15 21:44:53 +000068 """
69
Christian Heimes400adb02008-02-01 08:12:03 +000070 __slots__ = ('_numerator', '_denominator')
Guido van Rossum7736b5b2008-01-15 21:44:53 +000071
Christian Heimes587c2bf2008-01-19 16:21:02 +000072 # We're immutable, so use __new__ not __init__
Mark Dickinson3c286e22014-04-05 09:29:00 +010073 def __new__(cls, numerator=0, denominator=None, _normalize=True):
Christian Heimes587c2bf2008-01-19 16:21:02 +000074 """Constructs a Rational.
75
Mark Dickinson98127c32010-04-03 11:18:52 +000076 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 Heimes587c2bf2008-01-19 16:21:02 +0000102
103 """
Christian Heimes3feef612008-02-11 06:19:17 +0000104 self = super(Fraction, cls).__new__(cls)
Christian Heimes587c2bf2008-01-19 16:21:02 +0000105
Mark Dickinsond4d95f82009-04-24 14:06:19 +0000106 if denominator is None:
Georg Brandl40f97352014-09-24 08:37:55 +0200107 if type(numerator) is int:
108 self._numerator = numerator
109 self._denominator = 1
110 return self
111
112 elif isinstance(numerator, numbers.Rational):
Mark Dickinsond4d95f82009-04-24 14:06:19 +0000113 self._numerator = numerator.numerator
114 self._denominator = numerator.denominator
115 return self
116
Mark Dickinson98127c32010-04-03 11:18:52 +0000117 elif isinstance(numerator, float):
118 # Exact conversion from float
119 value = Fraction.from_float(numerator)
120 self._numerator = value._numerator
121 self._denominator = value._denominator
122 return self
123
124 elif isinstance(numerator, Decimal):
125 value = Fraction.from_decimal(numerator)
126 self._numerator = value._numerator
127 self._denominator = value._denominator
128 return self
129
Mark Dickinsond4d95f82009-04-24 14:06:19 +0000130 elif isinstance(numerator, str):
Christian Heimes587c2bf2008-01-19 16:21:02 +0000131 # Handle construction from strings.
Mark Dickinsoncf63f2f2009-04-22 17:50:21 +0000132 m = _RATIONAL_FORMAT.match(numerator)
Christian Heimes587c2bf2008-01-19 16:21:02 +0000133 if m is None:
Mark Dickinsoncf63f2f2009-04-22 17:50:21 +0000134 raise ValueError('Invalid literal for Fraction: %r' %
135 numerator)
136 numerator = int(m.group('num') or '0')
137 denom = m.group('denom')
138 if denom:
139 denominator = int(denom)
Christian Heimesaf98da12008-01-27 15:18:18 +0000140 else:
Mark Dickinsoncf63f2f2009-04-22 17:50:21 +0000141 denominator = 1
142 decimal = m.group('decimal')
143 if decimal:
144 scale = 10**len(decimal)
145 numerator = numerator * scale + int(decimal)
146 denominator *= scale
147 exp = m.group('exp')
148 if exp:
149 exp = int(exp)
150 if exp >= 0:
151 numerator *= 10**exp
152 else:
153 denominator *= 10**-exp
Christian Heimes587c2bf2008-01-19 16:21:02 +0000154 if m.group('sign') == '-':
155 numerator = -numerator
156
Mark Dickinsond4d95f82009-04-24 14:06:19 +0000157 else:
158 raise TypeError("argument should be a string "
159 "or a Rational instance")
160
Georg Brandl40f97352014-09-24 08:37:55 +0200161 elif type(numerator) is int is type(denominator):
162 pass # *very* normal case
163
Mark Dickinsond4d95f82009-04-24 14:06:19 +0000164 elif (isinstance(numerator, numbers.Rational) and
165 isinstance(denominator, numbers.Rational)):
166 numerator, denominator = (
167 numerator.numerator * denominator.denominator,
168 denominator.numerator * numerator.denominator
169 )
170 else:
171 raise TypeError("both arguments should be "
172 "Rational instances")
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000173
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000174 if denominator == 0:
Christian Heimes3feef612008-02-11 06:19:17 +0000175 raise ZeroDivisionError('Fraction(%s, 0)' % numerator)
Mark Dickinson3c286e22014-04-05 09:29:00 +0100176 if _normalize:
177 g = gcd(numerator, denominator)
178 numerator //= g
179 denominator //= g
180 self._numerator = numerator
181 self._denominator = denominator
Christian Heimes587c2bf2008-01-19 16:21:02 +0000182 return self
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000183
184 @classmethod
185 def from_float(cls, f):
Christian Heimes587c2bf2008-01-19 16:21:02 +0000186 """Converts a finite float to a rational number, exactly.
187
Christian Heimes3feef612008-02-11 06:19:17 +0000188 Beware that Fraction.from_float(0.3) != Fraction(3, 10).
Christian Heimes587c2bf2008-01-19 16:21:02 +0000189
190 """
Georg Brandl2ee470f2008-07-16 12:55:28 +0000191 if isinstance(f, numbers.Integral):
Georg Brandl3a9b0622009-01-03 22:07:57 +0000192 return cls(f)
Georg Brandl2ee470f2008-07-16 12:55:28 +0000193 elif not isinstance(f, float):
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000194 raise TypeError("%s.from_float() only takes floats, not %r (%s)" %
195 (cls.__name__, f, type(f).__name__))
Mark Dickinson73726aa2012-11-15 20:58:40 +0000196 if math.isnan(f):
197 raise ValueError("Cannot convert %r to %s." % (f, cls.__name__))
198 if math.isinf(f):
199 raise OverflowError("Cannot convert %r to %s." % (f, cls.__name__))
Christian Heimes26855632008-01-27 23:50:43 +0000200 return cls(*f.as_integer_ratio())
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000201
Christian Heimes587c2bf2008-01-19 16:21:02 +0000202 @classmethod
203 def from_decimal(cls, dec):
204 """Converts a finite Decimal instance to a rational number, exactly."""
205 from decimal import Decimal
Georg Brandl2ee470f2008-07-16 12:55:28 +0000206 if isinstance(dec, numbers.Integral):
207 dec = Decimal(int(dec))
208 elif not isinstance(dec, Decimal):
Christian Heimes587c2bf2008-01-19 16:21:02 +0000209 raise TypeError(
210 "%s.from_decimal() only takes Decimals, not %r (%s)" %
211 (cls.__name__, dec, type(dec).__name__))
Mark Dickinson73726aa2012-11-15 20:58:40 +0000212 if dec.is_infinite():
213 raise OverflowError(
214 "Cannot convert %s to %s." % (dec, cls.__name__))
215 if dec.is_nan():
216 raise ValueError("Cannot convert %s to %s." % (dec, cls.__name__))
Christian Heimes587c2bf2008-01-19 16:21:02 +0000217 sign, digits, exp = dec.as_tuple()
218 digits = int(''.join(map(str, digits)))
219 if sign:
220 digits = -digits
221 if exp >= 0:
222 return cls(digits * 10 ** exp)
223 else:
224 return cls(digits, 10 ** -exp)
225
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000226 def limit_denominator(self, max_denominator=1000000):
227 """Closest Fraction to self with denominator at most max_denominator.
Christian Heimesbbffeb62008-01-24 09:42:52 +0000228
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000229 >>> Fraction('3.141592653589793').limit_denominator(10)
230 Fraction(22, 7)
231 >>> Fraction('3.141592653589793').limit_denominator(100)
232 Fraction(311, 99)
Mark Dickinsondfb15622009-11-23 16:27:17 +0000233 >>> Fraction(4321, 8765).limit_denominator(10000)
234 Fraction(4321, 8765)
Christian Heimesbbffeb62008-01-24 09:42:52 +0000235
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000236 """
237 # Algorithm notes: For any real number x, define a *best upper
238 # approximation* to x to be a rational number p/q such that:
239 #
240 # (1) p/q >= x, and
241 # (2) if p/q > r/s >= x then s > q, for any rational r/s.
242 #
243 # Define *best lower approximation* similarly. Then it can be
244 # proved that a rational number is a best upper or lower
245 # approximation to x if, and only if, it is a convergent or
246 # semiconvergent of the (unique shortest) continued fraction
247 # associated to x.
248 #
249 # To find a best rational approximation with denominator <= M,
250 # we find the best upper and lower approximations with
251 # denominator <= M and take whichever of these is closer to x.
252 # In the event of a tie, the bound with smaller denominator is
253 # chosen. If both denominators are equal (which can happen
254 # only when max_denominator == 1 and self is midway between
255 # two integers) the lower bound---i.e., the floor of self, is
256 # taken.
257
258 if max_denominator < 1:
259 raise ValueError("max_denominator should be at least 1")
260 if self._denominator <= max_denominator:
261 return Fraction(self)
262
263 p0, q0, p1, q1 = 0, 1, 1, 0
264 n, d = self._numerator, self._denominator
265 while True:
266 a = n//d
267 q2 = q0+a*q1
268 if q2 > max_denominator:
Christian Heimesbbffeb62008-01-24 09:42:52 +0000269 break
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000270 p0, q0, p1, q1 = p1, q1, p0+a*p1, q2
271 n, d = d, n-a*d
272
273 k = (max_denominator-q0)//q1
274 bound1 = Fraction(p0+k*p1, q0+k*q1)
275 bound2 = Fraction(p1, q1)
276 if abs(bound2 - self) <= abs(bound1-self):
277 return bound2
278 else:
279 return bound1
Christian Heimesbbffeb62008-01-24 09:42:52 +0000280
Christian Heimes400adb02008-02-01 08:12:03 +0000281 @property
282 def numerator(a):
283 return a._numerator
284
285 @property
286 def denominator(a):
287 return a._denominator
288
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000289 def __repr__(self):
290 """repr(self)"""
Serhiy Storchaka465e60e2014-07-25 23:36:00 +0300291 return '%s(%s, %s)' % (self.__class__.__name__,
292 self._numerator, self._denominator)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000293
294 def __str__(self):
295 """str(self)"""
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000296 if self._denominator == 1:
297 return str(self._numerator)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000298 else:
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000299 return '%s/%s' % (self._numerator, self._denominator)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000300
301 def _operator_fallbacks(monomorphic_operator, fallback_operator):
302 """Generates forward and reverse operators given a purely-rational
303 operator and a function from the operator module.
304
305 Use this like:
306 __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op)
307
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000308 In general, we want to implement the arithmetic operations so
309 that mixed-mode operations either call an implementation whose
310 author knew about the types of both arguments, or convert both
311 to the nearest built in type and do the operation there. In
Christian Heimes3feef612008-02-11 06:19:17 +0000312 Fraction, that means that we define __add__ and __radd__ as:
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000313
314 def __add__(self, other):
Christian Heimes400adb02008-02-01 08:12:03 +0000315 # Both types have numerators/denominator attributes,
316 # so do the operation directly
Christian Heimes3feef612008-02-11 06:19:17 +0000317 if isinstance(other, (int, Fraction)):
318 return Fraction(self.numerator * other.denominator +
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000319 other.numerator * self.denominator,
320 self.denominator * other.denominator)
Christian Heimes400adb02008-02-01 08:12:03 +0000321 # float and complex don't have those operations, but we
322 # know about those types, so special case them.
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000323 elif isinstance(other, float):
324 return float(self) + other
325 elif isinstance(other, complex):
326 return complex(self) + other
Christian Heimes400adb02008-02-01 08:12:03 +0000327 # Let the other type take over.
328 return NotImplemented
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000329
330 def __radd__(self, other):
331 # radd handles more types than add because there's
332 # nothing left to fall back to.
Christian Heimes3feef612008-02-11 06:19:17 +0000333 if isinstance(other, numbers.Rational):
334 return Fraction(self.numerator * other.denominator +
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000335 other.numerator * self.denominator,
336 self.denominator * other.denominator)
337 elif isinstance(other, Real):
338 return float(other) + float(self)
339 elif isinstance(other, Complex):
340 return complex(other) + complex(self)
Christian Heimes400adb02008-02-01 08:12:03 +0000341 return NotImplemented
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000342
343
344 There are 5 different cases for a mixed-type addition on
Christian Heimes3feef612008-02-11 06:19:17 +0000345 Fraction. I'll refer to all of the above code that doesn't
346 refer to Fraction, float, or complex as "boilerplate". 'r'
347 will be an instance of Fraction, which is a subtype of
348 Rational (r : Fraction <: Rational), and b : B <:
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000349 Complex. The first three involve 'r + b':
350
Christian Heimes3feef612008-02-11 06:19:17 +0000351 1. If B <: Fraction, int, float, or complex, we handle
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000352 that specially, and all is well.
Christian Heimes3feef612008-02-11 06:19:17 +0000353 2. If Fraction falls back to the boilerplate code, and it
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000354 were to return a value from __add__, we'd miss the
355 possibility that B defines a more intelligent __radd__,
356 so the boilerplate should return NotImplemented from
Christian Heimes3feef612008-02-11 06:19:17 +0000357 __add__. In particular, we don't handle Rational
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000358 here, even though we could get an exact answer, in case
359 the other type wants to do something special.
Christian Heimes3feef612008-02-11 06:19:17 +0000360 3. If B <: Fraction, Python tries B.__radd__ before
361 Fraction.__add__. This is ok, because it was
362 implemented with knowledge of Fraction, so it can
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000363 handle those instances before delegating to Real or
364 Complex.
365
366 The next two situations describe 'b + r'. We assume that b
Christian Heimes3feef612008-02-11 06:19:17 +0000367 didn't know about Fraction in its implementation, and that it
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000368 uses similar boilerplate code:
369
Christian Heimes3feef612008-02-11 06:19:17 +0000370 4. If B <: Rational, then __radd_ converts both to the
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000371 builtin rational type (hey look, that's us) and
372 proceeds.
373 5. Otherwise, __radd__ tries to find the nearest common
374 base ABC, and fall back to its builtin type. Since this
375 class doesn't subclass a concrete type, there's no
376 implementation to fall back to, so we need to try as
377 hard as possible to return an actual value, or the user
378 will get a TypeError.
379
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000380 """
381 def forward(a, b):
Christian Heimes3feef612008-02-11 06:19:17 +0000382 if isinstance(b, (int, Fraction)):
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000383 return monomorphic_operator(a, b)
384 elif isinstance(b, float):
385 return fallback_operator(float(a), b)
386 elif isinstance(b, complex):
387 return fallback_operator(complex(a), b)
388 else:
389 return NotImplemented
390 forward.__name__ = '__' + fallback_operator.__name__ + '__'
391 forward.__doc__ = monomorphic_operator.__doc__
392
393 def reverse(b, a):
Christian Heimes3feef612008-02-11 06:19:17 +0000394 if isinstance(a, numbers.Rational):
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000395 # Includes ints.
396 return monomorphic_operator(a, b)
397 elif isinstance(a, numbers.Real):
398 return fallback_operator(float(a), float(b))
399 elif isinstance(a, numbers.Complex):
400 return fallback_operator(complex(a), complex(b))
401 else:
402 return NotImplemented
403 reverse.__name__ = '__r' + fallback_operator.__name__ + '__'
404 reverse.__doc__ = monomorphic_operator.__doc__
405
406 return forward, reverse
407
408 def _add(a, b):
409 """a + b"""
Georg Brandl40f97352014-09-24 08:37:55 +0200410 da, db = a.denominator, b.denominator
411 return Fraction(a.numerator * db + b.numerator * da,
412 da * db)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000413
414 __add__, __radd__ = _operator_fallbacks(_add, operator.add)
415
416 def _sub(a, b):
417 """a - b"""
Georg Brandl40f97352014-09-24 08:37:55 +0200418 da, db = a.denominator, b.denominator
419 return Fraction(a.numerator * db - b.numerator * da,
420 da * db)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000421
422 __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub)
423
424 def _mul(a, b):
425 """a * b"""
Christian Heimes3feef612008-02-11 06:19:17 +0000426 return Fraction(a.numerator * b.numerator, a.denominator * b.denominator)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000427
428 __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul)
429
430 def _div(a, b):
431 """a / b"""
Christian Heimes3feef612008-02-11 06:19:17 +0000432 return Fraction(a.numerator * b.denominator,
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000433 a.denominator * b.numerator)
434
435 __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000436
437 def __floordiv__(a, b):
438 """a // b"""
Jeffrey Yasskin9893de12008-01-17 07:36:30 +0000439 return math.floor(a / b)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000440
441 def __rfloordiv__(b, a):
442 """a // b"""
Jeffrey Yasskin9893de12008-01-17 07:36:30 +0000443 return math.floor(a / b)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000444
Christian Heimes969fe572008-01-25 11:23:10 +0000445 def __mod__(a, b):
446 """a % b"""
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000447 div = a // b
448 return a - b * div
449
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000450 def __rmod__(b, a):
451 """a % b"""
Christian Heimes969fe572008-01-25 11:23:10 +0000452 div = a // b
453 return a - b * div
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000454
455 def __pow__(a, b):
456 """a ** b
457
458 If b is not an integer, the result will be a float or complex
459 since roots are generally irrational. If b is an integer, the
460 result will be rational.
461
462 """
Christian Heimes3feef612008-02-11 06:19:17 +0000463 if isinstance(b, numbers.Rational):
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000464 if b.denominator == 1:
465 power = b.numerator
466 if power >= 0:
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000467 return Fraction(a._numerator ** power,
Mark Dickinson3c286e22014-04-05 09:29:00 +0100468 a._denominator ** power,
469 _normalize=False)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000470 else:
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000471 return Fraction(a._denominator ** -power,
Mark Dickinson3c286e22014-04-05 09:29:00 +0100472 a._numerator ** -power,
473 _normalize=False)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000474 else:
475 # A fractional power will generally produce an
476 # irrational number.
477 return float(a) ** float(b)
478 else:
479 return float(a) ** b
480
481 def __rpow__(b, a):
482 """a ** b"""
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000483 if b._denominator == 1 and b._numerator >= 0:
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000484 # If a is an int, keep it that way if possible.
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000485 return a ** b._numerator
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000486
Christian Heimes3feef612008-02-11 06:19:17 +0000487 if isinstance(a, numbers.Rational):
488 return Fraction(a.numerator, a.denominator) ** b
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000489
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000490 if b._denominator == 1:
491 return a ** b._numerator
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000492
493 return a ** float(b)
494
495 def __pos__(a):
Christian Heimes3feef612008-02-11 06:19:17 +0000496 """+a: Coerces a subclass instance to Fraction"""
Mark Dickinson3c286e22014-04-05 09:29:00 +0100497 return Fraction(a._numerator, a._denominator, _normalize=False)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000498
499 def __neg__(a):
500 """-a"""
Mark Dickinson3c286e22014-04-05 09:29:00 +0100501 return Fraction(-a._numerator, a._denominator, _normalize=False)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000502
503 def __abs__(a):
504 """abs(a)"""
Mark Dickinson3c286e22014-04-05 09:29:00 +0100505 return Fraction(abs(a._numerator), a._denominator, _normalize=False)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000506
507 def __trunc__(a):
508 """trunc(a)"""
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000509 if a._numerator < 0:
510 return -(-a._numerator // a._denominator)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000511 else:
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000512 return a._numerator // a._denominator
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000513
514 def __floor__(a):
515 """Will be math.floor(a) in 3.0."""
516 return a.numerator // a.denominator
517
518 def __ceil__(a):
519 """Will be math.ceil(a) in 3.0."""
520 # The negations cleverly convince floordiv to return the ceiling.
521 return -(-a.numerator // a.denominator)
522
523 def __round__(self, ndigits=None):
524 """Will be round(self, ndigits) in 3.0.
525
526 Rounds half toward even.
527 """
528 if ndigits is None:
529 floor, remainder = divmod(self.numerator, self.denominator)
530 if remainder * 2 < self.denominator:
531 return floor
532 elif remainder * 2 > self.denominator:
533 return floor + 1
534 # Deal with the half case:
535 elif floor % 2 == 0:
536 return floor
537 else:
538 return floor + 1
539 shift = 10**abs(ndigits)
540 # See _operator_fallbacks.forward to check that the results of
Christian Heimes3feef612008-02-11 06:19:17 +0000541 # these operations will always be Fraction and therefore have
Jeffrey Yasskin9893de12008-01-17 07:36:30 +0000542 # round().
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000543 if ndigits > 0:
Christian Heimes3feef612008-02-11 06:19:17 +0000544 return Fraction(round(self * shift), shift)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000545 else:
Christian Heimes3feef612008-02-11 06:19:17 +0000546 return Fraction(round(self / shift) * shift)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000547
548 def __hash__(self):
Mark Dickinsonfec66202010-11-13 10:27:38 +0000549 """hash(self)"""
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000550
Christian Heimes969fe572008-01-25 11:23:10 +0000551 # XXX since this method is expensive, consider caching the result
Mark Dickinsondc787d22010-05-23 13:33:13 +0000552
553 # In order to make sure that the hash of a Fraction agrees
554 # with the hash of a numerically equal integer, float or
555 # Decimal instance, we follow the rules for numeric hashes
556 # outlined in the documentation. (See library docs, 'Built-in
557 # Types').
558
559 # dinv is the inverse of self._denominator modulo the prime
560 # _PyHASH_MODULUS, or 0 if self._denominator is divisible by
561 # _PyHASH_MODULUS.
562 dinv = pow(self._denominator, _PyHASH_MODULUS - 2, _PyHASH_MODULUS)
563 if not dinv:
564 hash_ = _PyHASH_INF
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000565 else:
Mark Dickinsondc787d22010-05-23 13:33:13 +0000566 hash_ = abs(self._numerator) * dinv % _PyHASH_MODULUS
Mark Dickinsonfec66202010-11-13 10:27:38 +0000567 result = hash_ if self >= 0 else -hash_
568 return -2 if result == -1 else result
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000569
570 def __eq__(a, b):
571 """a == b"""
Georg Brandl40f97352014-09-24 08:37:55 +0200572 if type(b) is int:
573 return a._numerator == b and a._denominator == 1
Christian Heimes3feef612008-02-11 06:19:17 +0000574 if isinstance(b, numbers.Rational):
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000575 return (a._numerator == b.numerator and
576 a._denominator == b.denominator)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000577 if isinstance(b, numbers.Complex) and b.imag == 0:
578 b = b.real
579 if isinstance(b, float):
Mark Dickinson85424c92009-07-18 14:41:42 +0000580 if math.isnan(b) or math.isinf(b):
581 # comparisons with an infinity or nan should behave in
582 # the same way for any finite a, so treat a as zero.
583 return 0.0 == b
584 else:
585 return a == a.from_float(b)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000586 else:
Mark Dickinson85424c92009-07-18 14:41:42 +0000587 # Since a doesn't know how to compare with b, let's give b
588 # a chance to compare itself with a.
589 return NotImplemented
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000590
Mark Dickinson85424c92009-07-18 14:41:42 +0000591 def _richcmp(self, other, op):
592 """Helper for comparison operators, for internal use only.
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000593
Mark Dickinson85424c92009-07-18 14:41:42 +0000594 Implement comparison between a Rational instance `self`, and
595 either another Rational instance or a float `other`. If
596 `other` is not a Rational instance or a float, return
597 NotImplemented. `op` should be one of the six standard
598 comparison operators.
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000599
600 """
Mark Dickinson85424c92009-07-18 14:41:42 +0000601 # convert other to a Rational instance where reasonable.
602 if isinstance(other, numbers.Rational):
603 return op(self._numerator * other.denominator,
604 self._denominator * other.numerator)
Mark Dickinson85424c92009-07-18 14:41:42 +0000605 if isinstance(other, float):
606 if math.isnan(other) or math.isinf(other):
607 return op(0.0, other)
608 else:
609 return op(self, self.from_float(other))
610 else:
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000611 return NotImplemented
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000612
613 def __lt__(a, b):
614 """a < b"""
Mark Dickinson85424c92009-07-18 14:41:42 +0000615 return a._richcmp(b, operator.lt)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000616
617 def __gt__(a, b):
618 """a > b"""
Mark Dickinson85424c92009-07-18 14:41:42 +0000619 return a._richcmp(b, operator.gt)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000620
621 def __le__(a, b):
622 """a <= b"""
Mark Dickinson85424c92009-07-18 14:41:42 +0000623 return a._richcmp(b, operator.le)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000624
625 def __ge__(a, b):
626 """a >= b"""
Mark Dickinson85424c92009-07-18 14:41:42 +0000627 return a._richcmp(b, operator.ge)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000628
629 def __bool__(a):
630 """a != 0"""
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000631 return a._numerator != 0
Christian Heimes969fe572008-01-25 11:23:10 +0000632
633 # support for pickling, copy, and deepcopy
634
635 def __reduce__(self):
636 return (self.__class__, (str(self),))
637
638 def __copy__(self):
Christian Heimes3feef612008-02-11 06:19:17 +0000639 if type(self) == Fraction:
Christian Heimes969fe572008-01-25 11:23:10 +0000640 return self # I'm immutable; therefore I am my own clone
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000641 return self.__class__(self._numerator, self._denominator)
Christian Heimes969fe572008-01-25 11:23:10 +0000642
643 def __deepcopy__(self, memo):
Christian Heimes3feef612008-02-11 06:19:17 +0000644 if type(self) == Fraction:
Christian Heimes969fe572008-01-25 11:23:10 +0000645 return self # My components are also immutable
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000646 return self.__class__(self._numerator, self._denominator)