Python

Python fractions — Fraction, exact ratios, and limit_denominator

A third plus a sixth is a half, but neither third has an exact float form, so ratio work in floats carries small errors from the first step. The fractions module holds a value as a pair of integers, a numerator over a denominator, reduces the pair to its lowest terms, and keeps every sum, product, and quotient exact. This guide takes construction first, then arithmetic, the parts of a fraction, comparison, the limit_denominator method for finding a simple ratio near a float, and the error cases.

Written November 13, 2026 · Tested with Python 3.12.3 · 9 min read

By the end of this guide
  • The main program: float against Fraction
  • Construction: integers, strings, Decimal, and float
  • Arithmetic: the four operations, a whole number, and powers
  • The parts: numerator, denominator, sign, and whole values

Written November 13, 2026

Tested with Python 3.12.3

What this guide is

The fractions module gives a number type, Fraction, that stores a rational value as two integers. Rational means the value can be stated as one integer divided by another: a half, three quarters, seven thirds. A float stores such a value in base 2, and a fraction such as one third has no exact base 2 form, so the float is a near miss from the start. A Fraction keeps the pair itself. One third plus one sixth is computed on the pairs and comes back as exactly one half, reduced to its lowest terms without being asked. Code that works in ratios, rates stated as counts over counts, recipe quantities, or odds uses this module when the exact ratio matters more than a decimal display.

The main program: float against Fraction

The first line runs the sum in floats, where it happens to print cleanly. The next lines run the same sum on Fraction values, compare the result with one half, and then show two reductions: two quarters become a half, and six thirds become the whole number two:

Python
print(1/3 + 1/6)
from fractions import Fraction
print(Fraction(1, 3) + Fraction(1, 6))
print(Fraction(1, 3) + Fraction(1, 6) == Fraction(1, 2))
print(Fraction(2, 4))
print(Fraction(6, 3))

The exact output:

Output
0.5
1/2
True
1/2
2

Reduction is part of construction, not a separate step. Every Fraction is stored in its lowest terms, so two values that state the same ratio are the same value, and the equality test on the third printed line holds for that reason. A result that divides evenly prints as a whole number, with no denominator shown.

Construction: integers, strings, Decimal, and float

A Fraction can be built from a single integer, from a string that states a fraction or a decimal, from a Decimal, and from a float. The string and Decimal forms state the value the writer meant. The float form converts the float exactly, and exact conversion of a value such as 0.1 produces a very large pair. The limit_denominator call then finds the simple fraction that float was near:

Python
from fractions import Fraction
from decimal import Decimal
print(Fraction(3))
print(Fraction("3/4"))
print(Fraction("1.25"))
print(Fraction(Decimal("0.75")))
print(Fraction(0.5))
print(Fraction(0.1))
print(Fraction(0.1).limit_denominator())

The exact output:

Output
3
3/4
5/4
3/4
1/2
3602879701896397/36028797018963968
1/10

Half is the friendly case: 0.5 has an exact base 2 form, so its pair is small. One tenth has no such form, and the large pair on the sixth line is the float itself, stated in full. Building from a float is sound when the float is the input and its exact value is what the job needs. When the writer means one tenth, the string form states it directly, and the pair stays small.

Arithmetic: the four operations, a whole number, and powers

The four operations run on the pairs and return reduced Fraction results. A whole number can join the operation, and the result stays a Fraction. A power with a negative exponent returns the reciprocal:

Python
from fractions import Fraction
a = Fraction(2, 3)
b = Fraction(3, 4)
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a + 1)
print(a ** 2)
print(a ** -1)

The exact output:

Output
17/12
-1/12
1/2
8/9
5/3
4/9
3/2

Read the division line by its parts: two thirds divided by three quarters is two thirds times four thirds, which is eight ninths. No step in this program rounds. A chain of these operations stays exact for as long as the work stays in Fraction values and integers, which is the point of the type: the rounding decision, if the job needs one, is made once at the end, on a result that is still exact.

The parts: numerator, denominator, sign, and whole values

The two parts of a stored value are read as numerator and denominator. The stored pair is reduced and the denominator is kept positive, so the sign of a negative value sits on the numerator. A value above one stays as an improper fraction until the program converts it. The float conversion gives the near decimal form, and the math floor and ceiling functions return the whole numbers on either side:

Python
from fractions import Fraction
f = Fraction(-6, 8)
print(f)
print(f.numerator)
print(f.denominator)
print(Fraction(7, 3))
print(float(Fraction(7, 3)))
print(Fraction(7, 3) > 2)
import math
print(math.floor(Fraction(7, 3)))
print(math.ceil(Fraction(7, 3)))

The exact output:

Output
-3/4
-3
4
7/3
2.3333333333333335
True
2
3

Negative six eighths prints as -3/4: the pair was divided by two, and the minus sign moved to the numerator, leaving a denominator of 4. A program that splits a value into a whole part and a remaining fraction reads these two fields and the floor together, and a program that prints a value for a person often converts to float at that last step only.

Comparison: equality, order, sorting, and mixing types

Fractions compare by value against other fractions, integers, and floats. Two pairs that reduce to the same value test equal, and a fraction tests equal to a float that states the same value, with the same hash. Adding a float returns a float, which is the one place in this guide where exact work steps back into float work:

Python
from fractions import Fraction
print(Fraction(1, 2) == 0.5)
print(Fraction(1, 2) == Fraction(2, 4))
print(Fraction(1, 3) < Fraction(1, 2))
print([str(x) for x in sorted([Fraction(3, 4), Fraction(1, 3), Fraction(1, 2)])])
print(hash(Fraction(1, 2)) == hash(0.5))
print(Fraction(1, 2) + 0.5)

The exact output:

Output
True
True
True
['1/3', '1/2', '3/4']
True
1.0

The sorting line converts each value to a string for display; the sort itself runs on the fractions, by value. The last line states the mixing rule in one result: a Fraction plus a float gives a float. That rule is safe for a display sum and lossy for a ratio chain, so code that needs the exact result keeps its other operand as a Fraction, an integer, a string, or a Decimal.

limit_denominator: the simple ratio near a float

Some inputs arrive as floats and the job needs a simple ratio near them, not their exact pair. The limit_denominator method returns the closest fraction whose denominator is no larger than the stated limit. Applied to the float form of pi, a limit of 10 gives the school value 22/7, a limit of 100 gives 311/99, and a limit of 1000 gives 355/113, a ratio close enough that its difference from pi is under three ten-millionths:

Python
from fractions import Fraction
import math
print(Fraction(math.pi))
print(Fraction(math.pi).limit_denominator(10))
print(Fraction(math.pi).limit_denominator(100))
print(Fraction(math.pi).limit_denominator(1000))
print(Fraction("355/113"))
print(abs(math.pi - 355/113) < 0.0000003)

The exact output:

Output
884279719003555/281474976710656
22/7
311/99
355/113
355/113
True

The limit is a trade the caller states. A smaller limit gives a simpler ratio and a larger error; a larger limit gives a closer ratio with bigger parts. Gear ratios, scale factors, and display ratios are the usual jobs: the mechanism or the page states how large a denominator it can use, and this method returns the best ratio inside that bound.

Errors, and a scaled quantity

Two error cases close the guide. A zero denominator raises ZeroDivisionError at construction. A string that states no number raises ValueError. Below them, a quantity stated as three quarters is scaled by five halves, the shape a recipe or a mix ratio takes when a batch size changes:

Python
from fractions import Fraction
try:
    Fraction(1, 0)
except ZeroDivisionError as e:
    print(type(e).__name__)
try:
    Fraction("abc")
except ValueError as e:
    print(type(e).__name__)
servings = Fraction(3, 4)
scaled = servings * Fraction(5, 2)
print(scaled)
print(float(scaled))

The exact output:

Output
ZeroDivisionError
ValueError
15/8
1.875

The scaled result, fifteen eighths, is exact. Its float form, 1.875, is the form a person reads. Keeping the work in fractions until that last conversion means a quantity scaled twice, or scaled and then split, carries no error from an early conversion. Input read from a file or a form can be built inside a try block and reported as bad input by the error name, as the two cases above show.

Which choice for which job

Job Choice Why
State a ratio Fraction from two integers Pair stays exact
Read a written ratio Fraction from string States value as written
Money in decimal places Decimal, not Fraction Places are the unit
Simple ratio near a float limit_denominator Best ratio in bound
Display a result float at last step Form a person reads
Whole part of a value math.floor Lower whole number
Compare across types Direct comparison Tests run by value
Scale a quantity Multiply Fractions No rounding mid-chain

Checklist

  • Build a Fraction from two integers or a string when the ratio is the value; build from a float only when the float itself is the input.
  • Let reduction happen at construction; never store a pair by hand to state a value.
  • Keep a chain of ratio work in Fraction and integer operands; a float operand returns a float.
  • Use limit_denominator with the bound the job states when a simple ratio near a float is needed.
  • Convert to float at the display step, not before later work has run.
  • Catch ZeroDivisionError and ValueError where Fraction values are built from outside input.

Sources

  • Python Standard Library, fractions — Fraction construction from integers, strings, floats, and Decimal values, reduction to lowest terms, the numerator and denominator fields, arithmetic and comparison rules, and limit_denominator.
  • Python Standard Library, math — the floor and ceiling functions and the pi constant used in the limit_denominator section.

Keep Exploring