######################################################## # File rational.py # # Module for doing extended rational arithmetic: # includes infinity. # # Examples: # Define 5/12 as a = Rational(5,12), # define 7/3 as b = Rataional(7/3). # Then can form a + b, a - b, a*b, a/b. # Zero is Rational(0,1), Infinity is Rational(1,0). # # More work needs to be done to properly handle # cases where the result is undefined as opposed # to infinite. Should set Rational(0,0) as undefined. # Is it worth it? Should we have just plain infinity, # or plus and minus infnity? # ######################################################## def gcd(a,b): a, b = abs(a), abs(b) r = a % b while r > 0: a, b, r = b, r, b % r return( b ) class Rational: def __init__ (self, num, den=1): # Example a = Rational(5/12) to construct 5/12 # Because of default argument, Rational(5) constructs 5. self.num = num self.den = den self.simplify() def simplify( self ): # remove common factors of numerator and denominator # Note that this method is called at construction, # and hence also whenever an operation is performed # (*,0) --> (1,0) if * != 0 # (0,*) --> (0,1) if * != 0 if self.num == 0: if self.den != 0: self.den = 1 elif self.den == 0: if self.num != 0: self.num = 1 else: g = gcd(self.num,self.den) self.num = self.num/g self.den = self.den/g def display (self): print self.num, "/", self.den def string(self): return `self.num`+"/"+`self.den` def isZero( self ): if self.num == 0 and self.den != 0: return 1 else: return 0 def isInfinity( self ): if self.num != 0 and self.den == 0: return 1 else: return 0 def __add__ (self, other): if self.den != 0 and other.den != 0: n = self.num*other.den + self.den*other.num d = self.den*other.den else: n, d = 1, 0 return Rational(n,d) def __sub__ (self, other): if self.den != 0 and other.den != 0: n = self.num*other.den - self.den*other.num d = self.den*other.den else: n,d = 1,0 return Rational(n,d) def __mul__ (self, other): if self.den != 0 and other.den != 0: n = self.num*other.num d = self.den*other.den else: n, d = 1, 0 return Rational(n,d) def __div__ (self, other): if other.den == 0 and other.num != 0: # self is finite, other is infinite return Rational(0,1) # return zero else: n = self.num*other.den d = self.den*other.num return Rational(n,d) Infinity = Rational(1,0) Zero = Rational(0,1) One = Rational(1,1) def ratequal(A,B): if A.den*B.num - A.num*B.den == 0: return 1 else: return 0 def negative(A): if A.num < 0 and B.den > 0: return 1 elif A.den < 0 and B.num > 0: return 1 else: return 0