blob: 99c5ff6b9f012213c0a5aa65c1552a162c145644 [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
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +000028_RATIONAL_FORMAT = re.compile(
Jeffrey Yasskin3e1a3732008-01-27 05:40:35 +000029 r'^\s*(?P<sign>[-+]?)(?P<num>\d+)'
30 r'(?:/(?P<denom>\d+)|\.(?P<decimal>\d+))?\s*$')
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +000031
32
Jeffrey Yasskind7b00332008-01-15 07:46:24 +000033class Rational(RationalAbc):
34 """This class implements rational numbers.
35
36 Rational(8, 6) will produce a rational number equivalent to
37 4/3. Both arguments must be Integral. The numerator defaults to 0
38 and the denominator defaults to 1 so that Rational(3) == 3 and
39 Rational() == 0.
40
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +000041 Rationals can also be constructed from strings of the form
Jeffrey Yasskin3e1a3732008-01-27 05:40:35 +000042 '[-+]?[0-9]+((/|.)[0-9]+)?', optionally surrounded by spaces.
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +000043
Jeffrey Yasskind7b00332008-01-15 07:46:24 +000044 """
45
Raymond Hettinger7a6eacd2008-01-24 18:05:54 +000046 __slots__ = ('numerator', 'denominator')
Jeffrey Yasskind7b00332008-01-15 07:46:24 +000047
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +000048 # We're immutable, so use __new__ not __init__
49 def __new__(cls, numerator=0, denominator=1):
50 """Constructs a Rational.
51
Raymond Hettinger63c77b62008-01-27 10:13:57 +000052 Takes a string like '3/2' or '1.5', another Rational, or a
Jeffrey Yasskin3e1a3732008-01-27 05:40:35 +000053 numerator/denominator pair.
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +000054
55 """
56 self = super(Rational, cls).__new__(cls)
57
58 if denominator == 1:
59 if isinstance(numerator, basestring):
60 # Handle construction from strings.
61 input = numerator
62 m = _RATIONAL_FORMAT.match(input)
63 if m is None:
64 raise ValueError('Invalid literal for Rational: ' + input)
Jeffrey Yasskin3e1a3732008-01-27 05:40:35 +000065 numerator = m.group('num')
66 decimal = m.group('decimal')
67 if decimal:
68 # The literal is a decimal number.
69 numerator = int(numerator + decimal)
70 denominator = 10**len(decimal)
71 else:
72 # The literal is an integer or fraction.
73 numerator = int(numerator)
74 # Default denominator to 1.
75 denominator = int(m.group('denom') or 1)
76
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +000077 if m.group('sign') == '-':
78 numerator = -numerator
79
80 elif (not isinstance(numerator, numbers.Integral) and
81 isinstance(numerator, RationalAbc)):
82 # Handle copies from other rationals.
83 other_rational = numerator
84 numerator = other_rational.numerator
85 denominator = other_rational.denominator
Jeffrey Yasskind7b00332008-01-15 07:46:24 +000086
87 if (not isinstance(numerator, numbers.Integral) or
88 not isinstance(denominator, numbers.Integral)):
89 raise TypeError("Rational(%(numerator)s, %(denominator)s):"
90 " Both arguments must be integral." % locals())
91
92 if denominator == 0:
93 raise ZeroDivisionError('Rational(%s, 0)' % numerator)
94
Jeffrey Yasskin3e1a3732008-01-27 05:40:35 +000095 g = gcd(numerator, denominator)
Raymond Hettinger7a6eacd2008-01-24 18:05:54 +000096 self.numerator = int(numerator // g)
97 self.denominator = int(denominator // g)
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +000098 return self
Jeffrey Yasskind7b00332008-01-15 07:46:24 +000099
100 @classmethod
101 def from_float(cls, f):
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +0000102 """Converts a finite float to a rational number, exactly.
103
104 Beware that Rational.from_float(0.3) != Rational(3, 10).
105
106 """
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000107 if not isinstance(f, float):
108 raise TypeError("%s.from_float() only takes floats, not %r (%s)" %
109 (cls.__name__, f, type(f).__name__))
110 if math.isnan(f) or math.isinf(f):
111 raise TypeError("Cannot convert %r to %s." % (f, cls.__name__))
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +0000112 return cls(*f.as_integer_ratio())
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000113
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +0000114 @classmethod
115 def from_decimal(cls, dec):
116 """Converts a finite Decimal instance to a rational number, exactly."""
117 from decimal import Decimal
118 if not isinstance(dec, Decimal):
119 raise TypeError(
120 "%s.from_decimal() only takes Decimals, not %r (%s)" %
121 (cls.__name__, dec, type(dec).__name__))
122 if not dec.is_finite():
123 # Catches infinities and nans.
124 raise TypeError("Cannot convert %s to %s." % (dec, cls.__name__))
125 sign, digits, exp = dec.as_tuple()
126 digits = int(''.join(map(str, digits)))
127 if sign:
128 digits = -digits
129 if exp >= 0:
130 return cls(digits * 10 ** exp)
131 else:
132 return cls(digits, 10 ** -exp)
133
Raymond Hettingercf109262008-01-24 00:54:21 +0000134 @classmethod
135 def from_continued_fraction(cls, seq):
136 'Build a Rational from a continued fraction expessed as a sequence'
137 n, d = 1, 0
138 for e in reversed(seq):
139 n, d = d, n
140 n += e * d
Raymond Hettingerf336c8b2008-01-24 02:05:06 +0000141 return cls(n, d) if seq else cls(0)
Raymond Hettingercf109262008-01-24 00:54:21 +0000142
143 def as_continued_fraction(self):
144 'Return continued fraction expressed as a list'
145 n = self.numerator
146 d = self.denominator
147 cf = []
148 while d:
149 e = int(n // d)
150 cf.append(e)
151 n -= e * d
152 n, d = d, n
153 return cf
154
Raymond Hettinger9c6d81f2008-01-25 01:23:38 +0000155 def approximate(self, max_denominator):
156 'Best rational approximation with a denominator <= max_denominator'
Raymond Hettingercf109262008-01-24 00:54:21 +0000157 # XXX First cut at algorithm
158 # Still needs rounding rules as specified at
159 # http://en.wikipedia.org/wiki/Continued_fraction
Raymond Hettinger9c6d81f2008-01-25 01:23:38 +0000160 if self.denominator <= max_denominator:
161 return self
162 cf = self.as_continued_fraction()
Raymond Hettingereb461902008-01-24 02:00:25 +0000163 result = Rational(0)
Raymond Hettingercf109262008-01-24 00:54:21 +0000164 for i in range(1, len(cf)):
Raymond Hettinger9c6d81f2008-01-25 01:23:38 +0000165 new = self.from_continued_fraction(cf[:i])
Raymond Hettingercf109262008-01-24 00:54:21 +0000166 if new.denominator > max_denominator:
167 break
168 result = new
169 return result
170
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000171 def __repr__(self):
172 """repr(self)"""
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +0000173 return ('Rational(%r,%r)' % (self.numerator, self.denominator))
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000174
175 def __str__(self):
176 """str(self)"""
177 if self.denominator == 1:
178 return str(self.numerator)
179 else:
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +0000180 return '%s/%s' % (self.numerator, self.denominator)
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000181
Raymond Hettinger921cb5d2008-01-25 00:33:45 +0000182 """ XXX This section needs a lot more commentary
183
184 * Explain the typical sequence of checks, calls, and fallbacks.
185 * Explain the subtle reasons why this logic was needed.
186 * It is not clear how common cases are handled (for example, how
187 does the ratio of two huge integers get converted to a float
188 without overflowing the long-->float conversion.
189
190 """
191
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000192 def _operator_fallbacks(monomorphic_operator, fallback_operator):
193 """Generates forward and reverse operators given a purely-rational
194 operator and a function from the operator module.
195
196 Use this like:
197 __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op)
198
199 """
200 def forward(a, b):
201 if isinstance(b, RationalAbc):
202 # Includes ints.
203 return monomorphic_operator(a, b)
204 elif isinstance(b, float):
205 return fallback_operator(float(a), b)
206 elif isinstance(b, complex):
207 return fallback_operator(complex(a), b)
208 else:
209 return NotImplemented
210 forward.__name__ = '__' + fallback_operator.__name__ + '__'
211 forward.__doc__ = monomorphic_operator.__doc__
212
213 def reverse(b, a):
214 if isinstance(a, RationalAbc):
215 # Includes ints.
216 return monomorphic_operator(a, b)
217 elif isinstance(a, numbers.Real):
218 return fallback_operator(float(a), float(b))
219 elif isinstance(a, numbers.Complex):
220 return fallback_operator(complex(a), complex(b))
221 else:
222 return NotImplemented
223 reverse.__name__ = '__r' + fallback_operator.__name__ + '__'
224 reverse.__doc__ = monomorphic_operator.__doc__
225
226 return forward, reverse
227
228 def _add(a, b):
229 """a + b"""
230 return Rational(a.numerator * b.denominator +
231 b.numerator * a.denominator,
232 a.denominator * b.denominator)
233
234 __add__, __radd__ = _operator_fallbacks(_add, operator.add)
235
236 def _sub(a, b):
237 """a - b"""
238 return Rational(a.numerator * b.denominator -
239 b.numerator * a.denominator,
240 a.denominator * b.denominator)
241
242 __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub)
243
244 def _mul(a, b):
245 """a * b"""
246 return Rational(a.numerator * b.numerator, a.denominator * b.denominator)
247
248 __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul)
249
250 def _div(a, b):
251 """a / b"""
252 return Rational(a.numerator * b.denominator,
253 a.denominator * b.numerator)
254
255 __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv)
256 __div__, __rdiv__ = _operator_fallbacks(_div, operator.div)
257
Raymond Hettinger909e3342008-01-24 23:50:26 +0000258 def __floordiv__(a, b):
259 """a // b"""
260 # Will be math.floor(a / b) in 3.0.
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000261 div = a / b
262 if isinstance(div, RationalAbc):
263 # trunc(math.floor(div)) doesn't work if the rational is
264 # more precise than a float because the intermediate
265 # rounding may cross an integer boundary.
266 return div.numerator // div.denominator
267 else:
268 return math.floor(div)
269
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000270 def __rfloordiv__(b, a):
271 """a // b"""
272 # Will be math.floor(a / b) in 3.0.
Raymond Hettinger909e3342008-01-24 23:50:26 +0000273 div = a / b
274 if isinstance(div, RationalAbc):
275 # trunc(math.floor(div)) doesn't work if the rational is
276 # more precise than a float because the intermediate
277 # rounding may cross an integer boundary.
278 return div.numerator // div.denominator
279 else:
280 return math.floor(div)
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000281
282 def __mod__(a, b):
283 """a % b"""
Raymond Hettinger909e3342008-01-24 23:50:26 +0000284 div = a // b
285 return a - b * div
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000286
287 def __rmod__(b, a):
288 """a % b"""
Raymond Hettinger909e3342008-01-24 23:50:26 +0000289 div = a // b
290 return a - b * div
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000291
292 def __pow__(a, b):
293 """a ** b
294
295 If b is not an integer, the result will be a float or complex
296 since roots are generally irrational. If b is an integer, the
297 result will be rational.
298
299 """
300 if isinstance(b, RationalAbc):
301 if b.denominator == 1:
302 power = b.numerator
303 if power >= 0:
304 return Rational(a.numerator ** power,
305 a.denominator ** power)
306 else:
307 return Rational(a.denominator ** -power,
308 a.numerator ** -power)
309 else:
310 # A fractional power will generally produce an
311 # irrational number.
312 return float(a) ** float(b)
313 else:
314 return float(a) ** b
315
316 def __rpow__(b, a):
317 """a ** b"""
318 if b.denominator == 1 and b.numerator >= 0:
319 # If a is an int, keep it that way if possible.
320 return a ** b.numerator
321
322 if isinstance(a, RationalAbc):
323 return Rational(a.numerator, a.denominator) ** b
324
325 if b.denominator == 1:
326 return a ** b.numerator
327
328 return a ** float(b)
329
330 def __pos__(a):
331 """+a: Coerces a subclass instance to Rational"""
332 return Rational(a.numerator, a.denominator)
333
334 def __neg__(a):
335 """-a"""
336 return Rational(-a.numerator, a.denominator)
337
338 def __abs__(a):
339 """abs(a)"""
340 return Rational(abs(a.numerator), a.denominator)
341
342 def __trunc__(a):
343 """trunc(a)"""
344 if a.numerator < 0:
345 return -(-a.numerator // a.denominator)
346 else:
347 return a.numerator // a.denominator
348
Raymond Hettinger5b0e27e2008-01-24 19:30:19 +0000349 __int__ = __trunc__
350
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000351 def __floor__(a):
352 """Will be math.floor(a) in 3.0."""
353 return a.numerator // a.denominator
354
355 def __ceil__(a):
356 """Will be math.ceil(a) in 3.0."""
357 # The negations cleverly convince floordiv to return the ceiling.
358 return -(-a.numerator // a.denominator)
359
360 def __round__(self, ndigits=None):
361 """Will be round(self, ndigits) in 3.0.
362
363 Rounds half toward even.
364 """
365 if ndigits is None:
366 floor, remainder = divmod(self.numerator, self.denominator)
367 if remainder * 2 < self.denominator:
368 return floor
369 elif remainder * 2 > self.denominator:
370 return floor + 1
371 # Deal with the half case:
372 elif floor % 2 == 0:
373 return floor
374 else:
375 return floor + 1
376 shift = 10**abs(ndigits)
377 # See _operator_fallbacks.forward to check that the results of
378 # these operations will always be Rational and therefore have
379 # __round__().
380 if ndigits > 0:
381 return Rational((self * shift).__round__(), shift)
382 else:
383 return Rational((self / shift).__round__() * shift)
384
385 def __hash__(self):
386 """hash(self)
387
388 Tricky because values that are exactly representable as a
389 float must have the same hash as that float.
390
391 """
Raymond Hettinger921cb5d2008-01-25 00:33:45 +0000392 # XXX since this method is expensive, consider caching the result
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000393 if self.denominator == 1:
394 # Get integers right.
395 return hash(self.numerator)
396 # Expensive check, but definitely correct.
397 if self == float(self):
398 return hash(float(self))
399 else:
400 # Use tuple's hash to avoid a high collision rate on
401 # simple fractions.
402 return hash((self.numerator, self.denominator))
403
404 def __eq__(a, b):
405 """a == b"""
406 if isinstance(b, RationalAbc):
407 return (a.numerator == b.numerator and
408 a.denominator == b.denominator)
409 if isinstance(b, numbers.Complex) and b.imag == 0:
410 b = b.real
411 if isinstance(b, float):
412 return a == a.from_float(b)
413 else:
414 # XXX: If b.__eq__ is implemented like this method, it may
415 # give the wrong answer after float(a) changes a's
416 # value. Better ways of doing this are welcome.
417 return float(a) == b
418
419 def _subtractAndCompareToZero(a, b, op):
420 """Helper function for comparison operators.
421
422 Subtracts b from a, exactly if possible, and compares the
423 result with 0 using op, in such a way that the comparison
424 won't recurse. If the difference raises a TypeError, returns
425 NotImplemented instead.
426
427 """
428 if isinstance(b, numbers.Complex) and b.imag == 0:
429 b = b.real
430 if isinstance(b, float):
431 b = a.from_float(b)
432 try:
433 # XXX: If b <: Real but not <: RationalAbc, this is likely
434 # to fall back to a float. If the actual values differ by
435 # less than MIN_FLOAT, this could falsely call them equal,
436 # which would make <= inconsistent with ==. Better ways of
437 # doing this are welcome.
438 diff = a - b
439 except TypeError:
440 return NotImplemented
441 if isinstance(diff, RationalAbc):
442 return op(diff.numerator, 0)
443 return op(diff, 0)
444
445 def __lt__(a, b):
446 """a < b"""
447 return a._subtractAndCompareToZero(b, operator.lt)
448
449 def __gt__(a, b):
450 """a > b"""
451 return a._subtractAndCompareToZero(b, operator.gt)
452
453 def __le__(a, b):
454 """a <= b"""
455 return a._subtractAndCompareToZero(b, operator.le)
456
457 def __ge__(a, b):
458 """a >= b"""
459 return a._subtractAndCompareToZero(b, operator.ge)
460
461 def __nonzero__(a):
462 """a != 0"""
463 return a.numerator != 0
Raymond Hettingera6216742008-01-25 00:21:54 +0000464
465 # support for pickling, copy, and deepcopy
466
467 def __reduce__(self):
468 return (self.__class__, (str(self),))
469
470 def __copy__(self):
471 if type(self) == Rational:
472 return self # I'm immutable; therefore I am my own clone
473 return self.__class__(self.numerator, self.denominator)
474
475 def __deepcopy__(self, memo):
476 if type(self) == Rational:
477 return self # My components are also immutable
478 return self.__class__(self.numerator, self.denominator)