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

ExampleEdit & Run
import fractions 

values = [(1, 3), (2, 4), (2, 7)]

for n, d in values:
    f = fractions.Fraction(n, d)
    print(f)
Output:
1/31/22/7[Finished in 0.01892657997086644s]

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.

ExampleEdit & Run
#Import the fractions module
import fractions 

values = ["1/2", "0.3", "0.4"]

for v in values:
    f = fractions.Fraction(v)
    print(f)
Output:
1/23/102/5[Finished in 0.019024744862690568s]

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.

ExampleEdit & Run
import fractions 

values = [0.5, 1.0, 1.5]

for v in values:
    f = fractions.Fraction.from_float(v)
    print(f)
Output:
1/213/2[Finished in 0.017822918016463518s]

Arithmetic operations on Fractions 

Once fractions have been instantiated, they can be used in relevant mathematical expressions.

ExampleEdit & Run
import fractions

f1 = fractions.Fraction(3, 4)
f2 = fractions.Fraction(1, 2)


print("%s + %s = %s"%(f1, f2, f1 + f2))
print("%s - %s = %s"%(f1, f2, f1 - f2))
print("%s x %s = %s"%(f1, f2, f1 * f2))
print("%s / %s = %s"%(f1, f2, f1 / f2))
Output:
3/4 + 1/2 = 5/43/4 - 1/2 = 1/43/4 x 1/2 = 3/83/4 / 1/2 = 3/2[Finished in 0.01904331799596548s]

Approximating values

The Fraction class can be used for estimating a value up to a  certain degree of precision. This is achieved by limiting the size of the denominator.

ExampleEdit & Run
import fractions
import math

PI = math.pi

f = fractions.Fraction(str(PI))
print("no limit: %s"%f)

for i in [ 1, 6, 11, 60, 70, 90, 100 ]:

    limited = f.limit_denominator(i)
    print("%s"%(limited))
Output:
no limit: 3141592653589793/1000000000000000319/622/7179/57201/64267/85311/99[Finished in 0.019179330905899405s]

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.