blob: 19e7f141b484bcd84ddbf13649c42f3e953cb69f [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
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000175 @property
176 def numerator(a):
177 return a._numerator
178
179 @property
180 def denominator(a):
181 return a._denominator
182
183 def __repr__(self):
184 """repr(self)"""
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +0000185 return ('Rational(%r,%r)' % (self.numerator, self.denominator))
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000186
187 def __str__(self):
188 """str(self)"""
189 if self.denominator == 1:
190 return str(self.numerator)
191 else:
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +0000192 return '%s/%s' % (self.numerator, self.denominator)
Jeffrey Yasskind7b00332008-01-15 07:46:24 +0000193
194 def _operator_fallbacks(monomorphic_operator, fallback_operator):
195 """Generates forward and reverse operators given a purely-rational
196 operator and a function from the operator module.
197
198 Use this like:
199 __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op)
200
201 """
202 def forward(a, b):
203 if isinstance(b, RationalAbc):
204 # Includes ints.
205 return monomorphic_operator(a, b)
206 elif isinstance(b, float):
207 return fallback_operator(float(a), b)
208 elif isinstance(b, complex):
209 return fallback_operator(complex(a), b)
210 else:
211 return NotImplemented
212 forward.__name__ = '__' + fallback_operator.__name__ + '__'
213 forward.__doc__ = monomorphic_operator.__doc__
214
215 def reverse(b, a):
216 if isinstance(a, RationalAbc):
217 # Includes ints.
218 return monomorphic_operator(a, b)
219 elif isinstance(a, numbers.Real):
220 return fallback_operator(float(a), float(b))
221 elif isinstance(a, numbers.Complex):
222 return fallback_operator(complex(a), complex(b))
223 else:
224 return NotImplemented
225 reverse.__name__ = '__r' + fallback_operator.__name__ + '__'
226 reverse.__doc__ = monomorphic_operator.__doc__
227
228 return forward, reverse
229
230 def _add(a, b):
231 """a + b"""
232 return Rational(a.numerator * b.denominator +
233 b.numerator * a.denominator,
234 a.denominator * b.denominator)
235
236 __add__, __radd__ = _operator_fallbacks(_add, operator.add)
237
238 def _sub(a, b):
239 """a - b"""
240 return Rational(a.numerator * b.denominator -
241 b.numerator * a.denominator,
242 a.denominator * b.denominator)
243
244 __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub)
245
246 def _mul(a, b):
247 """a * b"""
248 return Rational(a.numerator * b.numerator, a.denominator * b.denominator)
249
250 __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul)
251
252 def _div(a, b):
253 """a / b"""
254 return Rational(a.numerator * b.denominator,
255 a.denominator * b.numerator)
256
257 __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv)
258 __div__, __rdiv__ = _operator_fallbacks(_div, operator.div)
259
260 @classmethod
261 def _floordiv(cls, a, b):
262 div = a / b
263 if isinstance(div, RationalAbc):
264 # trunc(math.floor(div)) doesn't work if the rational is
265 # more precise than a float because the intermediate
266 # rounding may cross an integer boundary.
267 return div.numerator // div.denominator
268 else:
269 return math.floor(div)
270
271 def __floordiv__(a, b):
272 """a // b"""
273 # Will be math.floor(a / b) in 3.0.
274 return a._floordiv(a, b)
275
276 def __rfloordiv__(b, a):
277 """a // b"""
278 # Will be math.floor(a / b) in 3.0.
279 return b._floordiv(a, b)
280
281 @classmethod
282 def _mod(cls, a, b):
283 div = a // b
284 return a - b * div
285
286 def __mod__(a, b):
287 """a % b"""
288 return a._mod(a, b)
289
290 def __rmod__(b, a):
291 """a % b"""
292 return b._mod(a, b)
293
294 def __pow__(a, b):
295 """a ** b
296
297 If b is not an integer, the result will be a float or complex
298 since roots are generally irrational. If b is an integer, the
299 result will be rational.
300
301 """
302 if isinstance(b, RationalAbc):
303 if b.denominator == 1:
304 power = b.numerator
305 if power >= 0:
306 return Rational(a.numerator ** power,
307 a.denominator ** power)
308 else:
309 return Rational(a.denominator ** -power,
310 a.numerator ** -power)
311 else:
312 # A fractional power will generally produce an
313 # irrational number.
314 return float(a) ** float(b)
315 else:
316 return float(a) ** b
317
318 def __rpow__(b, a):
319 """a ** b"""
320 if b.denominator == 1 and b.numerator >= 0:
321 # If a is an int, keep it that way if possible.
322 return a ** b.numerator
323
324 if isinstance(a, RationalAbc):
325 return Rational(a.numerator, a.denominator) ** b
326
327 if b.denominator == 1:
328 return a ** b.numerator
329
330 return a ** float(b)
331
332 def __pos__(a):
333 """+a: Coerces a subclass instance to Rational"""
334 return Rational(a.numerator, a.denominator)
335
336 def __neg__(a):
337 """-a"""
338 return Rational(-a.numerator, a.denominator)
339
340 def __abs__(a):
341 """abs(a)"""
342 return Rational(abs(a.numerator), a.denominator)
343
344 def __trunc__(a):
345 """trunc(a)"""
346 if a.numerator < 0:
347 return -(-a.numerator // a.denominator)
348 else:
349 return a.numerator // a.denominator
350
351 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 """
392 if self.denominator == 1:
393 # Get integers right.
394 return hash(self.numerator)
395 # Expensive check, but definitely correct.
396 if self == float(self):
397 return hash(float(self))
398 else:
399 # Use tuple's hash to avoid a high collision rate on
400 # simple fractions.
401 return hash((self.numerator, self.denominator))
402
403 def __eq__(a, b):
404 """a == b"""
405 if isinstance(b, RationalAbc):
406 return (a.numerator == b.numerator and
407 a.denominator == b.denominator)
408 if isinstance(b, numbers.Complex) and b.imag == 0:
409 b = b.real
410 if isinstance(b, float):
411 return a == a.from_float(b)
412 else:
413 # XXX: If b.__eq__ is implemented like this method, it may
414 # give the wrong answer after float(a) changes a's
415 # value. Better ways of doing this are welcome.
416 return float(a) == b
417
418 def _subtractAndCompareToZero(a, b, op):
419 """Helper function for comparison operators.
420
421 Subtracts b from a, exactly if possible, and compares the
422 result with 0 using op, in such a way that the comparison
423 won't recurse. If the difference raises a TypeError, returns
424 NotImplemented instead.
425
426 """
427 if isinstance(b, numbers.Complex) and b.imag == 0:
428 b = b.real
429 if isinstance(b, float):
430 b = a.from_float(b)
431 try:
432 # XXX: If b <: Real but not <: RationalAbc, this is likely
433 # to fall back to a float. If the actual values differ by
434 # less than MIN_FLOAT, this could falsely call them equal,
435 # which would make <= inconsistent with ==. Better ways of
436 # doing this are welcome.
437 diff = a - b
438 except TypeError:
439 return NotImplemented
440 if isinstance(diff, RationalAbc):
441 return op(diff.numerator, 0)
442 return op(diff, 0)
443
444 def __lt__(a, b):
445 """a < b"""
446 return a._subtractAndCompareToZero(b, operator.lt)
447
448 def __gt__(a, b):
449 """a > b"""
450 return a._subtractAndCompareToZero(b, operator.gt)
451
452 def __le__(a, b):
453 """a <= b"""
454 return a._subtractAndCompareToZero(b, operator.le)
455
456 def __ge__(a, b):
457 """a >= b"""
458 return a._subtractAndCompareToZero(b, operator.ge)
459
460 def __nonzero__(a):
461 """a != 0"""
462 return a.numerator != 0