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

import fractions 

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

for n, d in values:
    f = fractions.Fraction(n, d)

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.

#Import the fractions module
import fractions 

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

for v in values:
    f = fractions.Fraction(v)

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.

import fractions 

values = [0.5, 1.0, 1.5]

for v in values:
    f = fractions.Fraction.from_float(v)

Arithmetic operations on Fractions 

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

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))

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.

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)

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.