Question: Problem 5. (Rational Number) Define a data type rational in rational.py that represents a rational number, ie, a number of the form a/b where a



Problem 5. (Rational Number) Define a data type rational in rational.py that represents a rational number, ie, a number of the form a/b where a and b 0 are integers. The data type must support the following API method Rational (x, y) r + S rS rS abs (r) str (r) description a new rational r from the numerator x and denominator y sum of r and s difference of r and s product of r and s absolute value of r the string representation of r as 'x/y Use the private function -gcd) to ensure that the numerator and denominator never have any common factors. For example, the rational number 2/4 must be represented as 1/:2 $ python3 rational py 100 3.13159290356 import stdio import sys # Returns the GCD of p and q, computed using Euclid's algorithm. def _gcd(p, q): return p if q-0 else-gcd(q, p % q) class Rational: Represents a rational number. def -init--(self, x, y-1): Constructs a new rational given its numerator and denominator. d gcd(x, y) self._x - self .-y = . . . def add (self, other): Returns the sum of self and other. def sub(self, other): Returns the difference of self and other. II 101 def mul (self, other): Returns the product of self and other. def _abs__(self): Return the absolute value of self. II I0 def-str--(self): Returns a string representation of self. ifa== 0 or b== 1: return str(a) a*=-1 b*=-1 str(a) ' return + + str(b) # Test client [DO NOT EDIT]. Reads an integer n as command-line argument and # writes the value of PI computed using Leibniz series: # PI/4 = 1-1/3 + 1/5-1/7 + + (-1)^n/ (2n-1). def _main): n = int (sys.,ara.[1]) total = Rational(0) sign = Rational(1) for i in range(1, n + 1): total += sign * Rational(1, 2 * 1-1) sign *= Rational(-1) stdig.writeln(4.0 * total._x / total._y) 1f _name main -main()
Step by Step Solution
There are 3 Steps involved in it
To define a Rational data type in rationalpy that supports arithmetic operations and other functionalities like the string representation and absolute ... View full answer
Get step-by-step solutions from verified subject matter experts
