The fractions
module in the standard library provides support for rational number arithmetic. A rational number is any number that can be expressed as the ratio of two integers, where the numerator and denominator are both nonzero for example 1/4
, 7/3
, etc.
The fractions
module provides the Fraction
class for representing rational numbers more intuitively.
Instantiating fractions
In the above example we have created Fraction instances from two integers i.e Fraction(numerator, denominator)
. We can also create fractions from strings , as shown below.
When we give the value as a string as in "1/2"
, the string is parsed to find the numerator and denominator values. While when we use the floating point notation as in "0.3"
, the numerator and the denominator parts of the fraction are computed automatically.
Lastly, we can use float type to create fractions by using the from_float()
method of the Fraction
class. Similarly, the numerator and the denominator are computed automatically.
Arithmetic operations on Fractions
Once fractions have been instantiated, they can be used in relevant mathematical expressions.
Approximating values
The Fraction c
lass can be used for estimating a value up to a certain degree of precision. This is achieved by limiting the size of the denominator.
The above example computes and prints various approximations of the value of pi
as fractions, based on different denominator limits. The for loop iterates through the list of denominator limits, and for each limit, finds the closest fraction approximation of pi
with a denominator that is lower or equal to the limit.