This guide explains Floating-Point Precision: Why 0.1 + 0.2 Is Not Exactly 0.3 through a focused example and practical reasoning. No prior knowledge of this specific operation is required.
Understanding the Concept
Most decimal fractions cannot be represented exactly as finite binary floating-point values. As a result, arithmetic can produce tiny rounding differences. Compare approximate values with an appropriate tolerance instead of checking exact equality.
When You Would Use This
Two calculated totals look mathematically equal but may differ at the binary representation level.
Step-by-Step Example
import math
first_total = 0.1 + 0.2
second_total = 0.3
print(first_total == second_total)
print(math.isclose(first_total, second_total))
print(f"{first_total:.17f}")
How the Example Works
Direct equality is False, while math.isclose() is True under its default relative tolerance. The final output reveals additional digits of the binary approximation.
Example Output
False
True
0.30000000000000004
Try It Yourself
Try comparing 0.0 with 1e-10 using a suitable abs_tol.
Common Beginner Mistakes
- Using exact
==for results of inexact floating-point arithmetic. - Assuming formatted two-decimal output fixes the original numeric representation.
- Using the default relative tolerance near zero without considering an absolute tolerance.
Key Takeaways
- Most decimal fractions cannot be represented exactly as finite binary floating-point values.
- Direct equality is
False, whilemath.isclose()isTrueunder its default relative tolerance. - Avoid this mistake: Using exact
==for results of inexact floating-point arithmetic.