all Python 3Numbers & mathterm
fractions.Fraction
fractions
Represents rational numbers exactly, as a pair of integers (numerator and denominator). Without float error.
Syntax
from fractions import Fraction
Fraction(1, 3)
Fraction(0.1) faithfully takes the binary approximation of the float and turns into the monster 3602879701896397/36028797018963968 — from decimal text, build it as Fraction('0.1') or from a pair of integers. A Fraction is immutable and is reduced to lowest terms at construction, but mixing it with a float in arithmetic yields a float and throws the exactness away; after long chains of additions the denominators blow up, and limit_denominator() is what brings the value back to a readable approximation.
Examples
from fractions import Fraction
Fraction(1, 3) + Fraction(1, 6) # → Fraction(1, 2)
Fraction('0.1') + Fraction('0.2') # → Fraction(3, 10)
Fraction(1, 3) * 3 # → Fraction(1, 1)
Fraction(22, 7) # → Fraction(22, 7)
float(Fraction(1, 3)) # → 0.3333333333333333
See also
Open in the full glossarydocs.python.orgReport an inaccuracy