blob: 40b91635d34266e888fa108eec3c89183f6507ec [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
198 @classmethod
199 def approximate_from_float(cls, f, max_denominator):
200 'Best rational approximation to f with a denominator <= max_denominator'
201 # XXX First cut at algorithm
202 # Still needs rounding rules as specified at
203 # http://en.wikipedia.org/wiki/Continued_fraction
204 cf = cls.from_float(f).as_continued_fraction()
Raymond Hettingereb461902008-01-24 02:00:25 +0000205 result = Rational(0)
Raymond Hettingercf109262008-01-24 00:54:21 +0000206 for i in range(1, len(cf)):
207 new = cls.from_continued_fraction(cf[:i])
208 if new.denominator > max_denominator:
209 break
210 result = new
211 return result
212
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000213 def __repr__(self):
214 """repr(self)"""
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +0000215 return ('Rational(%r,%r)' % (self.numerator, self.denominator))
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000216
217 def __str__(self):
218 """str(self)"""
219 if self.denominator == 1:
220 return str(self.numerator)
221 else:
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +0000222 return '%s/%s' % (self.numerator, self.denominator)
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000223
Raymond Hettinger921cb5d2008-01-25 00:33:45 +0000224 """ XXX This section needs a lot more commentary
225
226 * Explain the typical sequence of checks, calls, and fallbacks.
227 * Explain the subtle reasons why this logic was needed.
228 * It is not clear how common cases are handled (for example, how
229 does the ratio of two huge integers get converted to a float
230 without overflowing the long-->float conversion.
231
232 """
233
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000234 def _operator_fallbacks(monomorphic_operator, fallback_operator):
235 """Generates forward and reverse operators given a purely-rational
236 operator and a function from the operator module.
237
238 Use this like:
239 __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op)
240
241 """
242 def forward(a, b):
243 if isinstance(b, RationalAbc):
244 # Includes ints.
245 return monomorphic_operator(a, b)
246 elif isinstance(b, float):
247 return fallback_operator(float(a), b)
248 elif isinstance(b, complex):
249 return fallback_operator(complex(a), b)
250 else:
251 return NotImplemented
252 forward.__name__ = '__' + fallback_operator.__name__ + '__'
253 forward.__doc__ = monomorphic_operator.__doc__
254
255 def reverse(b, a):
256 if isinstance(a, RationalAbc):
257 # Includes ints.
258 return monomorphic_operator(a, b)
259 elif isinstance(a, numbers.Real):
260 return fallback_operator(float(a), float(b))
261 elif isinstance(a, numbers.Complex):
262 return fallback_operator(complex(a), complex(b))
263 else:
264 return NotImplemented
265 reverse.__name__ = '__r' + fallback_operator.__name__ + '__'
266 reverse.__doc__ = monomorphic_operator.__doc__
267
268 return forward, reverse
269
270 def _add(a, b):
271 """a + b"""
272 return Rational(a.numerator * b.denominator +
273 b.numerator * a.denominator,
274 a.denominator * b.denominator)
275
276 __add__, __radd__ = _operator_fallbacks(_add, operator.add)
277
278 def _sub(a, b):
279 """a - b"""
280 return Rational(a.numerator * b.denominator -
281 b.numerator * a.denominator,
282 a.denominator * b.denominator)
283
284 __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub)
285
286 def _mul(a, b):
287 """a * b"""
288 return Rational(a.numerator * b.numerator, a.denominator * b.denominator)
289
290 __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul)
291
292 def _div(a, b):
293 """a / b"""
294 return Rational(a.numerator * b.denominator,
295 a.denominator * b.numerator)
296
297 __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv)
298 __div__, __rdiv__ = _operator_fallbacks(_div, operator.div)
299
Raymond Hettinger909e3342008-01-24 23:50:26 +0000300 def __floordiv__(a, b):
301 """a // b"""
302 # Will be math.floor(a / b) in 3.0.
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000303 div = a / b
304 if isinstance(div, RationalAbc):
305 # trunc(math.floor(div)) doesn't work if the rational is
306 # more precise than a float because the intermediate
307 # rounding may cross an integer boundary.
308 return div.numerator // div.denominator
309 else:
310 return math.floor(div)
311
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000312 def __rfloordiv__(b, a):
313 """a // b"""
314 # Will be math.floor(a / b) in 3.0.
Raymond Hettinger909e3342008-01-24 23:50:26 +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)
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000323
324 def __mod__(a, b):
325 """a % b"""
Raymond Hettinger909e3342008-01-24 23:50:26 +0000326 div = a // b
327 return a - b * div
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000328
329 def __rmod__(b, a):
330 """a % b"""
Raymond Hettinger909e3342008-01-24 23:50:26 +0000331 div = a // b
332 return a - b * div
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000333
334 def __pow__(a, b):
335 """a ** b
336
337 If b is not an integer, the result will be a float or complex
338 since roots are generally irrational. If b is an integer, the
339 result will be rational.
340
341 """
342 if isinstance(b, RationalAbc):
343 if b.denominator == 1:
344 power = b.numerator
345 if power >= 0:
346 return Rational(a.numerator ** power,
347 a.denominator ** power)
348 else:
349 return Rational(a.denominator ** -power,
350 a.numerator ** -power)
351 else:
352 # A fractional power will generally produce an
353 # irrational number.
354 return float(a) ** float(b)
355 else:
356 return float(a) ** b
357
358 def __rpow__(b, a):
359 """a ** b"""
360 if b.denominator == 1 and b.numerator >= 0:
361 # If a is an int, keep it that way if possible.
362 return a ** b.numerator
363
364 if isinstance(a, RationalAbc):
365 return Rational(a.numerator, a.denominator) ** b
366
367 if b.denominator == 1:
368 return a ** b.numerator
369
370 return a ** float(b)
371
372 def __pos__(a):
373 """+a: Coerces a subclass instance to Rational"""
374 return Rational(a.numerator, a.denominator)
375
376 def __neg__(a):
377 """-a"""
378 return Rational(-a.numerator, a.denominator)
379
380 def __abs__(a):
381 """abs(a)"""
382 return Rational(abs(a.numerator), a.denominator)
383
384 def __trunc__(a):
385 """trunc(a)"""
386 if a.numerator < 0:
387 return -(-a.numerator // a.denominator)
388 else:
389 return a.numerator // a.denominator
390
Raymond Hettinger5b0e27e2008-01-24 19:30:19 +0000391 __int__ = __trunc__
392
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000393 def __floor__(a):
394 """Will be math.floor(a) in 3.0."""
395 return a.numerator // a.denominator
396
397 def __ceil__(a):
398 """Will be math.ceil(a) in 3.0."""
399 # The negations cleverly convince floordiv to return the ceiling.
400 return -(-a.numerator // a.denominator)
401
402 def __round__(self, ndigits=None):
403 """Will be round(self, ndigits) in 3.0.
404
405 Rounds half toward even.
406 """
407 if ndigits is None:
408 floor, remainder = divmod(self.numerator, self.denominator)
409 if remainder * 2 < self.denominator:
410 return floor
411 elif remainder * 2 > self.denominator:
412 return floor + 1
413 # Deal with the half case:
414 elif floor % 2 == 0:
415 return floor
416 else:
417 return floor + 1
418 shift = 10**abs(ndigits)
419 # See _operator_fallbacks.forward to check that the results of
420 # these operations will always be Rational and therefore have
421 # __round__().
422 if ndigits > 0:
423 return Rational((self * shift).__round__(), shift)
424 else:
425 return Rational((self / shift).__round__() * shift)
426
427 def __hash__(self):
428 """hash(self)
429
430 Tricky because values that are exactly representable as a
431 float must have the same hash as that float.
432
433 """
Raymond Hettinger921cb5d2008-01-25 00:33:45 +0000434 # XXX since this method is expensive, consider caching the result
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000435 if self.denominator == 1:
436 # Get integers right.
437 return hash(self.numerator)
438 # Expensive check, but definitely correct.
439 if self == float(self):
440 return hash(float(self))
441 else:
442 # Use tuple's hash to avoid a high collision rate on
443 # simple fractions.
444 return hash((self.numerator, self.denominator))
445
446 def __eq__(a, b):
447 """a == b"""
448 if isinstance(b, RationalAbc):
449 return (a.numerator == b.numerator and
450 a.denominator == b.denominator)
451 if isinstance(b, numbers.Complex) and b.imag == 0:
452 b = b.real
453 if isinstance(b, float):
454 return a == a.from_float(b)
455 else:
456 # XXX: If b.__eq__ is implemented like this method, it may
457 # give the wrong answer after float(a) changes a's
458 # value. Better ways of doing this are welcome.
459 return float(a) == b
460
461 def _subtractAndCompareToZero(a, b, op):
462 """Helper function for comparison operators.
463
464 Subtracts b from a, exactly if possible, and compares the
465 result with 0 using op, in such a way that the comparison
466 won't recurse. If the difference raises a TypeError, returns
467 NotImplemented instead.
468
469 """
470 if isinstance(b, numbers.Complex) and b.imag == 0:
471 b = b.real
472 if isinstance(b, float):
473 b = a.from_float(b)
474 try:
475 # XXX: If b <: Real but not <: RationalAbc, this is likely
476 # to fall back to a float. If the actual values differ by
477 # less than MIN_FLOAT, this could falsely call them equal,
478 # which would make <= inconsistent with ==. Better ways of
479 # doing this are welcome.
480 diff = a - b
481 except TypeError:
482 return NotImplemented
483 if isinstance(diff, RationalAbc):
484 return op(diff.numerator, 0)
485 return op(diff, 0)
486
487 def __lt__(a, b):
488 """a < b"""
489 return a._subtractAndCompareToZero(b, operator.lt)
490
491 def __gt__(a, b):
492 """a > b"""
493 return a._subtractAndCompareToZero(b, operator.gt)
494
495 def __le__(a, b):
496 """a <= b"""
497 return a._subtractAndCompareToZero(b, operator.le)
498
499 def __ge__(a, b):
500 """a >= b"""
501 return a._subtractAndCompareToZero(b, operator.ge)
502
503 def __nonzero__(a):
504 """a != 0"""
505 return a.numerator != 0
Raymond Hettingera6216742008-01-25 00:21:54 +0000506
507 # support for pickling, copy, and deepcopy
508
509 def __reduce__(self):
510 return (self.__class__, (str(self),))
511
512 def __copy__(self):
513 if type(self) == Rational:
514 return self # I'm immutable; therefore I am my own clone
515 return self.__class__(self.numerator, self.denominator)
516
517 def __deepcopy__(self, memo):
518 if type(self) == Rational:
519 return self # My components are also immutable
520 return self.__class__(self.numerator, self.denominator)