Python. Please include comments where needed, explaining the code and screenshot
ID: 3801845 • Letter: P
Question
Python. Please include comments where needed, explaining the code and screenshot of output. thank you!
Suppose we want to do arithmetic with rational numbers. We want to be able to add, subtract,
multiply, and divide them and to test whether two rational numbers are equal.
We can add, subtract, multiply, divide, and test equality by using the following relations:
n1/d1 + n2/d2 = (n1*d2 + n2*d1)/(d1*d2)
n1/d1-n2/d2 = (n1*d2-n2*d1)/(d1*d2)
n1/d1 * n2/d2 = (n1*n2)/(d1*d2)
(n1/d1) / (n2/d2) = (n1*d2)/(d1*n2)
n1/d1 == n2/d2 if and only if n1*d2 == n2*d1
Define
a rational number class
with support for arithmetic operations (subtract, multiply, divide, and test equalitymethods) as follows:
class
RationalNumber:
"""
Rational Numbers with support for
arithmetic
operations.
"""
### your code
here
####
Explanation / Answer
//================================= rational.py ================================//
def gcd ( a, b ):
if b == 0:
return a
else:
return gcd(b, a%b)
"""
Rational Numbers with support for
arithmetic
operations.
"""
class RationalNumber:
def __init__ ( self, a, b ):
if b == 0:
raise ZeroDivisionError, ( "Denominator of a RationalNumber "
"may not be zero." )
else:
g = gcd ( a, b )
self.n = a / g
self.d = b / g
def __add__ ( self, other ):
return RationalNumber ( self.n * other.d + other.n * self.d,
self.d * other.d )
def __sub__ ( self, other ):
return RationalNumber ( self.n * other.d - other.n * self.d,
self.d * other.d )
def __mul__ ( self, other ):
return RationalNumber ( self.n * other.n, self.d * other.d )
def __div__ ( self, other ):
return RationalNumber ( self.n * other.d, self.d * other.n )
def __str__ ( self ):
return "%d/%d" % ( self.n, self.d )
def __float__ ( self ):
return float ( self.n ) / float ( self.d )
def main():
r1 = RationalNumber(3,2)
r2 = RationalNumber(1,2)
print "r1="+str(r1)
print "r2="+str(r2)
r3 = r1+r2
print "r1+r2 = "+str(r3)
r4 = r1-r2
print "r1-r2 = "+str(r4)
r5 = r1*r2
print "r1*r2 = "+str(r5)
r6 = r1/r2
print "r1/r2 = "+str(r6)
main()
==================================================================
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.