fractions
The fractions module provides the Fraction class for representing rational numbers exactly. Unlike floating-point numbers, Fraction objects represent numbers like 1/3 without any rounding error. This makes the module essential for financial calculations, precise measurements, and any scenario where decimal accuracy matters.
Syntax
from fractions import Fraction
# Create a fraction
Fraction(numerator=0, denominator=1)
Fraction(string) # e.g., "3/7"
Fraction(float)
Fraction(decimal)
The Fraction Class
The Fraction class is the primary entry point. It can be constructed from integers, strings, floats, decimals, or another Fraction.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
numerator | int | 0 | The top number in the fraction |
denominator | int | 1 | The bottom number (must not be zero) |
Constructing from different types
from fractions import Fraction
# From integers
half = Fraction(1, 2)
print(half)
# 1/2
# From a float (exact representation)
point_one = Fraction(0.1)
print(point_one)
# 3602879701896397/36028797018963968
# From a string
three_sevenths = Fraction("3/7")
print(three_sevenths)
# 3/7
# From a decimal
exact = Fraction(Decimal("0.25"))
print(exact)
# 1/4
Fraction arithmetic
from fractions import Fraction
a = Fraction(1, 2)
b = Fraction(3, 4)
# All basic operations work
print(a + b) # 5/4
print(a - b) # -1/4
print(a * b) # 3/8
print(a / b) # 2/3
# Comparisons work too
print(a < b) # True
print(a == b) # False
Class Methods
Fraction.from_float()
Creates a Fraction from a floating-point number. This method converts the exact binary representation to a rational number.
from fractions import Fraction
# From float
result = Fraction.from_float(0.5)
print(result)
# 1/2
# Note: float representation is exact
result = Fraction.from_float(0.1)
print(result)
# 3602879701896397/36028797018963968
Fraction.from_decimal()
Creates a Fraction from a Decimal object. This is useful when working with decimal financial data.
from fractions import Fraction
from decimal import Decimal
# From decimal
result = Fraction.from_decimal(Decimal("0.25"))
print(result)
# 1/2
# Useful for money calculations
dollar = Fraction(Decimal("10.50"))
print(dollar)
# 21/2
The gcd() Function
The fractions module also exposes math.gcd() for computing the greatest common divisor of two integers.
from math import gcd
print(gcd(48, 18))
# 6
Common Patterns
Avoiding floating-point errors
from fractions import Fraction
# Instead of 0.1 + 0.2 (which gives 0.30000000000000004)
result = Fraction(1, 10) + Fraction(2, 10)
print(result == Fraction(3, 10))
# True
Working with repeating decimals
from fractions import Fraction
# 1/3 as a fraction
third = Fraction(1, 3)
print(third)
# 1/3
# Operations remain exact
print(third * 3)
# 1
Converting to other types
from fractions import Fraction
f = Fraction(5, 4)
print(float(f)) # 1.25
print(int(f)) # 1 (truncates)
print(f.numerator) # 5
print(f.denominator) # 4