An instance of the Rational class represents
a rational number. Mathematically:
A rational number is the ratio of two integers, the numerator and the denominator. The denominator cannot be zero.
In grade-school terms, a rational number is a fraction. Examples: 1/2; 113/355; 0/1 (which has the value zero).
In Python, you will need to import the rational module. Within this module, there is a
class constructor that is invoked
like this:
Rational(n,d)
where is the
numerator and nd is the denominator.
This constructor returns an instance of the class, that is, an object that represents that specific rational value. Here is a conversational example:
>>> from rational import * >>> half = Rational ( 1, 2 ) >>> print half 1/2 >>> twoSevenths = Rational ( 2, 7 ) >>> print twoSevenths * half 1/7
The above example shows that (1/2)*(2/7) equals 1/7.
The constructor will reduce values to their lowest terms:
>>> print Rational ( 50, 100 ) 1/2 >>> print Rational ( 113, 355 ) 113/355 >>> print Rational ( 2000, 12000 ) 1/6
Operations allowed on Rational instances
include:
r + s
Sum of two rationals and r.
s
r - s
Difference of and r.
s
r * s
Product of and r.
s
r / s
Quotient of divided by rs.
float(r)
Returns the float value closest to the
value of .
r
str(r)
Return a representation of as a string of type rstr.
R.mixed()
For a Rational instance , returns the
value as a mixed fraction in string form. Examples:
R"17", "1/10", "3
and 1/7".
More examples:
>>> third=Rational(1,3) >>> fifth=Rational(1,5) >>> print third * fifth 1/15 >>> print third + fifth 8/15 >>> print third-fifth 2/15 >>> print fifth/third 3/5 >>> print str(fifth) 1/5 >>> print float(fifth) 0.2 >>> print float(third) 0.333333333333
The module also provides one ordinary method named mixed that returns a string representing an
instance as a mixed fraction. Example:
>>> badPi = Rational(22,7) >>> print badPi.mixed() 3 and 1/7 >>> properFraction = Rational(3,5) >>> print properFraction.mixed() 3/5 >>> wholeNum = Rational(8,2) >>> print wholeNum 4/1 >>> print wholeNum.mixed() 4 >>> zero = Rational ( 0, 12345 ) >>> print zero.mixed() 0