Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #An auxiliary helper function for constructor method of Rational Class
- def gcd(a, b):
- n1 = abs(a)
- n2 = abs(b)
- gcd = 1
- for k in range(2, min(n1,n2)+1):
- if (n1 % k == 0) and (n2 % k == 0):
- gcd = k
- return gcd
- class Rational:
- def __init__(self, a = 0, b = 1):
- if b <= 0:
- raise ValueError ("Denom may not be zero or less!")
- else:
- g = gcd(a, b)
- self.n = int(a / g)
- self.d = int(b / g)
- # Add a rational number to this rational number r2
- def __add__(self, r2):
- a = self.n * r2.d + self.d * r2.n
- b = self.d * r2.d
- return Rational(a, b)
- # Subtract a rational number from this rational number r2
- def __sub__(self, r2):
- a = self.n * r2.d - self.d * r2.n
- b = self.d * r2.d
- return Rational(a, b)
- def __eq__(self,r2):
- if self.n * r2.d == self.d * r2.n:
- return True
- else:
- return False
- def __str__ ( self ):
- return str(self.n) + "/" + str(self.d)
- #Client Usage
- #Application to overcoming roundoff errors
- print("Testing evaluation to 0:")
- x= 1. - 1. / 3 - 2. / 3
- print(x)
- if x == 0:
- print("Test Passed")
- else:
- print ("Test Failed")
- one = Rational(1,1)
- third = Rational(1,3)
- twothirds = Rational(2,3)
- print(str(one) + " - " + str(third) + " - " + str(twothirds) + " = " )
- x= one - third - twothirds
- print(x)
- if x == Rational(0):
- print("Test Passed")
- else:
- print ("Test Failed")
Advertisement
Add Comment
Please, Sign In to add comment