blob: 8ee38ba0a5c5f3a80fa16855dc9ee9c740d4221e [file] [log] [blame]
Jeffrey Yasskind7b00332008-01-15 07:46:24 +00001# Originally contributed by Sjoerd Mullender.
2# Significantly modified by Jeffrey Yasskin <jyasskin at gmail.com>.
3
4"""Rational, infinite-precision, real numbers."""
5
6from __future__ import division
7import math
8import numbers
9import operator
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +000010import re
Jeffrey Yasskind7b00332008-01-15 07:46:24 +000011
12__all__ = ["Rational"]
13
14RationalAbc = numbers.Rational
15
16
Jeffrey Yasskin3e1a3732008-01-27 05:40:35 +000017def gcd(a, b):
18 """Calculate the Greatest Common Divisor of a and b.
Jeffrey Yasskind7b00332008-01-15 07:46:24 +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
27
28def _binary_float_to_ratio(x):
29 """x -> (top, bot), a pair of ints s.t. x = top/bot.
30
31 The conversion is done exactly, without rounding.
32 bot > 0 guaranteed.
33 Some form of binary fp is assumed.
34 Pass NaNs or infinities at your own risk.
35
36 >>> _binary_float_to_ratio(10.0)
37 (10, 1)
38 >>> _binary_float_to_ratio(0.0)
39 (0, 1)
40 >>> _binary_float_to_ratio(-.25)
41 (-1, 4)
42 """
Jeffrey Yasskin3e1a3732008-01-27 05:40:35 +000043 # XXX Move this to floatobject.c with a name like
44 # float.as_integer_ratio()
Jeffrey Yasskind7b00332008-01-15 07:46:24 +000045
46 if x == 0:
47 return 0, 1
48 f, e = math.frexp(x)
49 signbit = 1
50 if f < 0:
51 f = -f
52 signbit = -1
53 assert 0.5 <= f < 1.0
54 # x = signbit * f * 2**e exactly
55
56 # Suck up CHUNK bits at a time; 28 is enough so that we suck
57 # up all bits in 2 iterations for all known binary double-
58 # precision formats, and small enough to fit in an int.
59 CHUNK = 28
60 top = 0
61 # invariant: x = signbit * (top + f) * 2**e exactly
62 while f:
63 f = math.ldexp(f, CHUNK)
64 digit = trunc(f)
65 assert digit >> CHUNK == 0
66 top = (top << CHUNK) | digit
67 f = f - digit
68 assert 0.0 <= f < 1.0
69 e = e - CHUNK
70 assert top
71
72 # Add in the sign bit.
73 top = signbit * top
74
75 # now x = top * 2**e exactly; fold in 2**e
76 if e>0:
77 return (top * 2**e, 1)
78 else:
79 return (top, 2 ** -e)
80
81
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +000082_RATIONAL_FORMAT = re.compile(
Jeffrey Yasskin3e1a3732008-01-27 05:40:35 +000083 r'^\s*(?P<sign>[-+]?)(?P<num>\d+)'
84 r'(?:/(?P<denom>\d+)|\.(?P<decimal>\d+))?\s*$')
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +000085
86
Jeffrey Yasskind7b00332008-01-15 07:46:24 +000087class Rational(RationalAbc):
88 """This class implements rational numbers.
89
90 Rational(8, 6) will produce a rational number equivalent to
91 4/3. Both arguments must be Integral. The numerator defaults to 0
92 and the denominator defaults to 1 so that Rational(3) == 3 and
93 Rational() == 0.
94
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +000095 Rationals can also be constructed from strings of the form
Jeffrey Yasskin3e1a3732008-01-27 05:40:35 +000096 '[-+]?[0-9]+((/|.)[0-9]+)?', optionally surrounded by spaces.
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +000097
Jeffrey Yasskind7b00332008-01-15 07:46:24 +000098 """
99
Raymond Hettinger7a6eacd2008-01-24 18:05:54 +0000100 __slots__ = ('numerator', 'denominator')
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000101
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +0000102 # We're immutable, so use __new__ not __init__
103 def __new__(cls, numerator=0, denominator=1):
104 """Constructs a Rational.
105
Raymond Hettinger63c77b62008-01-27 10:13:57 +0000106 Takes a string like '3/2' or '1.5', another Rational, or a
Jeffrey Yasskin3e1a3732008-01-27 05:40:35 +0000107 numerator/denominator pair.
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +0000108
109 """
110 self = super(Rational, cls).__new__(cls)
111
112 if denominator == 1:
113 if isinstance(numerator, basestring):
114 # Handle construction from strings.
115 input = numerator
116 m = _RATIONAL_FORMAT.match(input)
117 if m is None:
118 raise ValueError('Invalid literal for Rational: ' + input)
Jeffrey Yasskin3e1a3732008-01-27 05:40:35 +0000119 numerator = m.group('num')
120 decimal = m.group('decimal')
121 if decimal:
122 # The literal is a decimal number.
123 numerator = int(numerator + decimal)
124 denominator = 10**len(decimal)
125 else:
126 # The literal is an integer or fraction.
127 numerator = int(numerator)
128 # Default denominator to 1.
129 denominator = int(m.group('denom') or 1)
130
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +0000131 if m.group('sign') == '-':
132 numerator = -numerator
133
134 elif (not isinstance(numerator, numbers.Integral) and
135 isinstance(numerator, RationalAbc)):
136 # Handle copies from other rationals.
137 other_rational = numerator
138 numerator = other_rational.numerator
139 denominator = other_rational.denominator
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000140
141 if (not isinstance(numerator, numbers.Integral) or
142 not isinstance(denominator, numbers.Integral)):
143 raise TypeError("Rational(%(numerator)s, %(denominator)s):"
144 " Both arguments must be integral." % locals())
145
146 if denominator == 0:
147 raise ZeroDivisionError('Rational(%s, 0)' % numerator)
148
Jeffrey Yasskin3e1a3732008-01-27 05:40:35 +0000149 g = gcd(numerator, denominator)
Raymond Hettinger7a6eacd2008-01-24 18:05:54 +0000150 self.numerator = int(numerator // g)
151 self.denominator = int(denominator // g)
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +0000152 return self
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000153
154 @classmethod
155 def from_float(cls, f):
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +0000156 """Converts a finite float to a rational number, exactly.
157
158 Beware that Rational.from_float(0.3) != Rational(3, 10).
159
160 """
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000161 if not isinstance(f, float):
162 raise TypeError("%s.from_float() only takes floats, not %r (%s)" %
163 (cls.__name__, f, type(f).__name__))
164 if math.isnan(f) or math.isinf(f):
165 raise TypeError("Cannot convert %r to %s." % (f, cls.__name__))
166 return cls(*_binary_float_to_ratio(f))
167
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +0000168 @classmethod
169 def from_decimal(cls, dec):
170 """Converts a finite Decimal instance to a rational number, exactly."""
171 from decimal import Decimal
172 if not isinstance(dec, Decimal):
173 raise TypeError(
174 "%s.from_decimal() only takes Decimals, not %r (%s)" %
175 (cls.__name__, dec, type(dec).__name__))
176 if not dec.is_finite():
177 # Catches infinities and nans.
178 raise TypeError("Cannot convert %s to %s." % (dec, cls.__name__))
179 sign, digits, exp = dec.as_tuple()
180 digits = int(''.join(map(str, digits)))
181 if sign:
182 digits = -digits
183 if exp >= 0:
184 return cls(digits * 10 ** exp)
185 else:
186 return cls(digits, 10 ** -exp)
187
Raymond Hettingercf109262008-01-24 00:54:21 +0000188 @classmethod
189 def from_continued_fraction(cls, seq):
190 'Build a Rational from a continued fraction expessed as a sequence'
191 n, d = 1, 0
192 for e in reversed(seq):
193 n, d = d, n
194 n += e * d
Raymond Hettingerf336c8b2008-01-24 02:05:06 +0000195 return cls(n, d) if seq else cls(0)
Raymond Hettingercf109262008-01-24 00:54:21 +0000196
197 def as_continued_fraction(self):
198 'Return continued fraction expressed as a list'
199 n = self.numerator
200 d = self.denominator
201 cf = []
202 while d:
203 e = int(n // d)
204 cf.append(e)
205 n -= e * d
206 n, d = d, n
207 return cf
208
Raymond Hettinger9c6d81f2008-01-25 01:23:38 +0000209 def approximate(self, max_denominator):
210 'Best rational approximation with a denominator <= max_denominator'
Raymond Hettingercf109262008-01-24 00:54:21 +0000211 # XXX First cut at algorithm
212 # Still needs rounding rules as specified at
213 # http://en.wikipedia.org/wiki/Continued_fraction
Raymond Hettinger9c6d81f2008-01-25 01:23:38 +0000214 if self.denominator <= max_denominator:
215 return self
216 cf = self.as_continued_fraction()
Raymond Hettingereb461902008-01-24 02:00:25 +0000217 result = Rational(0)
Raymond Hettingercf109262008-01-24 00:54:21 +0000218 for i in range(1, len(cf)):
Raymond Hettinger9c6d81f2008-01-25 01:23:38 +0000219 new = self.from_continued_fraction(cf[:i])
Raymond Hettingercf109262008-01-24 00:54:21 +0000220 if new.denominator > max_denominator:
221 break
222 result = new
223 return result
224
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000225 def __repr__(self):
226 """repr(self)"""
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +0000227 return ('Rational(%r,%r)' % (self.numerator, self.denominator))
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000228
229 def __str__(self):
230 """str(self)"""
231 if self.denominator == 1:
232 return str(self.numerator)
233 else:
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +0000234 return '%s/%s' % (self.numerator, self.denominator)
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000235
Raymond Hettinger921cb5d2008-01-25 00:33:45 +0000236 """ XXX This section needs a lot more commentary
237
238 * Explain the typical sequence of checks, calls, and fallbacks.
239 * Explain the subtle reasons why this logic was needed.
240 * It is not clear how common cases are handled (for example, how
241 does the ratio of two huge integers get converted to a float
242 without overflowing the long-->float conversion.
243
244 """
245
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000246 def _operator_fallbacks(monomorphic_operator, fallback_operator):
247 """Generates forward and reverse operators given a purely-rational
248 operator and a function from the operator module.
249
250 Use this like:
251 __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op)
252
253 """
254 def forward(a, b):
255 if isinstance(b, RationalAbc):
256 # Includes ints.
257 return monomorphic_operator(a, b)
258 elif isinstance(b, float):
259 return fallback_operator(float(a), b)
260 elif isinstance(b, complex):
261 return fallback_operator(complex(a), b)
262 else:
263 return NotImplemented
264 forward.__name__ = '__' + fallback_operator.__name__ + '__'
265 forward.__doc__ = monomorphic_operator.__doc__
266
267 def reverse(b, a):
268 if isinstance(a, RationalAbc):
269 # Includes ints.
270 return monomorphic_operator(a, b)
271 elif isinstance(a, numbers.Real):
272 return fallback_operator(float(a), float(b))
273 elif isinstance(a, numbers.Complex):
274 return fallback_operator(complex(a), complex(b))
275 else:
276 return NotImplemented
277 reverse.__name__ = '__r' + fallback_operator.__name__ + '__'
278 reverse.__doc__ = monomorphic_operator.__doc__
279
280 return forward, reverse
281
282 def _add(a, b):
283 """a + b"""
284 return Rational(a.numerator * b.denominator +
285 b.numerator * a.denominator,
286 a.denominator * b.denominator)
287
288 __add__, __radd__ = _operator_fallbacks(_add, operator.add)
289
290 def _sub(a, b):
291 """a - b"""
292 return Rational(a.numerator * b.denominator -
293 b.numerator * a.denominator,
294 a.denominator * b.denominator)
295
296 __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub)
297
298 def _mul(a, b):
299 """a * b"""
300 return Rational(a.numerator * b.numerator, a.denominator * b.denominator)
301
302 __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul)
303
304 def _div(a, b):
305 """a / b"""
306 return Rational(a.numerator * b.denominator,
307 a.denominator * b.numerator)
308
309 __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv)
310 __div__, __rdiv__ = _operator_fallbacks(_div, operator.div)
311
Raymond Hettinger909e3342008-01-24 23:50:26 +0000312 def __floordiv__(a, b):
313 """a // b"""
314 # Will be math.floor(a / b) in 3.0.
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000315 div = a / b
316 if isinstance(div, RationalAbc):
317 # trunc(math.floor(div)) doesn't work if the rational is
318 # more precise than a float because the intermediate
319 # rounding may cross an integer boundary.
320 return div.numerator // div.denominator
321 else:
322 return math.floor(div)
323
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000324 def __rfloordiv__(b, a):
325 """a // b"""
326 # Will be math.floor(a / b) in 3.0.
Raymond Hettinger909e3342008-01-24 23:50:26 +0000327 div = a / b
328 if isinstance(div, RationalAbc):
329 # trunc(math.floor(div)) doesn't work if the rational is
330 # more precise than a float because the intermediate
331 # rounding may cross an integer boundary.
332 return div.numerator // div.denominator
333 else:
334 return math.floor(div)
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000335
336 def __mod__(a, b):
337 """a % b"""
Raymond Hettinger909e3342008-01-24 23:50:26 +0000338 div = a // b
339 return a - b * div
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000340
341 def __rmod__(b, a):
342 """a % b"""
Raymond Hettinger909e3342008-01-24 23:50:26 +0000343 div = a // b
344 return a - b * div
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000345
346 def __pow__(a, b):
347 """a ** b
348
349 If b is not an integer, the result will be a float or complex
350 since roots are generally irrational. If b is an integer, the
351 result will be rational.
352
353 """
354 if isinstance(b, RationalAbc):
355 if b.denominator == 1:
356 power = b.numerator
357 if power >= 0:
358 return Rational(a.numerator ** power,
359 a.denominator ** power)
360 else:
361 return Rational(a.denominator ** -power,
362 a.numerator ** -power)
363 else:
364 # A fractional power will generally produce an
365 # irrational number.
366 return float(a) ** float(b)
367 else:
368 return float(a) ** b
369
370 def __rpow__(b, a):
371 """a ** b"""
372 if b.denominator == 1 and b.numerator >= 0:
373 # If a is an int, keep it that way if possible.
374 return a ** b.numerator
375
376 if isinstance(a, RationalAbc):
377 return Rational(a.numerator, a.denominator) ** b
378
379 if b.denominator == 1:
380 return a ** b.numerator
381
382 return a ** float(b)
383
384 def __pos__(a):
385 """+a: Coerces a subclass instance to Rational"""
386 return Rational(a.numerator, a.denominator)
387
388 def __neg__(a):
389 """-a"""
390 return Rational(-a.numerator, a.denominator)
391
392 def __abs__(a):
393 """abs(a)"""
394 return Rational(abs(a.numerator), a.denominator)
395
396 def __trunc__(a):
397 """trunc(a)"""
398 if a.numerator < 0:
399 return -(-a.numerator // a.denominator)
400 else:
401 return a.numerator // a.denominator
402
Raymond Hettinger5b0e27e2008-01-24 19:30:19 +0000403 __int__ = __trunc__
404
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000405 def __floor__(a):
406 """Will be math.floor(a) in 3.0."""
407 return a.numerator // a.denominator
408
409 def __ceil__(a):
410 """Will be math.ceil(a) in 3.0."""
411 # The negations cleverly convince floordiv to return the ceiling.
412 return -(-a.numerator // a.denominator)
413
414 def __round__(self, ndigits=None):
415 """Will be round(self, ndigits) in 3.0.
416
417 Rounds half toward even.
418 """
419 if ndigits is None:
420 floor, remainder = divmod(self.numerator, self.denominator)
421 if remainder * 2 < self.denominator:
422 return floor
423 elif remainder * 2 > self.denominator:
424 return floor + 1
425 # Deal with the half case:
426 elif floor % 2 == 0:
427 return floor
428 else:
429 return floor + 1
430 shift = 10**abs(ndigits)
431 # See _operator_fallbacks.forward to check that the results of
432 # these operations will always be Rational and therefore have
433 # __round__().
434 if ndigits > 0:
435 return Rational((self * shift).__round__(), shift)
436 else:
437 return Rational((self / shift).__round__() * shift)
438
439 def __hash__(self):
440 """hash(self)
441
442 Tricky because values that are exactly representable as a
443 float must have the same hash as that float.
444
445 """
Raymond Hettinger921cb5d2008-01-25 00:33:45 +0000446 # XXX since this method is expensive, consider caching the result
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000447 if self.denominator == 1:
448 # Get integers right.
449 return hash(self.numerator)
450 # Expensive check, but definitely correct.
451 if self == float(self):
452 return hash(float(self))
453 else:
454 # Use tuple's hash to avoid a high collision rate on
455 # simple fractions.
456 return hash((self.numerator, self.denominator))
457
458 def __eq__(a, b):
459 """a == b"""
460 if isinstance(b, RationalAbc):
461 return (a.numerator == b.numerator and
462 a.denominator == b.denominator)
463 if isinstance(b, numbers.Complex) and b.imag == 0:
464 b = b.real
465 if isinstance(b, float):
466 return a == a.from_float(b)
467 else:
468 # XXX: If b.__eq__ is implemented like this method, it may
469 # give the wrong answer after float(a) changes a's
470 # value. Better ways of doing this are welcome.
471 return float(a) == b
472
473 def _subtractAndCompareToZero(a, b, op):
474 """Helper function for comparison operators.
475
476 Subtracts b from a, exactly if possible, and compares the
477 result with 0 using op, in such a way that the comparison
478 won't recurse. If the difference raises a TypeError, returns
479 NotImplemented instead.
480
481 """
482 if isinstance(b, numbers.Complex) and b.imag == 0:
483 b = b.real
484 if isinstance(b, float):
485 b = a.from_float(b)
486 try:
487 # XXX: If b <: Real but not <: RationalAbc, this is likely
488 # to fall back to a float. If the actual values differ by
489 # less than MIN_FLOAT, this could falsely call them equal,
490 # which would make <= inconsistent with ==. Better ways of
491 # doing this are welcome.
492 diff = a - b
493 except TypeError:
494 return NotImplemented
495 if isinstance(diff, RationalAbc):
496 return op(diff.numerator, 0)
497 return op(diff, 0)
498
499 def __lt__(a, b):
500 """a < b"""
501 return a._subtractAndCompareToZero(b, operator.lt)
502
503 def __gt__(a, b):
504 """a > b"""
505 return a._subtractAndCompareToZero(b, operator.gt)
506
507 def __le__(a, b):
508 """a <= b"""
509 return a._subtractAndCompareToZero(b, operator.le)
510
511 def __ge__(a, b):
512 """a >= b"""
513 return a._subtractAndCompareToZero(b, operator.ge)
514
515 def __nonzero__(a):
516 """a != 0"""
517 return a.numerator != 0
Raymond Hettingera6216742008-01-25 00:21:54 +0000518
519 # support for pickling, copy, and deepcopy
520
521 def __reduce__(self):
522 return (self.__class__, (str(self),))
523
524 def __copy__(self):
525 if type(self) == Rational:
526 return self # I'm immutable; therefore I am my own clone
527 return self.__class__(self.numerator, self.denominator)
528
529 def __deepcopy__(self, memo):
530 if type(self) == Rational:
531 return self # My components are also immutable
532 return self.__class__(self.numerator, self.denominator)