Today we’ll be talking about fractions. Sometimes decimal fractions are not exactly what you want. You may want to operate on fractions like 1/3 or 3/4 for example. If this is the case, you can easily do it in Python using the Fraction type from the fractions module.
We’ll make use of the fractions module, so let’s import it now:
from fractions import *
As I just mentioned, we use the Fraction type from the fractions module to create fractions.
Let’s say we want to create the fraction ¾. We can do it in a couple of ways using the Fraction method:
>>> Fraction(3, 4) # we can pass the numerator and denominator
Fraction(3, 4)
>>> Fraction(0.75) # we can pass the decimal value
Fraction(3, 4)
>>> Fraction('3/4') # we can pass a string
Fraction(3, 4)
We can also use the built-in float method as_integer_ratio, which returns a tuple. Then we have to add an asterisk which expands the tuple into its individual elements:
>>> Fraction(*(0.75).as_integer_ratio())
Fraction(3, 4)
The default value of the denominator is 1, so:
>>> Fraction(4) == Fraction(4, 1)
True
The default value of the numerator is 0, so:
>>> Fraction() == Fraction(0, 1) == Fraction(0, 3) == 0
True
You can use fractions in arithmetic operations:
>>> Fraction(3, 5) + Fraction(1, 5) # 3/5 + 1/5
Fraction(4, 5)
>>> Fraction(2, 7) * Fraction(7, 2) # 2/7 * 7/2
Fraction(1, 1)
>>> 49 ** Fraction(1, 2) # 49 ** (1/2)
7.0
>>> a = Fraction(2, 3)
>>> b = Fraction(5, 6)
>>> a + b, a - b, a * b, a / b, a // b
(Fraction(3, 2), Fraction(-1, 6), Fraction(5, 9), Fraction(4, 5), 0)
We can also pass a fraction as a numerator or denominator:
>>> Fraction(Fraction(3, 5), 2) # same as (3/5) / 2
Fraction(3, 10)
>>> Fraction(5, Fraction(1, 5)) # same as 5 / (1/5)
Fraction(25, 1)
>>> Fraction(Fraction(2, 3), Fraction(8, 5)) # same as (2/3) / (8/5)
Fraction(5, 12)
If either the numerator or the denominator is a negative number, in the resulting fraction the numerator is negative:
>>> Fraction(-1, 5)
Fraction(-1, 5)
>>> Fraction(1, -5)
Fraction(-1, 5)
It’s also possible to use scientific notation in a string passed as the argument:
>>> Fraction('-5e3') # same as -5 * 10 ** 3
Fraction(-5000, 1)
>>> Fraction('3e-2') # same as 3 * 10 ** (-2)
Fraction(3, 100)
We can use the limit_denominator method to obtain the closest fractional representation of a given float number where the denominator is not greater than the max_denominator passed as an argument to the function:
# the denominator can be no more than 5, so 3/2 is the closest to 1.54657
>>> Fraction(1.54657).limit_denominator(5)
Fraction(3, 2)
# the denominator can be no more than 10, so 14/9 is the closest to 1.54657
>>> Fraction(1.54657).limit_denominator(10)
Fraction(14, 9)
# the denominator can be no more than 100000, so 154657/100000 is the closest to 1.54657, actually this is the exact same thing
>>> Fraction(1.54657).limit_denominator(100000)
Fraction(154657, 100000)
Feel free to explore the fractions module even further.
Here’s the video version: