blob: d23f433969a1cd8f3f958c39a0e6aeeaa69bb12c [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
Raymond Hettinger7ea82252008-01-25 01:13:12 +000017def _gcd(a, b): # XXX This is a useful function. Consider making it public.
Jeffrey Yasskind7b00332008-01-15 07:46:24 +000018 """Calculate the Greatest Common Divisor.
19
20 Unless b==0, the result will have the same sign as b (so that when
21 b is divided by it, the result comes out positive).
22 """
23 while b:
24 a, b = b, a%b
25 return a
26
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 """
Raymond Hettinger921cb5d2008-01-25 00:33:45 +000043 # XXX Consider moving this to to floatobject.c
44 # with a name like float.as_intger_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(
83 r'^\s*(?P<sign>[-+]?)(?P<num>\d+)(?:/(?P<denom>\d+))?\s*$')
84
85
Jeffrey Yasskind7b00332008-01-15 07:46:24 +000086class Rational(RationalAbc):
87 """This class implements rational numbers.
88
89 Rational(8, 6) will produce a rational number equivalent to
90 4/3. Both arguments must be Integral. The numerator defaults to 0
91 and the denominator defaults to 1 so that Rational(3) == 3 and
92 Rational() == 0.
93
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +000094 Rationals can also be constructed from strings of the form
95 '[-+]?[0-9]+(/[0-9]+)?', optionally surrounded by spaces.
96
Jeffrey Yasskind7b00332008-01-15 07:46:24 +000097 """
98
Raymond Hettinger7a6eacd2008-01-24 18:05:54 +000099 __slots__ = ('numerator', 'denominator')
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000100
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +0000101 # We're immutable, so use __new__ not __init__
102 def __new__(cls, numerator=0, denominator=1):
103 """Constructs a Rational.
104
105 Takes a string, another Rational, or a numerator/denominator pair.
106
107 """
108 self = super(Rational, cls).__new__(cls)
109
110 if denominator == 1:
111 if isinstance(numerator, basestring):
112 # Handle construction from strings.
113 input = numerator
114 m = _RATIONAL_FORMAT.match(input)
115 if m is None:
116 raise ValueError('Invalid literal for Rational: ' + input)
117 numerator = int(m.group('num'))
118 # Default denominator to 1. That's the only optional group.
119 denominator = int(m.group('denom') or 1)
120 if m.group('sign') == '-':
121 numerator = -numerator
122
123 elif (not isinstance(numerator, numbers.Integral) and
124 isinstance(numerator, RationalAbc)):
125 # Handle copies from other rationals.
126 other_rational = numerator
127 numerator = other_rational.numerator
128 denominator = other_rational.denominator
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000129
130 if (not isinstance(numerator, numbers.Integral) or
131 not isinstance(denominator, numbers.Integral)):
132 raise TypeError("Rational(%(numerator)s, %(denominator)s):"
133 " Both arguments must be integral." % locals())
134
135 if denominator == 0:
136 raise ZeroDivisionError('Rational(%s, 0)' % numerator)
137
138 g = _gcd(numerator, denominator)
Raymond Hettinger7a6eacd2008-01-24 18:05:54 +0000139 self.numerator = int(numerator // g)
140 self.denominator = int(denominator // g)
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +0000141 return self
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000142
143 @classmethod
144 def from_float(cls, f):
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +0000145 """Converts a finite float to a rational number, exactly.
146
147 Beware that Rational.from_float(0.3) != Rational(3, 10).
148
149 """
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000150 if not isinstance(f, float):
151 raise TypeError("%s.from_float() only takes floats, not %r (%s)" %
152 (cls.__name__, f, type(f).__name__))
153 if math.isnan(f) or math.isinf(f):
154 raise TypeError("Cannot convert %r to %s." % (f, cls.__name__))
155 return cls(*_binary_float_to_ratio(f))
156
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +0000157 @classmethod
158 def from_decimal(cls, dec):
159 """Converts a finite Decimal instance to a rational number, exactly."""
160 from decimal import Decimal
161 if not isinstance(dec, Decimal):
162 raise TypeError(
163 "%s.from_decimal() only takes Decimals, not %r (%s)" %
164 (cls.__name__, dec, type(dec).__name__))
165 if not dec.is_finite():
166 # Catches infinities and nans.
167 raise TypeError("Cannot convert %s to %s." % (dec, cls.__name__))
168 sign, digits, exp = dec.as_tuple()
169 digits = int(''.join(map(str, digits)))
170 if sign:
171 digits = -digits
172 if exp >= 0:
173 return cls(digits * 10 ** exp)
174 else:
175 return cls(digits, 10 ** -exp)
176
Raymond Hettingercf109262008-01-24 00:54:21 +0000177 @classmethod
178 def from_continued_fraction(cls, seq):
179 'Build a Rational from a continued fraction expessed as a sequence'
180 n, d = 1, 0
181 for e in reversed(seq):
182 n, d = d, n
183 n += e * d
Raymond Hettingerf336c8b2008-01-24 02:05:06 +0000184 return cls(n, d) if seq else cls(0)
Raymond Hettingercf109262008-01-24 00:54:21 +0000185
186 def as_continued_fraction(self):
187 'Return continued fraction expressed as a list'
188 n = self.numerator
189 d = self.denominator
190 cf = []
191 while d:
192 e = int(n // d)
193 cf.append(e)
194 n -= e * d
195 n, d = d, n
196 return cf
197
Raymond Hettinger9c6d81f2008-01-25 01:23:38 +0000198 def approximate(self, max_denominator):
199 'Best rational approximation with a denominator <= max_denominator'
Raymond Hettingercf109262008-01-24 00:54:21 +0000200 # XXX First cut at algorithm
201 # Still needs rounding rules as specified at
202 # http://en.wikipedia.org/wiki/Continued_fraction
Raymond Hettinger9c6d81f2008-01-25 01:23:38 +0000203 if self.denominator <= max_denominator:
204 return self
205 cf = self.as_continued_fraction()
Raymond Hettingereb461902008-01-24 02:00:25 +0000206 result = Rational(0)
Raymond Hettingercf109262008-01-24 00:54:21 +0000207 for i in range(1, len(cf)):
Raymond Hettinger9c6d81f2008-01-25 01:23:38 +0000208 new = self.from_continued_fraction(cf[:i])
Raymond Hettingercf109262008-01-24 00:54:21 +0000209 if new.denominator > max_denominator:
210 break
211 result = new
212 return result
213
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000214 def __repr__(self):
215 """repr(self)"""
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +0000216 return ('Rational(%r,%r)' % (self.numerator, self.denominator))
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000217
218 def __str__(self):
219 """str(self)"""
220 if self.denominator == 1:
221 return str(self.numerator)
222 else:
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +0000223 return '%s/%s' % (self.numerator, self.denominator)
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000224
Raymond Hettinger921cb5d2008-01-25 00:33:45 +0000225 """ XXX This section needs a lot more commentary
226
227 * Explain the typical sequence of checks, calls, and fallbacks.
228 * Explain the subtle reasons why this logic was needed.
229 * It is not clear how common cases are handled (for example, how
230 does the ratio of two huge integers get converted to a float
231 without overflowing the long-->float conversion.
232
233 """
234
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000235 def _operator_fallbacks(monomorphic_operator, fallback_operator):
236 """Generates forward and reverse operators given a purely-rational
237 operator and a function from the operator module.
238
239 Use this like:
240 __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op)
241
242 """
243 def forward(a, b):
244 if isinstance(b, RationalAbc):
245 # Includes ints.
246 return monomorphic_operator(a, b)
247 elif isinstance(b, float):
248 return fallback_operator(float(a), b)
249 elif isinstance(b, complex):
250 return fallback_operator(complex(a), b)
251 else:
252 return NotImplemented
253 forward.__name__ = '__' + fallback_operator.__name__ + '__'
254 forward.__doc__ = monomorphic_operator.__doc__
255
256 def reverse(b, a):
257 if isinstance(a, RationalAbc):
258 # Includes ints.
259 return monomorphic_operator(a, b)
260 elif isinstance(a, numbers.Real):
261 return fallback_operator(float(a), float(b))
262 elif isinstance(a, numbers.Complex):
263 return fallback_operator(complex(a), complex(b))
264 else:
265 return NotImplemented
266 reverse.__name__ = '__r' + fallback_operator.__name__ + '__'
267 reverse.__doc__ = monomorphic_operator.__doc__
268
269 return forward, reverse
270
271 def _add(a, b):
272 """a + b"""
273 return Rational(a.numerator * b.denominator +
274 b.numerator * a.denominator,
275 a.denominator * b.denominator)
276
277 __add__, __radd__ = _operator_fallbacks(_add, operator.add)
278
279 def _sub(a, b):
280 """a - b"""
281 return Rational(a.numerator * b.denominator -
282 b.numerator * a.denominator,
283 a.denominator * b.denominator)
284
285 __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub)
286
287 def _mul(a, b):
288 """a * b"""
289 return Rational(a.numerator * b.numerator, a.denominator * b.denominator)
290
291 __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul)
292
293 def _div(a, b):
294 """a / b"""
295 return Rational(a.numerator * b.denominator,
296 a.denominator * b.numerator)
297
298 __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv)
299 __div__, __rdiv__ = _operator_fallbacks(_div, operator.div)
300
Raymond Hettinger909e3342008-01-24 23:50:26 +0000301 def __floordiv__(a, b):
302 """a // b"""
303 # Will be math.floor(a / b) in 3.0.
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000304 div = a / b
305 if isinstance(div, RationalAbc):
306 # trunc(math.floor(div)) doesn't work if the rational is
307 # more precise than a float because the intermediate
308 # rounding may cross an integer boundary.
309 return div.numerator // div.denominator
310 else:
311 return math.floor(div)
312
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000313 def __rfloordiv__(b, a):
314 """a // b"""
315 # Will be math.floor(a / b) in 3.0.
Raymond Hettinger909e3342008-01-24 23:50:26 +0000316 div = a / b
317 if isinstance(div, RationalAbc):
318 # trunc(math.floor(div)) doesn't work if the rational is
319 # more precise than a float because the intermediate
320 # rounding may cross an integer boundary.
321 return div.numerator // div.denominator
322 else:
323 return math.floor(div)
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000324
325 def __mod__(a, b):
326 """a % b"""
Raymond Hettinger909e3342008-01-24 23:50:26 +0000327 div = a // b
328 return a - b * div
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000329
330 def __rmod__(b, a):
331 """a % b"""
Raymond Hettinger909e3342008-01-24 23:50:26 +0000332 div = a // b
333 return a - b * div
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000334
335 def __pow__(a, b):
336 """a ** b
337
338 If b is not an integer, the result will be a float or complex
339 since roots are generally irrational. If b is an integer, the
340 result will be rational.
341
342 """
343 if isinstance(b, RationalAbc):
344 if b.denominator == 1:
345 power = b.numerator
346 if power >= 0:
347 return Rational(a.numerator ** power,
348 a.denominator ** power)
349 else:
350 return Rational(a.denominator ** -power,
351 a.numerator ** -power)
352 else:
353 # A fractional power will generally produce an
354 # irrational number.
355 return float(a) ** float(b)
356 else:
357 return float(a) ** b
358
359 def __rpow__(b, a):
360 """a ** b"""
361 if b.denominator == 1 and b.numerator >= 0:
362 # If a is an int, keep it that way if possible.
363 return a ** b.numerator
364
365 if isinstance(a, RationalAbc):
366 return Rational(a.numerator, a.denominator) ** b
367
368 if b.denominator == 1:
369 return a ** b.numerator
370
371 return a ** float(b)
372
373 def __pos__(a):
374 """+a: Coerces a subclass instance to Rational"""
375 return Rational(a.numerator, a.denominator)
376
377 def __neg__(a):
378 """-a"""
379 return Rational(-a.numerator, a.denominator)
380
381 def __abs__(a):
382 """abs(a)"""
383 return Rational(abs(a.numerator), a.denominator)
384
385 def __trunc__(a):
386 """trunc(a)"""
387 if a.numerator < 0:
388 return -(-a.numerator // a.denominator)
389 else:
390 return a.numerator // a.denominator
391
Raymond Hettinger5b0e27e2008-01-24 19:30:19 +0000392 __int__ = __trunc__
393
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000394 def __floor__(a):
395 """Will be math.floor(a) in 3.0."""
396 return a.numerator // a.denominator
397
398 def __ceil__(a):
399 """Will be math.ceil(a) in 3.0."""
400 # The negations cleverly convince floordiv to return the ceiling.
401 return -(-a.numerator // a.denominator)
402
403 def __round__(self, ndigits=None):
404 """Will be round(self, ndigits) in 3.0.
405
406 Rounds half toward even.
407 """
408 if ndigits is None:
409 floor, remainder = divmod(self.numerator, self.denominator)
410 if remainder * 2 < self.denominator:
411 return floor
412 elif remainder * 2 > self.denominator:
413 return floor + 1
414 # Deal with the half case:
415 elif floor % 2 == 0:
416 return floor
417 else:
418 return floor + 1
419 shift = 10**abs(ndigits)
420 # See _operator_fallbacks.forward to check that the results of
421 # these operations will always be Rational and therefore have
422 # __round__().
423 if ndigits > 0:
424 return Rational((self * shift).__round__(), shift)
425 else:
426 return Rational((self / shift).__round__() * shift)
427
428 def __hash__(self):
429 """hash(self)
430
431 Tricky because values that are exactly representable as a
432 float must have the same hash as that float.
433
434 """
Raymond Hettinger921cb5d2008-01-25 00:33:45 +0000435 # XXX since this method is expensive, consider caching the result
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000436 if self.denominator == 1:
437 # Get integers right.
438 return hash(self.numerator)
439 # Expensive check, but definitely correct.
440 if self == float(self):
441 return hash(float(self))
442 else:
443 # Use tuple's hash to avoid a high collision rate on
444 # simple fractions.
445 return hash((self.numerator, self.denominator))
446
447 def __eq__(a, b):
448 """a == b"""
449 if isinstance(b, RationalAbc):
450 return (a.numerator == b.numerator and
451 a.denominator == b.denominator)
452 if isinstance(b, numbers.Complex) and b.imag == 0:
453 b = b.real
454 if isinstance(b, float):
455 return a == a.from_float(b)
456 else:
457 # XXX: If b.__eq__ is implemented like this method, it may
458 # give the wrong answer after float(a) changes a's
459 # value. Better ways of doing this are welcome.
460 return float(a) == b
461
462 def _subtractAndCompareToZero(a, b, op):
463 """Helper function for comparison operators.
464
465 Subtracts b from a, exactly if possible, and compares the
466 result with 0 using op, in such a way that the comparison
467 won't recurse. If the difference raises a TypeError, returns
468 NotImplemented instead.
469
470 """
471 if isinstance(b, numbers.Complex) and b.imag == 0:
472 b = b.real
473 if isinstance(b, float):
474 b = a.from_float(b)
475 try:
476 # XXX: If b <: Real but not <: RationalAbc, this is likely
477 # to fall back to a float. If the actual values differ by
478 # less than MIN_FLOAT, this could falsely call them equal,
479 # which would make <= inconsistent with ==. Better ways of
480 # doing this are welcome.
481 diff = a - b
482 except TypeError:
483 return NotImplemented
484 if isinstance(diff, RationalAbc):
485 return op(diff.numerator, 0)
486 return op(diff, 0)
487
488 def __lt__(a, b):
489 """a < b"""
490 return a._subtractAndCompareToZero(b, operator.lt)
491
492 def __gt__(a, b):
493 """a > b"""
494 return a._subtractAndCompareToZero(b, operator.gt)
495
496 def __le__(a, b):
497 """a <= b"""
498 return a._subtractAndCompareToZero(b, operator.le)
499
500 def __ge__(a, b):
501 """a >= b"""
502 return a._subtractAndCompareToZero(b, operator.ge)
503
504 def __nonzero__(a):
505 """a != 0"""
506 return a.numerator != 0
Raymond Hettingera6216742008-01-25 00:21:54 +0000507
508 # support for pickling, copy, and deepcopy
509
510 def __reduce__(self):
511 return (self.__class__, (str(self),))
512
513 def __copy__(self):
514 if type(self) == Rational:
515 return self # I'm immutable; therefore I am my own clone
516 return self.__class__(self.numerator, self.denominator)
517
518 def __deepcopy__(self, memo):
519 if type(self) == Rational:
520 return self # My components are also immutable
521 return self.__class__(self.numerator, self.denominator)