What is floatingpointerror?
In Python, floating point errors arise due to the way numbers are represented in binary form. This can lead to precision errors, where the result of a calculation is not exactly as expected, often due to the limitations of binary representation of decimal numbers.
Common Causes
- Using float for calculations requiring high precision:
python
result = 0.1 + 0.2
print(result) # Output: 0.30000000000000004
- Comparing floating-point numbers directly:
python
if 0.1 + 0.2 == 0.3:
print('Equal')
else:
print('Not equal') # Output: Not equal
- Accumulating errors over many operations:
python
total = 0.0
for _ in range(1000):
total += 0.1
print(total) # Output: 100.00000000000009
How to Fix
- Use the decimal module for high precision calculations.
- Use a tolerance level for comparing floats.
Wrong Code
result = 0.1 + 0.2
if result == 0.3:
print('Equal')Correct Code
from decimal import Decimal
result = Decimal('0.1') + Decimal('0.2')
print(result)
import math
if math.isclose(0.1 + 0.2, 0.3, rel_tol=1e-9):
print('Equal')Prevention Tips
- Use the decimal module for precise decimal calculations.
- Avoid direct comparison of floating-point numbers.
- Accumulate errors using higher precision data types when possible.