Why 0.1 plus 0.2 is not equal to 0.3 in Python explained
In Python,
0.1 + 0.2 is not exactly equal to 0.3 because floating-point numbers are stored in binary, which cannot precisely represent some decimal fractions. This causes tiny rounding errors, making the sum slightly different from 0.3.Syntax
In Python, you write decimal numbers using float type like 0.1, 0.2, and 0.3. When you add two floats, Python uses binary floating-point arithmetic internally.
0.1,0.2,0.3: decimal numbers as floats+: addition operator- Comparison with
==checks if two values are exactly equal
python
a = 0.1 b = 0.2 c = 0.3 print(a + b == c)
Output
False
Example
This example shows that adding 0.1 and 0.2 does not exactly equal 0.3, and prints the actual sum to reveal the tiny difference.
python
a = 0.1 b = 0.2 c = 0.3 print('0.1 + 0.2 == 0.3:', a + b == c) print('Actual sum:', a + b)
Output
0.1 + 0.2 == 0.3: False
Actual sum: 0.30000000000000004
Common Pitfalls
Many beginners expect 0.1 + 0.2 == 0.3 to be True, but floating-point precision causes this to be False. This can lead to bugs when comparing floats directly.
To avoid this, use a small tolerance to check if two floats are close enough instead of exactly equal.
python
a = 0.1 b = 0.2 c = 0.3 # Wrong way: direct equality print(a + b == c) # False # Right way: check closeness with tolerance tolerance = 1e-9 print(abs((a + b) - c) < tolerance) # True
Output
False
True
Quick Reference
- Floating-point numbers store decimals approximately in binary.
- Direct equality checks can fail due to tiny rounding errors.
- Use a tolerance (like
1e-9) to compare floats safely. - Python's
math.isclose()function can also help compare floats.
python
import math print(math.isclose(0.1 + 0.2, 0.3))
Output
True
Key Takeaways
Floating-point numbers cannot represent some decimals exactly, causing small errors.
Directly comparing floats with == can give unexpected False results.
Use a small tolerance or math.isclose() to compare float values safely.
The sum 0.1 + 0.2 is very close but not exactly 0.3 in Python.
Understanding floating-point precision helps avoid bugs in numeric code.