← Back to Error Guide
floatingpointerror

How to Fix floatingpointerror

Floatingpointerror occurs when numerical calculations using floats result in unexpected precision issues.

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

How to Fix

  1. Use the decimal module for high precision calculations.
  2. 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

Related Errors

More Python Error Guides