blob: e34a7134407aa59404a6c332d91206f80f3f316d [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
17def _gcd(a, b):
18 """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 """
43
44 if x == 0:
45 return 0, 1
46 f, e = math.frexp(x)
47 signbit = 1
48 if f < 0:
49 f = -f
50 signbit = -1
51 assert 0.5 <= f < 1.0
52 # x = signbit * f * 2**e exactly
53
54 # Suck up CHUNK bits at a time; 28 is enough so that we suck
55 # up all bits in 2 iterations for all known binary double-
56 # precision formats, and small enough to fit in an int.
57 CHUNK = 28
58 top = 0
59 # invariant: x = signbit * (top + f) * 2**e exactly
60 while f:
61 f = math.ldexp(f, CHUNK)
62 digit = trunc(f)
63 assert digit >> CHUNK == 0
64 top = (top << CHUNK) | digit
65 f = f - digit
66 assert 0.0 <= f < 1.0
67 e = e - CHUNK
68 assert top
69
70 # Add in the sign bit.
71 top = signbit * top
72
73 # now x = top * 2**e exactly; fold in 2**e
74 if e>0:
75 return (top * 2**e, 1)
76 else:
77 return (top, 2 ** -e)
78
79
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +000080_RATIONAL_FORMAT = re.compile(
81 r'^\s*(?P<sign>[-+]?)(?P<num>\d+)(?:/(?P<denom>\d+))?\s*$')
82
83
Jeffrey Yasskind7b00332008-01-15 07:46:24 +000084class Rational(RationalAbc):
85 """This class implements rational numbers.
86
87 Rational(8, 6) will produce a rational number equivalent to
88 4/3. Both arguments must be Integral. The numerator defaults to 0
89 and the denominator defaults to 1 so that Rational(3) == 3 and
90 Rational() == 0.
91
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +000092 Rationals can also be constructed from strings of the form
93 '[-+]?[0-9]+(/[0-9]+)?', optionally surrounded by spaces.
94
Jeffrey Yasskind7b00332008-01-15 07:46:24 +000095 """
96
97 __slots__ = ('_numerator', '_denominator')
98
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +000099 # We're immutable, so use __new__ not __init__
100 def __new__(cls, numerator=0, denominator=1):
101 """Constructs a Rational.
102
103 Takes a string, another Rational, or a numerator/denominator pair.
104
105 """
106 self = super(Rational, cls).__new__(cls)
107
108 if denominator == 1:
109 if isinstance(numerator, basestring):
110 # Handle construction from strings.
111 input = numerator
112 m = _RATIONAL_FORMAT.match(input)
113 if m is None:
114 raise ValueError('Invalid literal for Rational: ' + input)
115 numerator = int(m.group('num'))
116 # Default denominator to 1. That's the only optional group.
117 denominator = int(m.group('denom') or 1)
118 if m.group('sign') == '-':
119 numerator = -numerator
120
121 elif (not isinstance(numerator, numbers.Integral) and
122 isinstance(numerator, RationalAbc)):
123 # Handle copies from other rationals.
124 other_rational = numerator
125 numerator = other_rational.numerator
126 denominator = other_rational.denominator
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000127
128 if (not isinstance(numerator, numbers.Integral) or
129 not isinstance(denominator, numbers.Integral)):
130 raise TypeError("Rational(%(numerator)s, %(denominator)s):"
131 " Both arguments must be integral." % locals())
132
133 if denominator == 0:
134 raise ZeroDivisionError('Rational(%s, 0)' % numerator)
135
136 g = _gcd(numerator, denominator)
137 self._numerator = int(numerator // g)
138 self._denominator = int(denominator // g)
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +0000139 return self
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000140
141 @classmethod
142 def from_float(cls, f):
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +0000143 """Converts a finite float to a rational number, exactly.
144
145 Beware that Rational.from_float(0.3) != Rational(3, 10).
146
147 """
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000148 if not isinstance(f, float):
149 raise TypeError("%s.from_float() only takes floats, not %r (%s)" %
150 (cls.__name__, f, type(f).__name__))
151 if math.isnan(f) or math.isinf(f):
152 raise TypeError("Cannot convert %r to %s." % (f, cls.__name__))
153 return cls(*_binary_float_to_ratio(f))
154
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +0000155 @classmethod
156 def from_decimal(cls, dec):
157 """Converts a finite Decimal instance to a rational number, exactly."""
158 from decimal import Decimal
159 if not isinstance(dec, Decimal):
160 raise TypeError(
161 "%s.from_decimal() only takes Decimals, not %r (%s)" %
162 (cls.__name__, dec, type(dec).__name__))
163 if not dec.is_finite():
164 # Catches infinities and nans.
165 raise TypeError("Cannot convert %s to %s." % (dec, cls.__name__))
166 sign, digits, exp = dec.as_tuple()
167 digits = int(''.join(map(str, digits)))
168 if sign:
169 digits = -digits
170 if exp >= 0:
171 return cls(digits * 10 ** exp)
172 else:
173 return cls(digits, 10 ** -exp)
174
Raymond Hettingercf109262008-01-24 00:54:21 +0000175 @classmethod
176 def from_continued_fraction(cls, seq):
177 'Build a Rational from a continued fraction expessed as a sequence'
178 n, d = 1, 0
179 for e in reversed(seq):
180 n, d = d, n
181 n += e * d
Raymond Hettingerf336c8b2008-01-24 02:05:06 +0000182 return cls(n, d) if seq else cls(0)
Raymond Hettingercf109262008-01-24 00:54:21 +0000183
184 def as_continued_fraction(self):
185 'Return continued fraction expressed as a list'
186 n = self.numerator
187 d = self.denominator
188 cf = []
189 while d:
190 e = int(n // d)
191 cf.append(e)
192 n -= e * d
193 n, d = d, n
194 return cf
195
196 @classmethod
197 def approximate_from_float(cls, f, max_denominator):
198 'Best rational approximation to f with a denominator <= max_denominator'
199 # XXX First cut at algorithm
200 # Still needs rounding rules as specified at
201 # http://en.wikipedia.org/wiki/Continued_fraction
202 cf = cls.from_float(f).as_continued_fraction()
Raymond Hettingereb461902008-01-24 02:00:25 +0000203 result = Rational(0)
Raymond Hettingercf109262008-01-24 00:54:21 +0000204 for i in range(1, len(cf)):
205 new = cls.from_continued_fraction(cf[:i])
206 if new.denominator > max_denominator:
207 break
208 result = new
209 return result
210
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000211 @property
212 def numerator(a):
213 return a._numerator
214
215 @property
216 def denominator(a):
217 return a._denominator
218
219 def __repr__(self):
220 """repr(self)"""
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +0000221 return ('Rational(%r,%r)' % (self.numerator, self.denominator))
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000222
223 def __str__(self):
224 """str(self)"""
225 if self.denominator == 1:
226 return str(self.numerator)
227 else:
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +0000228 return '%s/%s' % (self.numerator, self.denominator)
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000229
230 def _operator_fallbacks(monomorphic_operator, fallback_operator):
231 """Generates forward and reverse operators given a purely-rational
232 operator and a function from the operator module.
233
234 Use this like:
235 __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op)
236
237 """
238 def forward(a, b):
239 if isinstance(b, RationalAbc):
240 # Includes ints.
241 return monomorphic_operator(a, b)
242 elif isinstance(b, float):
243 return fallback_operator(float(a), b)
244 elif isinstance(b, complex):
245 return fallback_operator(complex(a), b)
246 else:
247 return NotImplemented
248 forward.__name__ = '__' + fallback_operator.__name__ + '__'
249 forward.__doc__ = monomorphic_operator.__doc__
250
251 def reverse(b, a):
252 if isinstance(a, RationalAbc):
253 # Includes ints.
254 return monomorphic_operator(a, b)
255 elif isinstance(a, numbers.Real):
256 return fallback_operator(float(a), float(b))
257 elif isinstance(a, numbers.Complex):
258 return fallback_operator(complex(a), complex(b))
259 else:
260 return NotImplemented
261 reverse.__name__ = '__r' + fallback_operator.__name__ + '__'
262 reverse.__doc__ = monomorphic_operator.__doc__
263
264 return forward, reverse
265
266 def _add(a, b):
267 """a + b"""
268 return Rational(a.numerator * b.denominator +
269 b.numerator * a.denominator,
270 a.denominator * b.denominator)
271
272 __add__, __radd__ = _operator_fallbacks(_add, operator.add)
273
274 def _sub(a, b):
275 """a - b"""
276 return Rational(a.numerator * b.denominator -
277 b.numerator * a.denominator,
278 a.denominator * b.denominator)
279
280 __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub)
281
282 def _mul(a, b):
283 """a * b"""
284 return Rational(a.numerator * b.numerator, a.denominator * b.denominator)
285
286 __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul)
287
288 def _div(a, b):
289 """a / b"""
290 return Rational(a.numerator * b.denominator,
291 a.denominator * b.numerator)
292
293 __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv)
294 __div__, __rdiv__ = _operator_fallbacks(_div, operator.div)
295
296 @classmethod
297 def _floordiv(cls, a, b):
298 div = a / b
299 if isinstance(div, RationalAbc):
300 # trunc(math.floor(div)) doesn't work if the rational is
301 # more precise than a float because the intermediate
302 # rounding may cross an integer boundary.
303 return div.numerator // div.denominator
304 else:
305 return math.floor(div)
306
307 def __floordiv__(a, b):
308 """a // b"""
309 # Will be math.floor(a / b) in 3.0.
310 return a._floordiv(a, b)
311
312 def __rfloordiv__(b, a):
313 """a // b"""
314 # Will be math.floor(a / b) in 3.0.
315 return b._floordiv(a, b)
316
317 @classmethod
318 def _mod(cls, a, b):
319 div = a // b
320 return a - b * div
321
322 def __mod__(a, b):
323 """a % b"""
324 return a._mod(a, b)
325
326 def __rmod__(b, a):
327 """a % b"""
328 return b._mod(a, b)
329
330 def __pow__(a, b):
331 """a ** b
332
333 If b is not an integer, the result will be a float or complex
334 since roots are generally irrational. If b is an integer, the
335 result will be rational.
336
337 """
338 if isinstance(b, RationalAbc):
339 if b.denominator == 1:
340 power = b.numerator
341 if power >= 0:
342 return Rational(a.numerator ** power,
343 a.denominator ** power)
344 else:
345 return Rational(a.denominator ** -power,
346 a.numerator ** -power)
347 else:
348 # A fractional power will generally produce an
349 # irrational number.
350 return float(a) ** float(b)
351 else:
352 return float(a) ** b
353
354 def __rpow__(b, a):
355 """a ** b"""
356 if b.denominator == 1 and b.numerator >= 0:
357 # If a is an int, keep it that way if possible.
358 return a ** b.numerator
359
360 if isinstance(a, RationalAbc):
361 return Rational(a.numerator, a.denominator) ** b
362
363 if b.denominator == 1:
364 return a ** b.numerator
365
366 return a ** float(b)
367
368 def __pos__(a):
369 """+a: Coerces a subclass instance to Rational"""
370 return Rational(a.numerator, a.denominator)
371
372 def __neg__(a):
373 """-a"""
374 return Rational(-a.numerator, a.denominator)
375
376 def __abs__(a):
377 """abs(a)"""
378 return Rational(abs(a.numerator), a.denominator)
379
380 def __trunc__(a):
381 """trunc(a)"""
382 if a.numerator < 0:
383 return -(-a.numerator // a.denominator)
384 else:
385 return a.numerator // a.denominator
386
387 def __floor__(a):
388 """Will be math.floor(a) in 3.0."""
389 return a.numerator // a.denominator
390
391 def __ceil__(a):
392 """Will be math.ceil(a) in 3.0."""
393 # The negations cleverly convince floordiv to return the ceiling.
394 return -(-a.numerator // a.denominator)
395
396 def __round__(self, ndigits=None):
397 """Will be round(self, ndigits) in 3.0.
398
399 Rounds half toward even.
400 """
401 if ndigits is None:
402 floor, remainder = divmod(self.numerator, self.denominator)
403 if remainder * 2 < self.denominator:
404 return floor
405 elif remainder * 2 > self.denominator:
406 return floor + 1
407 # Deal with the half case:
408 elif floor % 2 == 0:
409 return floor
410 else:
411 return floor + 1
412 shift = 10**abs(ndigits)
413 # See _operator_fallbacks.forward to check that the results of
414 # these operations will always be Rational and therefore have
415 # __round__().
416 if ndigits > 0:
417 return Rational((self * shift).__round__(), shift)
418 else:
419 return Rational((self / shift).__round__() * shift)
420
421 def __hash__(self):
422 """hash(self)
423
424 Tricky because values that are exactly representable as a
425 float must have the same hash as that float.
426
427 """
428 if self.denominator == 1:
429 # Get integers right.
430 return hash(self.numerator)
431 # Expensive check, but definitely correct.
432 if self == float(self):
433 return hash(float(self))
434 else:
435 # Use tuple's hash to avoid a high collision rate on
436 # simple fractions.
437 return hash((self.numerator, self.denominator))
438
439 def __eq__(a, b):
440 """a == b"""
441 if isinstance(b, RationalAbc):
442 return (a.numerator == b.numerator and
443 a.denominator == b.denominator)
444 if isinstance(b, numbers.Complex) and b.imag == 0:
445 b = b.real
446 if isinstance(b, float):
447 return a == a.from_float(b)
448 else:
449 # XXX: If b.__eq__ is implemented like this method, it may
450 # give the wrong answer after float(a) changes a's
451 # value. Better ways of doing this are welcome.
452 return float(a) == b
453
454 def _subtractAndCompareToZero(a, b, op):
455 """Helper function for comparison operators.
456
457 Subtracts b from a, exactly if possible, and compares the
458 result with 0 using op, in such a way that the comparison
459 won't recurse. If the difference raises a TypeError, returns
460 NotImplemented instead.
461
462 """
463 if isinstance(b, numbers.Complex) and b.imag == 0:
464 b = b.real
465 if isinstance(b, float):
466 b = a.from_float(b)
467 try:
468 # XXX: If b <: Real but not <: RationalAbc, this is likely
469 # to fall back to a float. If the actual values differ by
470 # less than MIN_FLOAT, this could falsely call them equal,
471 # which would make <= inconsistent with ==. Better ways of
472 # doing this are welcome.
473 diff = a - b
474 except TypeError:
475 return NotImplemented
476 if isinstance(diff, RationalAbc):
477 return op(diff.numerator, 0)
478 return op(diff, 0)
479
480 def __lt__(a, b):
481 """a < b"""
482 return a._subtractAndCompareToZero(b, operator.lt)
483
484 def __gt__(a, b):
485 """a > b"""
486 return a._subtractAndCompareToZero(b, operator.gt)
487
488 def __le__(a, b):
489 """a <= b"""
490 return a._subtractAndCompareToZero(b, operator.le)
491
492 def __ge__(a, b):
493 """a >= b"""
494 return a._subtractAndCompareToZero(b, operator.ge)
495
496 def __nonzero__(a):
497 """a != 0"""
498 return a.numerator != 0