Rationalise (Canonise) the Fractions before Subtraction
Normally before fractions are subtracted, they are rationalised;
i.e., they are put in a form where their denominators become
the same. This same denominator is the LCM of the
denominators of all the separate fractions.
After this is done, the new numerators can then be subtracted.
Steps for Subtraction of Fractions Python code
The following steps will guide us in writing our code.
Let's illustrate with
7/4 - 2/5
Step 1:
Find the LCM of the denominators.
⇒ LCM of 4 & 5 = 20
Step 2:
In a turn by turn fashion, divide the found LCM from Step 1
by each denominator, multiplying the quotient by the corresponding numerator.
⇒
((7 x 5) - (2 x 4))/20
= (35 - 8)/20
Step 3:
Go ahead and subtract the numerators.
⇒
27/20
Create a new module file;
call it SubtractFraction.py
Type out the adjoining Python code for subtracting fractions.
Note: You can comment out the AddFraction Python object
code in the main class from the previous lesson or simply continue from where it stopped.
So!
Feel free to try out your own set of numerators and denominators for fractional subtraction.
Python code for SubtractFraction Module File
from AddFraction import PlusFraction
class MinusFraction(PlusFraction):
def __init__(self, fractions):
super().__init__(fractions)
def doSubtract(self):
self.canoniseFraction()
self.answer = self.new_numerators[0]
for count in range(1, len(self.new_numerators)): self.answer -= self.new_numerators[count]
return {'numerator':self.answer, 'denominator':self.lcm}
Main class
from SubtractFraction import MinusFraction
numerators = [9, 3, 5, 7]
denominators = [2, 4, 12, 18]
fractions = {'numerators':numerators, 'denominators':denominators}
print('\n Solving:\n')
for numerator in fractions['numerators']: print('{:13d}'.format(numerator), end='')
print('{}{:>12}'.format('\n', ' '), end='')
for wasted in range(len(numerators)-1): print('{}'.format('- + '), end='')
print('{:>1}'.format('-'))
for denominator in fractions['denominators']: print('{:13d}'.format(denominator), end='')
print('\n\n')
sub_fract = MinusFraction(fractions)
fraction = sub_fract.doSubtract()
print('{:25d}'.format(fraction['numerator']))
print('{:>25}'.format('Answer = -'))
print('{:25d}'.format(fraction['denominator']))
print('\n\n')