blob: 070e593bad8a14fada0be284c267fdb39b275a3b [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 Hettingereb461902008-01-24 02:00:25 +0000182 if seq:
183 return cls(n, d)
184 return 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 @property
214 def numerator(a):
215 return a._numerator
216
217 @property
218 def denominator(a):
219 return a._denominator
220
221 def __repr__(self):
222 """repr(self)"""
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +0000223 return ('Rational(%r,%r)' % (self.numerator, self.denominator))
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000224
225 def __str__(self):
226 """str(self)"""
227 if self.denominator == 1:
228 return str(self.numerator)
229 else:
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +0000230 return '%s/%s' % (self.numerator, self.denominator)
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000231
232 def _operator_fallbacks(monomorphic_operator, fallback_operator):
233 """Generates forward and reverse operators given a purely-rational
234 operator and a function from the operator module.
235
236 Use this like:
237 __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op)
238
239 """
240 def forward(a, b):
241 if isinstance(b, RationalAbc):
242 # Includes ints.
243 return monomorphic_operator(a, b)
244 elif isinstance(b, float):
245 return fallback_operator(float(a), b)
246 elif isinstance(b, complex):
247 return fallback_operator(complex(a), b)
248 else:
249 return NotImplemented
250 forward.__name__ = '__' + fallback_operator.__name__ + '__'
251 forward.__doc__ = monomorphic_operator.__doc__
252
253 def reverse(b, a):
254 if isinstance(a, RationalAbc):
255 # Includes ints.
256 return monomorphic_operator(a, b)
257 elif isinstance(a, numbers.Real):
258 return fallback_operator(float(a), float(b))
259 elif isinstance(a, numbers.Complex):
260 return fallback_operator(complex(a), complex(b))
261 else:
262 return NotImplemented
263 reverse.__name__ = '__r' + fallback_operator.__name__ + '__'
264 reverse.__doc__ = monomorphic_operator.__doc__
265
266 return forward, reverse
267
268 def _add(a, b):
269 """a + b"""
270 return Rational(a.numerator * b.denominator +
271 b.numerator * a.denominator,
272 a.denominator * b.denominator)
273
274 __add__, __radd__ = _operator_fallbacks(_add, operator.add)
275
276 def _sub(a, b):
277 """a - b"""
278 return Rational(a.numerator * b.denominator -
279 b.numerator * a.denominator,
280 a.denominator * b.denominator)
281
282 __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub)
283
284 def _mul(a, b):
285 """a * b"""
286 return Rational(a.numerator * b.numerator, a.denominator * b.denominator)
287
288 __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul)
289
290 def _div(a, b):
291 """a / b"""
292 return Rational(a.numerator * b.denominator,
293 a.denominator * b.numerator)
294
295 __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv)
296 __div__, __rdiv__ = _operator_fallbacks(_div, operator.div)
297
298 @classmethod
299 def _floordiv(cls, a, b):
300 div = a / b
301 if isinstance(div, RationalAbc):
302 # trunc(math.floor(div)) doesn't work if the rational is
303 # more precise than a float because the intermediate
304 # rounding may cross an integer boundary.
305 return div.numerator // div.denominator
306 else:
307 return math.floor(div)
308
309 def __floordiv__(a, b):
310 """a // b"""
311 # Will be math.floor(a / b) in 3.0.
312 return a._floordiv(a, b)
313
314 def __rfloordiv__(b, a):
315 """a // b"""
316 # Will be math.floor(a / b) in 3.0.
317 return b._floordiv(a, b)
318
319 @classmethod
320 def _mod(cls, a, b):
321 div = a // b
322 return a - b * div
323
324 def __mod__(a, b):
325 """a % b"""
326 return a._mod(a, b)
327
328 def __rmod__(b, a):
329 """a % b"""
330 return b._mod(a, b)
331
332 def __pow__(a, b):
333 """a ** b
334
335 If b is not an integer, the result will be a float or complex
336 since roots are generally irrational. If b is an integer, the
337 result will be rational.
338
339 """
340 if isinstance(b, RationalAbc):
341 if b.denominator == 1:
342 power = b.numerator
343 if power >= 0:
344 return Rational(a.numerator ** power,
345 a.denominator ** power)
346 else:
347 return Rational(a.denominator ** -power,
348 a.numerator ** -power)
349 else:
350 # A fractional power will generally produce an
351 # irrational number.
352 return float(a) ** float(b)
353 else:
354 return float(a) ** b
355
356 def __rpow__(b, a):
357 """a ** b"""
358 if b.denominator == 1 and b.numerator >= 0:
359 # If a is an int, keep it that way if possible.
360 return a ** b.numerator
361
362 if isinstance(a, RationalAbc):
363 return Rational(a.numerator, a.denominator) ** b
364
365 if b.denominator == 1:
366 return a ** b.numerator
367
368 return a ** float(b)
369
370 def __pos__(a):
371 """+a: Coerces a subclass instance to Rational"""
372 return Rational(a.numerator, a.denominator)
373
374 def __neg__(a):
375 """-a"""
376 return Rational(-a.numerator, a.denominator)
377
378 def __abs__(a):
379 """abs(a)"""
380 return Rational(abs(a.numerator), a.denominator)
381
382 def __trunc__(a):
383 """trunc(a)"""
384 if a.numerator < 0:
385 return -(-a.numerator // a.denominator)
386 else:
387 return a.numerator // a.denominator
388
389 def __floor__(a):
390 """Will be math.floor(a) in 3.0."""
391 return a.numerator // a.denominator
392
393 def __ceil__(a):
394 """Will be math.ceil(a) in 3.0."""
395 # The negations cleverly convince floordiv to return the ceiling.
396 return -(-a.numerator // a.denominator)
397
398 def __round__(self, ndigits=None):
399 """Will be round(self, ndigits) in 3.0.
400
401 Rounds half toward even.
402 """
403 if ndigits is None:
404 floor, remainder = divmod(self.numerator, self.denominator)
405 if remainder * 2 < self.denominator:
406 return floor
407 elif remainder * 2 > self.denominator:
408 return floor + 1
409 # Deal with the half case:
410 elif floor % 2 == 0:
411 return floor
412 else:
413 return floor + 1
414 shift = 10**abs(ndigits)
415 # See _operator_fallbacks.forward to check that the results of
416 # these operations will always be Rational and therefore have
417 # __round__().
418 if ndigits > 0:
419 return Rational((self * shift).__round__(), shift)
420 else:
421 return Rational((self / shift).__round__() * shift)
422
423 def __hash__(self):
424 """hash(self)
425
426 Tricky because values that are exactly representable as a
427 float must have the same hash as that float.
428
429 """
430 if self.denominator == 1:
431 # Get integers right.
432 return hash(self.numerator)
433 # Expensive check, but definitely correct.
434 if self == float(self):
435 return hash(float(self))
436 else:
437 # Use tuple's hash to avoid a high collision rate on
438 # simple fractions.
439 return hash((self.numerator, self.denominator))
440
441 def __eq__(a, b):
442 """a == b"""
443 if isinstance(b, RationalAbc):
444 return (a.numerator == b.numerator and
445 a.denominator == b.denominator)
446 if isinstance(b, numbers.Complex) and b.imag == 0:
447 b = b.real
448 if isinstance(b, float):
449 return a == a.from_float(b)
450 else:
451 # XXX: If b.__eq__ is implemented like this method, it may
452 # give the wrong answer after float(a) changes a's
453 # value. Better ways of doing this are welcome.
454 return float(a) == b
455
456 def _subtractAndCompareToZero(a, b, op):
457 """Helper function for comparison operators.
458
459 Subtracts b from a, exactly if possible, and compares the
460 result with 0 using op, in such a way that the comparison
461 won't recurse. If the difference raises a TypeError, returns
462 NotImplemented instead.
463
464 """
465 if isinstance(b, numbers.Complex) and b.imag == 0:
466 b = b.real
467 if isinstance(b, float):
468 b = a.from_float(b)
469 try:
470 # XXX: If b <: Real but not <: RationalAbc, this is likely
471 # to fall back to a float. If the actual values differ by
472 # less than MIN_FLOAT, this could falsely call them equal,
473 # which would make <= inconsistent with ==. Better ways of
474 # doing this are welcome.
475 diff = a - b
476 except TypeError:
477 return NotImplemented
478 if isinstance(diff, RationalAbc):
479 return op(diff.numerator, 0)
480 return op(diff, 0)
481
482 def __lt__(a, b):
483 """a < b"""
484 return a._subtractAndCompareToZero(b, operator.lt)
485
486 def __gt__(a, b):
487 """a > b"""
488 return a._subtractAndCompareToZero(b, operator.gt)
489
490 def __le__(a, b):
491 """a <= b"""
492 return a._subtractAndCompareToZero(b, operator.le)
493
494 def __ge__(a, b):
495 """a >= b"""
496 return a._subtractAndCompareToZero(b, operator.ge)
497
498 def __nonzero__(a):
499 """a != 0"""
500 return a.numerator != 0