Rational number implemented as a normalized pair of ints.
| 26 | return isinstance(x, Rat) |
| 27 | |
| 28 | class Rat(object): |
| 29 | |
| 30 | """Rational number implemented as a normalized pair of ints.""" |
| 31 | |
| 32 | __slots__ = ['_Rat__num', '_Rat__den'] |
| 33 | |
| 34 | def __init__(self, num=0, den=1): |
| 35 | """Constructor: Rat([num[, den]]). |
| 36 | |
| 37 | The arguments must be ints, and default to (0, 1).""" |
| 38 | if not isint(num): |
| 39 | raise TypeError("Rat numerator must be int (%r)" % num) |
| 40 | if not isint(den): |
| 41 | raise TypeError("Rat denominator must be int (%r)" % den) |
| 42 | # But the zero is always on |
| 43 | if den == 0: |
| 44 | raise ZeroDivisionError("zero denominator") |
| 45 | g = gcd(den, num) |
| 46 | self.__num = int(num//g) |
| 47 | self.__den = int(den//g) |
| 48 | |
| 49 | def _get_num(self): |
| 50 | """Accessor function for read-only 'num' attribute of Rat.""" |
| 51 | return self.__num |
| 52 | num = property(_get_num, None) |
| 53 | |
| 54 | def _get_den(self): |
| 55 | """Accessor function for read-only 'den' attribute of Rat.""" |
| 56 | return self.__den |
| 57 | den = property(_get_den, None) |
| 58 | |
| 59 | def __repr__(self): |
| 60 | """Convert a Rat to a string resembling a Rat constructor call.""" |
| 61 | return "Rat(%d, %d)" % (self.__num, self.__den) |
| 62 | |
| 63 | def __str__(self): |
| 64 | """Convert a Rat to a string resembling a decimal numeric value.""" |
| 65 | return str(float(self)) |
| 66 | |
| 67 | def __float__(self): |
| 68 | """Convert a Rat to a float.""" |
| 69 | return self.__num*1.0/self.__den |
| 70 | |
| 71 | def __int__(self): |
| 72 | """Convert a Rat to an int; self.den must be 1.""" |
| 73 | if self.__den == 1: |
| 74 | try: |
| 75 | return int(self.__num) |
| 76 | except OverflowError: |
| 77 | raise OverflowError("%s too large to convert to int" % |
| 78 | repr(self)) |
| 79 | raise ValueError("can't convert %s to int" % repr(self)) |
| 80 | |
| 81 | def __add__(self, other): |
| 82 | """Add two Rats, or a Rat and a number.""" |
| 83 | if isint(other): |
| 84 | other = Rat(other) |
| 85 | if isRat(other): |