In this lesson, you will learn how to bypass floating-point precision errors by performing exact calculations using the Fraction class from Python’s fractions module.
The Problem with Floats
Computers represent floating-point numbers (like 0.1 or 0.3) as binary fractions. Because many decimal values cannot be represented exactly in binary, you often encounter annoying artifacts like 0.1 + 0.2 == 0.30000000000000004. When your application requires absolute mathematical precision—such as in financial calculations or scientific ratios—these tiny inaccuracies can compound into significant errors.
Using the Fraction Module
The Fraction object stores numbers as a pair of integers (numerator and denominator), maintaining perfect accuracy regardless of how many operations you perform.
from fractions import Fraction
# Create fractions from integers, strings, or floats
a = Fraction(1, 3)
b = Fraction("0.25")
# Calculations remain exact
result = a + b # 1/3 + 1/4 = 7/12
print(result) # Output: 7/12
Managing Float Conversions
You might sometimes receive data as a float that you need to convert to a Fraction. However, Fraction(0.1) will result in a very long, messy fraction (e.g., 3602879701896397/36028797018963968) because it is capturing the exact binary representation of that float.
To handle this, use the .limit_denominator() method. This rounds the fraction to the nearest value that makes sense for your data:
# The raw float representation is messy
precise_val = Fraction(0.1)
# Constrain it to a reasonable decimal approximation
clean_val = precise_val.limit_denominator(10)
print(clean_val) # Output: 1/10
By using Fraction, you ensure that your program calculates 1/3 + 1/3 + 1/3 to be exactly 1, rather than a value slightly less than one. This keeps your logic clean and removes the need for "epsilon" comparison checks when determining if two rational values are equal.
Key Takeaway: Always use the Fraction module when your logic requires exact rational arithmetic, and use .limit_denominator() to clean up fractions derived from imperfect floating-point inputs.