blob: 8de8f230ad7a489452c58964e17bf1e04c227aed [file] [log] [blame]
Guido van Rossum7736b5b2008-01-15 21:44:53 +00001# Originally contributed by Sjoerd Mullender.
2# Significantly modified by Jeffrey Yasskin <jyasskin at gmail.com>.
3
4"""Rational, infinite-precision, real numbers."""
5
Guido van Rossum7736b5b2008-01-15 21:44:53 +00006import math
7import numbers
8import operator
Christian Heimes587c2bf2008-01-19 16:21:02 +00009import re
Guido van Rossum7736b5b2008-01-15 21:44:53 +000010
11__all__ = ["Rational"]
12
13RationalAbc = numbers.Rational
14
15
Christian Heimesaf98da12008-01-27 15:18:18 +000016def gcd(a, b):
17 """Calculate the Greatest Common Divisor of a and b.
Guido van Rossum7736b5b2008-01-15 21:44:53 +000018
19 Unless b==0, the result will have the same sign as b (so that when
20 b is divided by it, the result comes out positive).
21 """
22 while b:
23 a, b = b, a%b
24 return a
25
26
Christian Heimes587c2bf2008-01-19 16:21:02 +000027_RATIONAL_FORMAT = re.compile(
Christian Heimesaf98da12008-01-27 15:18:18 +000028 r'^\s*(?P<sign>[-+]?)(?P<num>\d+)'
29 r'(?:/(?P<denom>\d+)|\.(?P<decimal>\d+))?\s*$')
Christian Heimes587c2bf2008-01-19 16:21:02 +000030
31
Guido van Rossum7736b5b2008-01-15 21:44:53 +000032class Rational(RationalAbc):
33 """This class implements rational numbers.
34
35 Rational(8, 6) will produce a rational number equivalent to
36 4/3. Both arguments must be Integral. The numerator defaults to 0
37 and the denominator defaults to 1 so that Rational(3) == 3 and
38 Rational() == 0.
39
Christian Heimes587c2bf2008-01-19 16:21:02 +000040 Rationals can also be constructed from strings of the form
Christian Heimesaf98da12008-01-27 15:18:18 +000041 '[-+]?[0-9]+((/|.)[0-9]+)?', optionally surrounded by spaces.
Christian Heimes587c2bf2008-01-19 16:21:02 +000042
Guido van Rossum7736b5b2008-01-15 21:44:53 +000043 """
44
Christian Heimes969fe572008-01-25 11:23:10 +000045 __slots__ = ('numerator', 'denominator')
Guido van Rossum7736b5b2008-01-15 21:44:53 +000046
Christian Heimes587c2bf2008-01-19 16:21:02 +000047 # We're immutable, so use __new__ not __init__
48 def __new__(cls, numerator=0, denominator=1):
49 """Constructs a Rational.
50
Christian Heimesaf98da12008-01-27 15:18:18 +000051 Takes a string like '3/2' or '1.5', another Rational, or a
52 numerator/denominator pair.
Christian Heimes587c2bf2008-01-19 16:21:02 +000053
54 """
55 self = super(Rational, cls).__new__(cls)
56
57 if denominator == 1:
58 if isinstance(numerator, str):
59 # Handle construction from strings.
60 input = numerator
61 m = _RATIONAL_FORMAT.match(input)
62 if m is None:
63 raise ValueError('Invalid literal for Rational: ' + input)
Christian Heimesaf98da12008-01-27 15:18:18 +000064 numerator = m.group('num')
65 decimal = m.group('decimal')
66 if decimal:
67 # The literal is a decimal number.
68 numerator = int(numerator + decimal)
69 denominator = 10**len(decimal)
70 else:
71 # The literal is an integer or fraction.
72 numerator = int(numerator)
73 # Default denominator to 1.
74 denominator = int(m.group('denom') or 1)
75
Christian Heimes587c2bf2008-01-19 16:21:02 +000076 if m.group('sign') == '-':
77 numerator = -numerator
78
79 elif (not isinstance(numerator, numbers.Integral) and
80 isinstance(numerator, RationalAbc)):
81 # Handle copies from other rationals.
82 other_rational = numerator
83 numerator = other_rational.numerator
84 denominator = other_rational.denominator
Guido van Rossum7736b5b2008-01-15 21:44:53 +000085
86 if (not isinstance(numerator, numbers.Integral) or
87 not isinstance(denominator, numbers.Integral)):
88 raise TypeError("Rational(%(numerator)s, %(denominator)s):"
89 " Both arguments must be integral." % locals())
90
91 if denominator == 0:
92 raise ZeroDivisionError('Rational(%s, 0)' % numerator)
93
Christian Heimesaf98da12008-01-27 15:18:18 +000094 g = gcd(numerator, denominator)
Christian Heimes969fe572008-01-25 11:23:10 +000095 self.numerator = int(numerator // g)
96 self.denominator = int(denominator // g)
Christian Heimes587c2bf2008-01-19 16:21:02 +000097 return self
Guido van Rossum7736b5b2008-01-15 21:44:53 +000098
99 @classmethod
100 def from_float(cls, f):
Christian Heimes587c2bf2008-01-19 16:21:02 +0000101 """Converts a finite float to a rational number, exactly.
102
103 Beware that Rational.from_float(0.3) != Rational(3, 10).
104
105 """
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000106 if not isinstance(f, float):
107 raise TypeError("%s.from_float() only takes floats, not %r (%s)" %
108 (cls.__name__, f, type(f).__name__))
109 if math.isnan(f) or math.isinf(f):
110 raise TypeError("Cannot convert %r to %s." % (f, cls.__name__))
Christian Heimes26855632008-01-27 23:50:43 +0000111 return cls(*f.as_integer_ratio())
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000112
Christian Heimes587c2bf2008-01-19 16:21:02 +0000113 @classmethod
114 def from_decimal(cls, dec):
115 """Converts a finite Decimal instance to a rational number, exactly."""
116 from decimal import Decimal
117 if not isinstance(dec, Decimal):
118 raise TypeError(
119 "%s.from_decimal() only takes Decimals, not %r (%s)" %
120 (cls.__name__, dec, type(dec).__name__))
121 if not dec.is_finite():
122 # Catches infinities and nans.
123 raise TypeError("Cannot convert %s to %s." % (dec, cls.__name__))
124 sign, digits, exp = dec.as_tuple()
125 digits = int(''.join(map(str, digits)))
126 if sign:
127 digits = -digits
128 if exp >= 0:
129 return cls(digits * 10 ** exp)
130 else:
131 return cls(digits, 10 ** -exp)
132
Christian Heimesbbffeb62008-01-24 09:42:52 +0000133 @classmethod
134 def from_continued_fraction(cls, seq):
135 'Build a Rational from a continued fraction expessed as a sequence'
136 n, d = 1, 0
137 for e in reversed(seq):
138 n, d = d, n
139 n += e * d
140 return cls(n, d) if seq else cls(0)
141
142 def as_continued_fraction(self):
143 'Return continued fraction expressed as a list'
144 n = self.numerator
145 d = self.denominator
146 cf = []
147 while d:
148 e = int(n // d)
149 cf.append(e)
150 n -= e * d
151 n, d = d, n
152 return cf
153
Christian Heimes969fe572008-01-25 11:23:10 +0000154 def approximate(self, max_denominator):
155 'Best rational approximation with a denominator <= max_denominator'
Christian Heimesbbffeb62008-01-24 09:42:52 +0000156 # XXX First cut at algorithm
157 # Still needs rounding rules as specified at
158 # http://en.wikipedia.org/wiki/Continued_fraction
Christian Heimes969fe572008-01-25 11:23:10 +0000159 if self.denominator <= max_denominator:
160 return self
161 cf = self.as_continued_fraction()
Christian Heimesbbffeb62008-01-24 09:42:52 +0000162 result = Rational(0)
163 for i in range(1, len(cf)):
Christian Heimes969fe572008-01-25 11:23:10 +0000164 new = self.from_continued_fraction(cf[:i])
Christian Heimesbbffeb62008-01-24 09:42:52 +0000165 if new.denominator > max_denominator:
166 break
167 result = new
168 return result
169
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000170 def __repr__(self):
171 """repr(self)"""
Christian Heimes587c2bf2008-01-19 16:21:02 +0000172 return ('Rational(%r,%r)' % (self.numerator, self.denominator))
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000173
174 def __str__(self):
175 """str(self)"""
176 if self.denominator == 1:
177 return str(self.numerator)
178 else:
Christian Heimes587c2bf2008-01-19 16:21:02 +0000179 return '%s/%s' % (self.numerator, self.denominator)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000180
Christian Heimes969fe572008-01-25 11:23:10 +0000181 """ XXX This section needs a lot more commentary
182
183 * Explain the typical sequence of checks, calls, and fallbacks.
184 * Explain the subtle reasons why this logic was needed.
185 * It is not clear how common cases are handled (for example, how
186 does the ratio of two huge integers get converted to a float
187 without overflowing the long-->float conversion.
188
189 """
190
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000191 def _operator_fallbacks(monomorphic_operator, fallback_operator):
192 """Generates forward and reverse operators given a purely-rational
193 operator and a function from the operator module.
194
195 Use this like:
196 __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op)
197
198 """
199 def forward(a, b):
200 if isinstance(b, RationalAbc):
201 # Includes ints.
202 return monomorphic_operator(a, b)
203 elif isinstance(b, float):
204 return fallback_operator(float(a), b)
205 elif isinstance(b, complex):
206 return fallback_operator(complex(a), b)
207 else:
208 return NotImplemented
209 forward.__name__ = '__' + fallback_operator.__name__ + '__'
210 forward.__doc__ = monomorphic_operator.__doc__
211
212 def reverse(b, a):
213 if isinstance(a, RationalAbc):
214 # Includes ints.
215 return monomorphic_operator(a, b)
216 elif isinstance(a, numbers.Real):
217 return fallback_operator(float(a), float(b))
218 elif isinstance(a, numbers.Complex):
219 return fallback_operator(complex(a), complex(b))
220 else:
221 return NotImplemented
222 reverse.__name__ = '__r' + fallback_operator.__name__ + '__'
223 reverse.__doc__ = monomorphic_operator.__doc__
224
225 return forward, reverse
226
227 def _add(a, b):
228 """a + b"""
229 return Rational(a.numerator * b.denominator +
230 b.numerator * a.denominator,
231 a.denominator * b.denominator)
232
233 __add__, __radd__ = _operator_fallbacks(_add, operator.add)
234
235 def _sub(a, b):
236 """a - b"""
237 return Rational(a.numerator * b.denominator -
238 b.numerator * a.denominator,
239 a.denominator * b.denominator)
240
241 __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub)
242
243 def _mul(a, b):
244 """a * b"""
245 return Rational(a.numerator * b.numerator, a.denominator * b.denominator)
246
247 __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul)
248
249 def _div(a, b):
250 """a / b"""
251 return Rational(a.numerator * b.denominator,
252 a.denominator * b.numerator)
253
254 __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000255
256 def __floordiv__(a, b):
257 """a // b"""
Jeffrey Yasskin9893de12008-01-17 07:36:30 +0000258 return math.floor(a / b)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000259
260 def __rfloordiv__(b, a):
261 """a // b"""
Jeffrey Yasskin9893de12008-01-17 07:36:30 +0000262 return math.floor(a / b)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000263
Christian Heimes969fe572008-01-25 11:23:10 +0000264 def __mod__(a, b):
265 """a % b"""
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000266 div = a // b
267 return a - b * div
268
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000269 def __rmod__(b, a):
270 """a % b"""
Christian Heimes969fe572008-01-25 11:23:10 +0000271 div = a // b
272 return a - b * div
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000273
274 def __pow__(a, b):
275 """a ** b
276
277 If b is not an integer, the result will be a float or complex
278 since roots are generally irrational. If b is an integer, the
279 result will be rational.
280
281 """
282 if isinstance(b, RationalAbc):
283 if b.denominator == 1:
284 power = b.numerator
285 if power >= 0:
286 return Rational(a.numerator ** power,
287 a.denominator ** power)
288 else:
289 return Rational(a.denominator ** -power,
290 a.numerator ** -power)
291 else:
292 # A fractional power will generally produce an
293 # irrational number.
294 return float(a) ** float(b)
295 else:
296 return float(a) ** b
297
298 def __rpow__(b, a):
299 """a ** b"""
300 if b.denominator == 1 and b.numerator >= 0:
301 # If a is an int, keep it that way if possible.
302 return a ** b.numerator
303
304 if isinstance(a, RationalAbc):
305 return Rational(a.numerator, a.denominator) ** b
306
307 if b.denominator == 1:
308 return a ** b.numerator
309
310 return a ** float(b)
311
312 def __pos__(a):
313 """+a: Coerces a subclass instance to Rational"""
314 return Rational(a.numerator, a.denominator)
315
316 def __neg__(a):
317 """-a"""
318 return Rational(-a.numerator, a.denominator)
319
320 def __abs__(a):
321 """abs(a)"""
322 return Rational(abs(a.numerator), a.denominator)
323
324 def __trunc__(a):
325 """trunc(a)"""
326 if a.numerator < 0:
327 return -(-a.numerator // a.denominator)
328 else:
329 return a.numerator // a.denominator
330
Christian Heimes969fe572008-01-25 11:23:10 +0000331 __int__ = __trunc__
332
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000333 def __floor__(a):
334 """Will be math.floor(a) in 3.0."""
335 return a.numerator // a.denominator
336
337 def __ceil__(a):
338 """Will be math.ceil(a) in 3.0."""
339 # The negations cleverly convince floordiv to return the ceiling.
340 return -(-a.numerator // a.denominator)
341
342 def __round__(self, ndigits=None):
343 """Will be round(self, ndigits) in 3.0.
344
345 Rounds half toward even.
346 """
347 if ndigits is None:
348 floor, remainder = divmod(self.numerator, self.denominator)
349 if remainder * 2 < self.denominator:
350 return floor
351 elif remainder * 2 > self.denominator:
352 return floor + 1
353 # Deal with the half case:
354 elif floor % 2 == 0:
355 return floor
356 else:
357 return floor + 1
358 shift = 10**abs(ndigits)
359 # See _operator_fallbacks.forward to check that the results of
360 # these operations will always be Rational and therefore have
Jeffrey Yasskin9893de12008-01-17 07:36:30 +0000361 # round().
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000362 if ndigits > 0:
Jeffrey Yasskin9893de12008-01-17 07:36:30 +0000363 return Rational(round(self * shift), shift)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000364 else:
Jeffrey Yasskin9893de12008-01-17 07:36:30 +0000365 return Rational(round(self / shift) * shift)
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000366
367 def __hash__(self):
368 """hash(self)
369
370 Tricky because values that are exactly representable as a
371 float must have the same hash as that float.
372
373 """
Christian Heimes969fe572008-01-25 11:23:10 +0000374 # XXX since this method is expensive, consider caching the result
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000375 if self.denominator == 1:
376 # Get integers right.
377 return hash(self.numerator)
378 # Expensive check, but definitely correct.
379 if self == float(self):
380 return hash(float(self))
381 else:
382 # Use tuple's hash to avoid a high collision rate on
383 # simple fractions.
384 return hash((self.numerator, self.denominator))
385
386 def __eq__(a, b):
387 """a == b"""
388 if isinstance(b, RationalAbc):
389 return (a.numerator == b.numerator and
390 a.denominator == b.denominator)
391 if isinstance(b, numbers.Complex) and b.imag == 0:
392 b = b.real
393 if isinstance(b, float):
394 return a == a.from_float(b)
395 else:
396 # XXX: If b.__eq__ is implemented like this method, it may
397 # give the wrong answer after float(a) changes a's
398 # value. Better ways of doing this are welcome.
399 return float(a) == b
400
401 def _subtractAndCompareToZero(a, b, op):
402 """Helper function for comparison operators.
403
404 Subtracts b from a, exactly if possible, and compares the
405 result with 0 using op, in such a way that the comparison
406 won't recurse. If the difference raises a TypeError, returns
407 NotImplemented instead.
408
409 """
410 if isinstance(b, numbers.Complex) and b.imag == 0:
411 b = b.real
412 if isinstance(b, float):
413 b = a.from_float(b)
414 try:
415 # XXX: If b <: Real but not <: RationalAbc, this is likely
416 # to fall back to a float. If the actual values differ by
417 # less than MIN_FLOAT, this could falsely call them equal,
418 # which would make <= inconsistent with ==. Better ways of
419 # doing this are welcome.
420 diff = a - b
421 except TypeError:
422 return NotImplemented
423 if isinstance(diff, RationalAbc):
424 return op(diff.numerator, 0)
425 return op(diff, 0)
426
427 def __lt__(a, b):
428 """a < b"""
429 return a._subtractAndCompareToZero(b, operator.lt)
430
431 def __gt__(a, b):
432 """a > b"""
433 return a._subtractAndCompareToZero(b, operator.gt)
434
435 def __le__(a, b):
436 """a <= b"""
437 return a._subtractAndCompareToZero(b, operator.le)
438
439 def __ge__(a, b):
440 """a >= b"""
441 return a._subtractAndCompareToZero(b, operator.ge)
442
443 def __bool__(a):
444 """a != 0"""
445 return a.numerator != 0
Christian Heimes969fe572008-01-25 11:23:10 +0000446
447 # support for pickling, copy, and deepcopy
448
449 def __reduce__(self):
450 return (self.__class__, (str(self),))
451
452 def __copy__(self):
453 if type(self) == Rational:
454 return self # I'm immutable; therefore I am my own clone
455 return self.__class__(self.numerator, self.denominator)
456
457 def __deepcopy__(self, memo):
458 if type(self) == Rational:
459 return self # My components are also immutable
460 return self.__class__(self.numerator, self.denominator)