Index: Demo/classes/Rat.py =================================================================== --- Demo/classes/Rat.py (revision 59590) +++ Demo/classes/Rat.py (working copy) @@ -1,306 +0,0 @@ -'''\ -This module implements rational numbers. - -The entry point of this module is the function - rat(numerator, denominator) -If either numerator or denominator is of an integral or rational type, -the result is a rational number, else, the result is the simplest of -the types float and complex which can hold numerator/denominator. -If denominator is omitted, it defaults to 1. -Rational numbers can be used in calculations with any other numeric -type. The result of the calculation will be rational if possible. - -There is also a test function with calling sequence - test() -The documentation string of the test function contains the expected -output. -''' - -# Contributed by Sjoerd Mullender - -from types import * - -def gcd(a, b): - '''Calculate the Greatest Common Divisor.''' - while b: - a, b = b, a%b - return a - -def rat(num, den = 1): - # must check complex before float - if isinstance(num, complex) or isinstance(den, complex): - # numerator or denominator is complex: return a complex - return complex(num) / complex(den) - if isinstance(num, float) or isinstance(den, float): - # numerator or denominator is float: return a float - return float(num) / float(den) - # otherwise return a rational - return Rat(num, den) - -class Rat: - '''This class implements rational numbers.''' - - def __init__(self, num, den = 1): - if den == 0: - raise ZeroDivisionError('rat(x, 0)') - - # normalize - - # must check complex before float - if (isinstance(num, complex) or - isinstance(den, complex)): - # numerator or denominator is complex: - # normalized form has denominator == 1+0j - self.__num = complex(num) / complex(den) - self.__den = complex(1) - return - if isinstance(num, float) or isinstance(den, float): - # numerator or denominator is float: - # normalized form has denominator == 1.0 - self.__num = float(num) / float(den) - self.__den = 1.0 - return - if (isinstance(num, self.__class__) or - isinstance(den, self.__class__)): - # numerator or denominator is rational - new = num / den - if not isinstance(new, self.__class__): - self.__num = new - if isinstance(new, complex): - self.__den = complex(1) - else: - self.__den = 1.0 - else: - self.__num = new.__num - self.__den = new.__den - else: - # make sure numerator and denominator don't - # have common factors - # this also makes sure that denominator > 0 - g = gcd(num, den) - self.__num = num / g - self.__den = den / g - # try making numerator and denominator of IntType if they fit - try: - numi = int(self.__num) - deni = int(self.__den) - except (OverflowError, TypeError): - pass - else: - if self.__num == numi and self.__den == deni: - self.__num = numi - self.__den = deni - - def __repr__(self): - return 'Rat(%s,%s)' % (self.__num, self.__den) - - def __str__(self): - if self.__den == 1: - return str(self.__num) - else: - return '(%s/%s)' % (str(self.__num), str(self.__den)) - - # a + b - def __add__(a, b): - try: - return rat(a.__num * b.__den + b.__num * a.__den, - a.__den * b.__den) - except OverflowError: - return rat(int(a.__num) * int(b.__den) + - int(b.__num) * int(a.__den), - int(a.__den) * int(b.__den)) - - def __radd__(b, a): - return Rat(a) + b - - # a - b - def __sub__(a, b): - try: - return rat(a.__num * b.__den - b.__num * a.__den, - a.__den * b.__den) - except OverflowError: - return rat(int(a.__num) * int(b.__den) - - int(b.__num) * int(a.__den), - int(a.__den) * int(b.__den)) - - def __rsub__(b, a): - return Rat(a) - b - - # a * b - def __mul__(a, b): - try: - return rat(a.__num * b.__num, a.__den * b.__den) - except OverflowError: - return rat(int(a.__num) * int(b.__num), - int(a.__den) * int(b.__den)) - - def __rmul__(b, a): - return Rat(a) * b - - # a / b - def __div__(a, b): - try: - return rat(a.__num * b.__den, a.__den * b.__num) - except OverflowError: - return rat(int(a.__num) * int(b.__den), - int(a.__den) * int(b.__num)) - - def __rdiv__(b, a): - return Rat(a) / b - - # a % b - def __mod__(a, b): - div = a / b - try: - div = int(div) - except OverflowError: - div = int(div) - return a - b * div - - def __rmod__(b, a): - return Rat(a) % b - - # a ** b - def __pow__(a, b): - if b.__den != 1: - if isinstance(a.__num, complex): - a = complex(a) - else: - a = float(a) - if isinstance(b.__num, complex): - b = complex(b) - else: - b = float(b) - return a ** b - try: - return rat(a.__num ** b.__num, a.__den ** b.__num) - except OverflowError: - return rat(int(a.__num) ** b.__num, - int(a.__den) ** b.__num) - - def __rpow__(b, a): - return Rat(a) ** b - - # -a - def __neg__(a): - try: - return rat(-a.__num, a.__den) - except OverflowError: - # a.__num == sys.maxint - return rat(-int(a.__num), a.__den) - - # abs(a) - def __abs__(a): - return rat(abs(a.__num), a.__den) - - # int(a) - def __int__(a): - return int(a.__num / a.__den) - - # long(a) - def __long__(a): - return int(a.__num) / int(a.__den) - - # float(a) - def __float__(a): - return float(a.__num) / float(a.__den) - - # complex(a) - def __complex__(a): - return complex(a.__num) / complex(a.__den) - - # cmp(a,b) - def __cmp__(a, b): - diff = Rat(a - b) - if diff.__num < 0: - return -1 - elif diff.__num > 0: - return 1 - else: - return 0 - - def __rcmp__(b, a): - return cmp(Rat(a), b) - - # a != 0 - def __bool__(a): - return a.__num != 0 - -def test(): - '''\ - Test function for rat module. - - The expected output is (module some differences in floating - precission): - -1 - -1 - 0 0L 0.1 (0.1+0j) - [Rat(1,2), Rat(-3,10), Rat(1,25), Rat(1,4)] - [Rat(-3,10), Rat(1,25), Rat(1,4), Rat(1,2)] - 0 - (11/10) - (11/10) - 1.1 - OK - 2 1.5 (3/2) (1.5+1.5j) (15707963/5000000) - 2 2 2.0 (2+0j) - - 4 0 4 1 4 0 - 3.5 0.5 3.0 1.33333333333 2.82842712475 1 - (7/2) (1/2) 3 (4/3) 2.82842712475 1 - (3.5+1.5j) (0.5-1.5j) (3+3j) (0.666666666667-0.666666666667j) (1.43248815986+2.43884761145j) 1 - 1.5 1 1.5 (1.5+0j) - - 3.5 -0.5 3.0 0.75 2.25 -1 - 3.0 0.0 2.25 1.0 1.83711730709 0 - 3.0 0.0 2.25 1.0 1.83711730709 1 - (3+1.5j) -1.5j (2.25+2.25j) (0.5-0.5j) (1.50768393746+1.04970907623j) -1 - (3/2) 1 1.5 (1.5+0j) - - (7/2) (-1/2) 3 (3/4) (9/4) -1 - 3.0 0.0 2.25 1.0 1.83711730709 -1 - 3 0 (9/4) 1 1.83711730709 0 - (3+1.5j) -1.5j (2.25+2.25j) (0.5-0.5j) (1.50768393746+1.04970907623j) -1 - (1.5+1.5j) (1.5+1.5j) - - (3.5+1.5j) (-0.5+1.5j) (3+3j) (0.75+0.75j) 4.5j -1 - (3+1.5j) 1.5j (2.25+2.25j) (1+1j) (1.18235814075+2.85446505899j) 1 - (3+1.5j) 1.5j (2.25+2.25j) (1+1j) (1.18235814075+2.85446505899j) 1 - (3+3j) 0j 4.5j (1+0j) (-0.638110484918+0.705394566962j) 0 - ''' - print(rat(-1, 1)) - print(rat(1, -1)) - a = rat(1, 10) - print(int(a), int(a), float(a), complex(a)) - b = rat(2, 5) - l = [a+b, a-b, a*b, a/b] - print(l) - l.sort() - print(l) - print(rat(0, 1)) - print(a+1) - print(a+1) - print(a+1.0) - try: - print(rat(1, 0)) - raise SystemError('should have been ZeroDivisionError') - except ZeroDivisionError: - print('OK') - print(rat(2), rat(1.5), rat(3, 2), rat(1.5+1.5j), rat(31415926,10000000)) - list = [2, 1.5, rat(3,2), 1.5+1.5j] - for i in list: - print(i, end=' ') - if not isinstance(i, complex): - print(int(i), float(i), end=' ') - print(complex(i)) - print() - for j in list: - print(i + j, i - j, i * j, i / j, i ** j, end=' ') - if not (isinstance(i, complex) or - isinstance(j, complex)): - print(cmp(i, j)) - print() - - -if __name__ == '__main__': - test() Index: Lib/rational.py =================================================================== --- Lib/rational.py (revision 59566) +++ Lib/rational.py (working copy) @@ -1,306 +1,271 @@ -'''\ -This module implements rational numbers. +# Contributed by Sjoerd Mullender -The entry point of this module is the function - rat(numerator, denominator) -If either numerator or denominator is of an integral or rational type, -the result is a rational number, else, the result is the simplest of -the types float and complex which can hold numerator/denominator. -If denominator is omitted, it defaults to 1. -Rational numbers can be used in calculations with any other numeric -type. The result of the calculation will be rational if possible. +"""Rational, infinite-precision, real numbers.""" -There is also a test function with calling sequence - test() -The documentation string of the test function contains the expected -output. -''' +import math +import numbers +import operator -# Contributed by Sjoerd Mullender +__all__ = ["Rational"] -from types import * +RationalAbc = numbers.Rational -def gcd(a, b): - '''Calculate the Greatest Common Divisor.''' +def _gcd(a:numbers.Integral, b:numbers.Integral): + """Calculate the Greatest Common Divisor.""" while b: a, b = b, a%b return a -def rat(num, den = 1): - # must check complex before float - if isinstance(num, complex) or isinstance(den, complex): - # numerator or denominator is complex: return a complex - return complex(num) / complex(den) - if isinstance(num, float) or isinstance(den, float): - # numerator or denominator is float: return a float - return float(num) / float(den) - # otherwise return a rational - return Rat(num, den) +class Rational(RationalAbc): + """This class implements rational numbers. -class Rat: - '''This class implements rational numbers.''' + Rational(8, 6) will produce a rational number equivalent to + 4/3. Both arguments must be convertible to ints. The denominator + defaults to 1 so that Rational(3) == 3. - def __init__(self, num, den = 1): - if den == 0: - raise ZeroDivisionError('rat(x, 0)') + """ - # normalize + __slots__ = ('_numerator', '_denominator') - # must check complex before float - if (isinstance(num, complex) or - isinstance(den, complex)): - # numerator or denominator is complex: - # normalized form has denominator == 1+0j - self.__num = complex(num) / complex(den) - self.__den = complex(1) - return - if isinstance(num, float) or isinstance(den, float): - # numerator or denominator is float: - # normalized form has denominator == 1.0 - self.__num = float(num) / float(den) - self.__den = 1.0 - return - if (isinstance(num, self.__class__) or - isinstance(den, self.__class__)): - # numerator or denominator is rational - new = num / den - if not isinstance(new, self.__class__): - self.__num = new - if isinstance(new, complex): - self.__den = complex(1) - else: - self.__den = 1.0 - else: - self.__num = new.__num - self.__den = new.__den - else: - # make sure numerator and denominator don't - # have common factors - # this also makes sure that denominator > 0 - g = gcd(num, den) - self.__num = num / g - self.__den = den / g - # try making numerator and denominator of IntType if they fit - try: - numi = int(self.__num) - deni = int(self.__den) - except (OverflowError, TypeError): - pass - else: - if self.__num == numi and self.__den == deni: - self.__num = numi - self.__den = deni + def __init__(self, + numerator:numbers.Integral, + denominator:numbers.Integral=1): + if (not isinstance(numerator, numbers.Integral) or + not isinstance(denominator, numbers.Integral)): + raise TypeError("Rational(%(numerator)s, %(denominator)s):" + " Both arguments must be integral." % locals()) + if denominator == 0: + raise ZeroDivisionError('Rational(%s, 0)' % numerator) + + g = _gcd(numerator, denominator) + self._numerator = int(numerator / g) + self._denominator = int(denominator / g) + + @property + def numerator(a): + return a._numerator + + @property + def denominator(a): + return a._denominator + def __repr__(self): - return 'Rat(%s,%s)' % (self.__num, self.__den) + """repr(self)""" + return ('rational.Rational(%r,%r)' % + (self.numerator, self.denominator)) def __str__(self): - if self.__den == 1: - return str(self.__num) + """str(self)""" + if self.denominator == 1: + return str(self.numerator) else: - return '(%s/%s)' % (str(self.__num), str(self.__den)) + return '(%s/%s)' % (self.numerator, self.denominator) - # a + b - def __add__(a, b): - try: - return rat(a.__num * b.__den + b.__num * a.__den, - a.__den * b.__den) - except OverflowError: - return rat(int(a.__num) * int(b.__den) + - int(b.__num) * int(a.__den), - int(a.__den) * int(b.__den)) + def _operator_fallbacks(monomorphic_operator, fallback_operator): + """Generates forward and reverse operators given a purely-rational + operator and a function from the operator module. - def __radd__(b, a): - return Rat(a) + b + Use this like: + __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) - # a - b - def __sub__(a, b): - try: - return rat(a.__num * b.__den - b.__num * a.__den, - a.__den * b.__den) - except OverflowError: - return rat(int(a.__num) * int(b.__den) - - int(b.__num) * int(a.__den), - int(a.__den) * int(b.__den)) + """ + def forward(a, b): + if isinstance(b, RationalAbc): + return monomorphic_operator(a, b) + elif isinstance(b, float): + return fallback_operator(float(a), b) + elif isinstance(b, complex): + return fallback_operator(complex(a), b) + else: + return NotImplemented + forward.__name__ = '__' + fallback_operator.__name__ + '__' + forward.__doc__ = monomorphic_operator.__doc__ - def __rsub__(b, a): - return Rat(a) - b + def reverse(b, a): + if isinstance(a, RationalAbc): + return monomorphic_operator(a, b) + elif isinstance(a, numbers.Real): + return fallback_operator(float(a), float(b)) + elif isinstance(a, numbers.Complex): + return fallback_operator(complex(a), complex(b)) + else: + return NotImplemented + reverse.__name__ = '__r' + fallback_operator.__name__ + '__' + reverse.__doc__ = monomorphic_operator.__doc__ - # a * b - def __mul__(a, b): - try: - return rat(a.__num * b.__num, a.__den * b.__den) - except OverflowError: - return rat(int(a.__num) * int(b.__num), - int(a.__den) * int(b.__den)) + return forward, reverse - def __rmul__(b, a): - return Rat(a) * b + def _add(a:RationalAbc, b:RationalAbc): + """a + b""" + return Rational(a.numerator * b.denominator + + b.numerator * a.denominator, + a.denominator * b.denominator) - # a / b - def __div__(a, b): - try: - return rat(a.__num * b.__den, a.__den * b.__num) - except OverflowError: - return rat(int(a.__num) * int(b.__den), - int(a.__den) * int(b.__num)) + __add__, __radd__ = _operator_fallbacks(_add, operator.add) - def __rdiv__(b, a): - return Rat(a) / b + def _sub(a, b): + """a - b""" + return Rational(a.numerator * b.denominator - + b.numerator * a.denominator, + a.denominator * b.denominator) - # a % b - def __mod__(a, b): - div = a / b - try: - div = int(div) - except OverflowError: - div = int(div) + __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) + + def _mul(a, b): + """a * b""" + return Rational(a.numerator * b.numerator, a.denominator * b.denominator) + + __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) + + def _div(a:RationalAbc, b:RationalAbc): + """a / b""" + return Rational(a.numerator * b.denominator, + a.denominator * b.numerator) + + __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) + + def __floordiv__(a, b): + """a // b""" + return math.floor(a / b) + + def __rfloordiv__(b, a): + """a // b""" + return math.floor(a / b) + + @classmethod + def _mod(cls, a, b): + div = a // b return a - b * div + + def __mod__(a, b): + """a % b""" + return a._mod(a, b) def __rmod__(b, a): - return Rat(a) % b + """a % b""" + return b._mod(a, b) - # a ** b def __pow__(a, b): - if b.__den != 1: - if isinstance(a.__num, complex): - a = complex(a) + """a ** b + + If b is not an integer, the result will be a float since roots + are generally irrational. If b is an integer, the result will + be rational. + + """ + if isinstance(b, RationalAbc): + if b.denominator == 1: + power = b.numerator + if power >= 0: + return Rational(a.numerator ** power, + a.denominator ** power) + else: + return Rational(a.denominator ** -power, + a.numerator ** -power) else: - a = float(a) - if isinstance(b.__num, complex): - b = complex(b) - else: - b = float(b) - return a ** b - try: - return rat(a.__num ** b.__num, a.__den ** b.__num) - except OverflowError: - return rat(int(a.__num) ** b.__num, - int(a.__den) ** b.__num) + # A fractional power will generally produce an + # irrational number. + return float(a) ** float(b) + else: + return float(a) ** b def __rpow__(b, a): - return Rat(a) ** b + """a ** b""" + if b.denominator == 1 and b.numerator >= 0: + # If a is an int, keep it that way if possible. + return a ** b.numerator - # -a - def __neg__(a): - try: - return rat(-a.__num, a.__den) - except OverflowError: - # a.__num == sys.maxint - return rat(-int(a.__num), a.__den) + if isinstance(a, RationalAbc): + return Rational(a.numerator, a.denominator) ** b - # abs(a) - def __abs__(a): - return rat(abs(a.__num), a.__den) + if b.denominator == 1: + return a ** b.numerator - # int(a) - def __int__(a): - return int(a.__num / a.__den) + return a ** float(b) - # long(a) - def __long__(a): - return int(a.__num) / int(a.__den) + def __neg__(a): + """-a""" + return Rational(-a.numerator, a.denominator) - # float(a) - def __float__(a): - return float(a.__num) / float(a.__den) + def __abs__(a): + """abs(a)""" + return Rational(abs(a.numerator), a.denominator) - # complex(a) - def __complex__(a): - return complex(a.__num) / complex(a.__den) - - # cmp(a,b) - def __cmp__(a, b): - diff = Rat(a - b) - if diff.__num < 0: - return -1 - elif diff.__num > 0: - return 1 + def __trunc__(a): + """trunc(a)""" + if a.numerator < 0: + return -(abs(a.numerator) // a.denominator) else: - return 0 + return a.numerator // a.denominator - def __rcmp__(b, a): - return cmp(Rat(a), b) + def __floor__(a): + """math.floor(a)""" + return a.numerator // a.denominator - # a != 0 - def __bool__(a): - return a.__num != 0 + def __ceil__(a): + """math.ceil(a)""" + floor, remainder = divmod(a.numerator, a.denominator) + if remainder == 0: + return floor + else: + return floor + 1 -def test(): - '''\ - Test function for rat module. + def __round__(self, ndigits=None): + """round(self, ndigits)""" + if ndigits is None: + floor, remainder = divmod(self.numerator, self.denominator) + if remainder * 2 < self.denominator: + return floor + elif remainder * 2 > self.denominator: + return floor + 1 + # Deal with the half case: + elif floor % 2 == 0: + return floor + else: + return floor + 1 + shift = 10**abs(ndigits) + if ndigits > 0: + return Rational(round(shift * self), shift) + else: + return Rational((self // shift) * shift) - The expected output is (module some differences in floating - precission): - -1 - -1 - 0 0L 0.1 (0.1+0j) - [Rat(1,2), Rat(-3,10), Rat(1,25), Rat(1,4)] - [Rat(-3,10), Rat(1,25), Rat(1,4), Rat(1,2)] - 0 - (11/10) - (11/10) - 1.1 - OK - 2 1.5 (3/2) (1.5+1.5j) (15707963/5000000) - 2 2 2.0 (2+0j) + def __eq__(a, b): + """a == b""" + if isinstance(b, RationalAbc): + return (a.numerator == b.numerator and + a.denominator == b.denominator) + else: + return float(a) == b + + @classmethod + def _makeComparableWithZero(cls, diff): + """Helper function for comparison operators. - 4 0 4 1 4 0 - 3.5 0.5 3.0 1.33333333333 2.82842712475 1 - (7/2) (1/2) 3 (4/3) 2.82842712475 1 - (3.5+1.5j) (0.5-1.5j) (3+3j) (0.666666666667-0.666666666667j) (1.43248815986+2.43884761145j) 1 - 1.5 1 1.5 (1.5+0j) + Returns a value such that comparing with 0 won't recurse. - 3.5 -0.5 3.0 0.75 2.25 -1 - 3.0 0.0 2.25 1.0 1.83711730709 0 - 3.0 0.0 2.25 1.0 1.83711730709 1 - (3+1.5j) -1.5j (2.25+2.25j) (0.5-0.5j) (1.50768393746+1.04970907623j) -1 - (3/2) 1 1.5 (1.5+0j) + """ + if isinstance(diff, RationalAbc): + return diff.numerator + else: + return diff + + def __lt__(a, b): + """a < b""" + return a._makeComparableWithZero(a - b) < 0 - (7/2) (-1/2) 3 (3/4) (9/4) -1 - 3.0 0.0 2.25 1.0 1.83711730709 -1 - 3 0 (9/4) 1 1.83711730709 0 - (3+1.5j) -1.5j (2.25+2.25j) (0.5-0.5j) (1.50768393746+1.04970907623j) -1 - (1.5+1.5j) (1.5+1.5j) + def __gt__(a, b): + """a > b""" + return a._makeComparableWithZero(a - b) > 0 - (3.5+1.5j) (-0.5+1.5j) (3+3j) (0.75+0.75j) 4.5j -1 - (3+1.5j) 1.5j (2.25+2.25j) (1+1j) (1.18235814075+2.85446505899j) 1 - (3+1.5j) 1.5j (2.25+2.25j) (1+1j) (1.18235814075+2.85446505899j) 1 - (3+3j) 0j 4.5j (1+0j) (-0.638110484918+0.705394566962j) 0 - ''' - print(rat(-1, 1)) - print(rat(1, -1)) - a = rat(1, 10) - print(int(a), int(a), float(a), complex(a)) - b = rat(2, 5) - l = [a+b, a-b, a*b, a/b] - print(l) - l.sort() - print(l) - print(rat(0, 1)) - print(a+1) - print(a+1) - print(a+1.0) - try: - print(rat(1, 0)) - raise SystemError('should have been ZeroDivisionError') - except ZeroDivisionError: - print('OK') - print(rat(2), rat(1.5), rat(3, 2), rat(1.5+1.5j), rat(31415926,10000000)) - list = [2, 1.5, rat(3,2), 1.5+1.5j] - for i in list: - print(i, end=' ') - if not isinstance(i, complex): - print(int(i), float(i), end=' ') - print(complex(i)) - print() - for j in list: - print(i + j, i - j, i * j, i / j, i ** j, end=' ') - if not (isinstance(i, complex) or - isinstance(j, complex)): - print(cmp(i, j)) - print() + def __le__(a, b): + """a <= b""" + return a._makeComparableWithZero(a - b) <= 0 + def __ge__(a, b): + """a >= b""" + return a._makeComparableWithZero(a - b) >= 0 -if __name__ == '__main__': - test() + def __bool__(a): + """a != 0""" + return a.numerator != 0 Index: Lib/numbers.py =================================================================== --- Lib/numbers.py (revision 59590) +++ Lib/numbers.py (working copy) @@ -119,12 +119,12 @@ raise NotImplementedError @abstractmethod - def __div__(self, other): + def __truediv__(self, other): """self / other; should promote to float or complex when necessary.""" raise NotImplementedError @abstractmethod - def __rdiv__(self, other): + def __rtruediv__(self, other): """other / self""" raise NotImplementedError Index: Lib/test/test_rational.py =================================================================== --- Lib/test/test_rational.py (revision 0) +++ Lib/test/test_rational.py (revision 0) @@ -0,0 +1,156 @@ +"""Tests for Lib/rational.py.""" + +from test.test_support import run_unittest, verbose +import math +import rational +import unittest +R = rational.Rational + +class RationalTest(unittest.TestCase): + + def assertExactlyEquals(self, expected, actual): + """Asserts that both the types and values are the same.""" + self.assertEquals(type(expected), type(actual)) + self.assertEquals(expected, actual) + + def testInit(self): + def components(r): + return (r.numerator, r.denominator) + self.assertEquals((-1, 1), components(R(-1, 1))) + self.assertEquals((-1, 1), components(R(1, -1))) + self.assertEquals((1, 2), components(R(5, 10))) + self.assertEquals((7, 15), components(R(7, 15))) + + try: + R(12, 0) + self.fail("R(12, 0) failed to raise ZeroDivisionError") + except ZeroDivisionError as e: + self.assertEquals("Rational(12, 0)", str(e)) + + self.assertRaises(TypeError, R, 1.5) + self.assertRaises(TypeError, R, 1.5 + 3j) + + def testConversions(self): + self.assertExactlyEquals(-1, trunc(R(-11, 10))) + self.assertExactlyEquals(-2, math.floor(R(-11, 10))) + self.assertExactlyEquals(-1, math.ceil(R(-11, 10))) + self.assertExactlyEquals(-1, math.ceil(R(-10, 10))) + + self.assertExactlyEquals(0, round(R(-1, 10))) + self.assertExactlyEquals(0, round(R(-5, 10))) + self.assertExactlyEquals(-2, round(R(-15, 10))) + self.assertExactlyEquals(-1, round(R(-7, 10))) + + self.assertExactlyEquals(0.1, float(R(1, 10))) + self.assertExactlyEquals(0.1+0j, complex(R(1,10))) + + + def testArithmetic(self): + self.assertEquals(R(1, 2), R(1, 10) + R(2, 5)) + self.assertEquals(R(-3, 10), R(1, 10) - R(2, 5)) + self.assertEquals(R(1, 25), R(1, 10) * R(2, 5)) + self.assertEquals(R(1, 4), R(1, 10) / R(2, 5)) + + def testMixedArithmetic(self): + self.assertExactlyEquals(R(11, 10), R(1, 10) + 1) + self.assertExactlyEquals(1.1, R(1, 10) + 1.0) + self.assertExactlyEquals(1.1 + 0j, R(1, 10) + (1.0 + 0j)) + self.assertExactlyEquals(R(11, 10), 1 + R(1, 10)) + self.assertExactlyEquals(1.1, 1.0 + R(1, 10)) + self.assertExactlyEquals(1.1 + 0j, (1.0 + 0j) + R(1, 10)) + + self.assertExactlyEquals(R(-9, 10), R(1, 10) - 1) + self.assertExactlyEquals(-0.9, R(1, 10) - 1.0) + self.assertExactlyEquals(-0.9 + 0j, R(1, 10) - (1.0 + 0j)) + self.assertExactlyEquals(R(9, 10), 1 - R(1, 10)) + self.assertExactlyEquals(0.9, 1.0 - R(1, 10)) + self.assertExactlyEquals(0.9 + 0j, (1.0 + 0j) - R(1, 10)) + + self.assertExactlyEquals(R(1, 10), R(1, 10) * 1) + self.assertExactlyEquals(0.1, R(1, 10) * 1.0) + self.assertExactlyEquals(0.1 + 0j, R(1, 10) * (1.0 + 0j)) + self.assertExactlyEquals(R(1, 10), 1 * R(1, 10)) + self.assertExactlyEquals(0.1, 1.0 * R(1, 10)) + self.assertExactlyEquals(0.1 + 0j, (1.0 + 0j) * R(1, 10)) + + self.assertExactlyEquals(R(1, 10), R(1, 10) / 1) + self.assertExactlyEquals(0.1, R(1, 10) / 1.0) + self.assertExactlyEquals(0.1 + 0j, R(1, 10) / (1.0 + 0j)) + self.assertExactlyEquals(R(10, 1), 1 / R(1, 10)) + self.assertExactlyEquals(10.0, 1.0 / R(1, 10)) + self.assertExactlyEquals(10.0 + 0j, (1.0 + 0j) / R(1, 10)) + + self.assertExactlyEquals(0, R(1, 10) // 1) + self.assertExactlyEquals(0.0, R(1, 10) // 1.0) + self.assertExactlyEquals(10, 1 // R(1, 10)) + self.assertExactlyEquals(10.0, 1.0 // R(1, 10)) + + self.assertExactlyEquals(R(1, 10), R(1, 10) % 1) + self.assertExactlyEquals(0.1, R(1, 10) % 1.0) + self.assertExactlyEquals(R(0, 1), 1 % R(1, 10)) + self.assertExactlyEquals(0.0, 1.0 % R(1, 10)) + + # No need for divmod since we don't override it. + + # ** has more interesting conversion rules. + self.assertExactlyEquals(R(100, 1), R(1, 10) ** -2) + self.assertExactlyEquals(R(100, 1), R(10, 1) ** 2) + self.assertExactlyEquals(0.1, R(1, 10) ** 1.0) + self.assertExactlyEquals(0.1 + 0j, R(1, 10) ** (1.0 + 0j)) + self.assertExactlyEquals(4 , 2 ** R(2, 1)) + self.assertAlmostEquals(1j, (-1) ** R(1, 2)) + self.assertExactlyEquals(R(1, 4) , 2 ** R(-2, 1)) + self.assertExactlyEquals(2.0 , 4 ** R(1, 2)) + self.assertExactlyEquals(0.25, 2.0 ** R(-2, 1)) + self.assertExactlyEquals(1.0 + 0j, (1.0 + 0j) ** R(1, 10)) + + def testComparisons(self): + self.assertTrue(R(1, 2) < R(2, 3)) + self.assertFalse(R(1, 2) < R(1, 2)) + self.assertTrue(R(1, 2) <= R(2, 3)) + self.assertTrue(R(1, 2) <= R(1, 2)) + self.assertFalse(R(2, 3) <= R(1, 2)) + self.assertTrue(R(1, 2) == R(1, 2)) + self.assertFalse(R(1, 2) == R(1, 3)) + + def testMixedLess(self): + self.assertTrue(2 < R(5, 2)) + self.assertFalse(2 < R(4, 2)) + self.assertTrue(R(5, 2) < 3) + self.assertFalse(R(4, 2) < 2) + + self.assertTrue(R(1, 2) < 0.6) + self.assertFalse(R(1, 2) < 0.4) + self.assertTrue(0.4 < R(1, 2)) + self.assertFalse(0.5 < R(1, 2)) + + def testMixedLessEqual(self): + self.assertTrue(0.5 <= R(1, 2)) + self.assertFalse(0.6 <= R(1, 2)) + self.assertTrue(R(1, 2) <= 0.5) + self.assertFalse(R(1, 2) <= 0.4) + self.assertTrue(2 <= R(4, 2)) + self.assertFalse(2 <= R(3, 2)) + self.assertTrue(R(4, 2) <= 2) + self.assertFalse(R(5, 2) <= 2) + + def testMixedEqual(self): + self.assertTrue(0.5 == R(1, 2)) + self.assertFalse(0.6 == R(1, 2)) + self.assertTrue(R(1, 2) == 0.5) + self.assertFalse(R(1, 2) == 0.4) + self.assertTrue(2 == R(4, 2)) + self.assertFalse(2 == R(3, 2)) + self.assertTrue(R(4, 2) == 2) + self.assertFalse(R(5, 2) == 2) + + def testStringification(self): + self.assertEquals("rational.Rational(7,3)", repr(R(7, 3))) + self.assertEquals("(7/3)", str(R(7, 3))) + self.assertEquals("7", str(R(7, 1))) + +def test_main(): + run_unittest(RationalTest) + +if __name__ == '__main__': + test_main()