Before you keep reading...
Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.
Before you keep reading...
Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.
18.4. Arithmetic Methods¶
We will conclude this chapter by adding a few more methods to our
Fraction class. In particular, we will implement
arithmetic. To begin, consider what it means to add two fractions together.
Remember that you can only add fractions if they have the same denominator. The easiest way to find a common denominator is
to multiply the two individual denominators together. Anything we do to the denominator needs to the done to the numerator. This gives us the following equation for fraction addition:
a/b + c/d = (ad + cb)/bd
add method will take a
Fraction as a parameter. It will return a new
Fraction representing the sum. We
will use the equation shown above to compute the new numerator and the new denominator. Since this equation will not
give us lowest terms, we will utilize a similar technique as was used in the
simplify method to find the
greatest common divisor and then divide each part of the new fraction.
def add(self,otherfraction): newnum = self.num*otherfraction.den + self.den*otherfraction.num newden = self.den * otherfraction.den common = gcd(newnum,newden) return Fraction(newnum//common,newden//common)
You can try the addition method and then modify the fractions and retry.
One final modification to this method will be quite useful. Instead invoking the
add method, we can use the
addition operator “+”. This requires that we implement another special method, this time called
The details of the method are the same.
def __add__(self, otherfraction): newnum = self.num*otherfraction.den + self.den*otherfraction.num newden = self.den * otherfraction.den common = gcd(newnum, newden) return Fraction(newnum // common, newden // common)
However, now we can perform addition in the same manner that we are used to with other numeric data.
f1 = Fraction(1, 2) f2 = Fraction(1, 4) f3 = f1 + f2 # calls the __add__ method of f1 print(f3)
This workspace is provided for your convenience. You can use this activecode window to try out anything you like.