The actual code of the
rational.py module is displayed
here, with commentary. This document is therefore an
example of lightweight literate programming; see the
author's page on The Cleanroom software development methodology for more information about the tools
and techniques used in this document.
rational.py file starts with a module documentation
string that describes the class interface. This is
basically a restatement of the interface as described
above, using Cleanroom intended functions to document
each attribute and method. For more information, see
The Cleanroom software development methodology.
'''rational.py: Module to do rational arithmetic. For full documentation, see http://www.nmt.edu/~shipman/soft/rational/.
To simplify fractions (for example, reducing 4/8 to 1/2), we will need a function to find the greatest common divisor of two numbers.
Exports: gcd ( a, b ): [ a and b are integers -> return the greatest common divisor of a and b ]
Here is the class constructor.
Rational ( a, b ): [ (a is a nonnegative integer) and (b is a positive integer) -> return a new Rational instance with numerator a and denominator b ]
We make the numerator and denominator values available
outside the class as visible attributes named
.n: [ the numerator ] .d: [ the denominator ]
We implement all four of the common mathematical
/. These operations are
implemented by defining methods that use certain special
names, such as
__add__ for addition.
.__add__(self, other): [ other is a Rational instance -> return the sum of self and other as a Rational instance ] .__sub__(self, other): [ other is a Rational instance -> return the difference of self and other as a Rational instance ] .__mul__(self, other): [ other is a Rational instance -> return the product of self and other as a Rational instance ] .__div__(self, other): [ other is a Rational instance -> return the quotient of self and other as a Rational instance ]
The built-in Python functions
float() are also implemented using special
.__str__(self): [ return a string representation of self ] .__float__(self): [ return a float approximation of self ]
.mixed() method that converts
an instance to a string displaying the fraction as a
.mixed(self): [ return a string representation of self as a mixed fraction ] '''