all Python 3Numbers & mathterm
fractions
module
Rational numbers: the Fraction class stores an exact common fraction and computes without rounding error.
Syntax
from fractions import Fraction
Use fractions when you need an exact answer as a common fraction: 1/3 + 1/6 is exactly 1/2. For money and a fixed number of decimal places decimal fits better, and for fast approximate maths there is float. A Fraction built from a float shows its true binary value, so an exact fraction is built from a string or a pair of integers.
Examples
from fractions import Fraction
print(Fraction(1, 3) + Fraction(1, 6)) # → 1/2
print(Fraction('0.1') * 3 == Fraction(3, 10)) # → True
print(Fraction(0.1)) # → 3602879701896397/36028797018963968
See also
Open in the full glossarydocs.python.orgReport an inaccuracy