proffreda

Rational Class in Python

Mar 8th, 2016
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.56 KB | None | 0 0
  1. #An auxiliary helper function for constructor method of Rational Class
  2. def gcd(a, b):
  3.     n1 = abs(a)
  4.     n2 = abs(b)
  5.     gcd = 1
  6.     for k in range(2, min(n1,n2)+1):
  7.         if (n1 % k == 0) and (n2 % k == 0):
  8.             gcd = k
  9.     return gcd
  10.  
  11.  
  12. class Rational:
  13.     def __init__(self, a = 0, b = 1):
  14.         if  b <= 0:
  15.             raise ValueError ("Denom may not be zero or less!")
  16.         else:
  17.             g  =  gcd(a, b)
  18.             self.n  =  int(a / g)
  19.             self.d  =  int(b / g)
  20.  
  21. # Add a rational number to this rational number r2
  22.     def __add__(self, r2):
  23.         a = self.n * r2.d +  self.d * r2.n
  24.         b = self.d * r2.d
  25.         return Rational(a, b)
  26.  
  27. # Subtract a rational number from this rational number r2
  28.     def __sub__(self, r2):
  29.         a = self.n * r2.d - self.d * r2.n
  30.         b = self.d * r2.d
  31.         return Rational(a, b)
  32.  
  33.     def __eq__(self,r2):
  34.         if self.n *  r2.d ==  self.d * r2.n:
  35.             return True
  36.         else:
  37.             return False
  38.            
  39.     def __str__ ( self ):
  40.         return  str(self.n) + "/" + str(self.d)
  41.  
  42.  
  43. #Client Usage
  44. #Application to overcoming roundoff errors
  45. print("Testing evaluation to 0:")
  46. x= 1. - 1. / 3 - 2. / 3
  47. print(x)
  48. if x == 0:
  49.     print("Test Passed")
  50. else:
  51.     print ("Test Failed")
  52.  
  53. one = Rational(1,1)
  54. third = Rational(1,3)
  55. twothirds = Rational(2,3)
  56. print(str(one) + " - " + str(third) + " - " + str(twothirds) + " = " )
  57. x= one - third - twothirds
  58. print(x)
  59. if x == Rational(0):
  60.     print("Test Passed")
  61. else:
  62.     print ("Test Failed")
Advertisement
Add Comment
Please, Sign In to add comment