How to Fix Floating Point Precision Issues in Python With Examples

 



 What Is a Floating Point Precision Problem?

In Python, floating point numbers (float) use binary representation, which can’t accurately store some decimal numbers, leading to unexpected results.

 Example Problem:

a = 0.1 + 0.2
print(a)  # Output: 0.30000000000000004

This happens because 0.1 and 0.2 cannot be exactly represented in binary.

 Common Ways to Fix Floating Point Issues

1.  Use round() for Display or Comparison

a = 0.1 + 0.2
print(round(a, 2))  # Output: 0.3

 Note: Use round() only for display or loose comparison, not for financial calculations.

2.  Use decimal.Decimal for Precision (e.g., in finance)

from decimal import Decimal, getcontext

getcontext().prec = 6  # Set precision if needed

a = Decimal("0.1") + Decimal("0.2")
print(a)  # Output: 0.3

 Use Decimal when precise base-10 arithmetic is required.

3.  Use math.isclose() for Comparisons

For floating-point comparisons, never use ==. Use this instead:

import math

a = 0.1 + 0.2
print(math.isclose(a, 0.3))  # Output: True

You can also set tolerances:

math.isclose(a, 0.3, rel_tol=1e-9)

4.  Use fractions.Fraction for Exact Rational Numbers

from fractions import Fraction

a = Fraction(1, 10) + Fraction(2, 10)
print(a)  # Output: 3/10
print(float(a))  # Output: 0.3

 Useful in math-heavy apps (like calculators, parsers, etc.)

 When Should You Worry About Precision?

Use Case Recommended Tool
Financial software decimal.Decimal
Math teaching apps fractions.Fraction
Display formatting round() or string fmt
Scientific calc math.isclose()

 Summary Table

Problem Example Solution
0.1 + 0.2 != 0.3 Use math.isclose()
Accurate decimals needed Use decimal.Decimal
Display rounding Use round(number, ndigits)
Use rational math Use fractions.Fraction

 Bonus: String Formatting for Clean Output

x = 0.1 + 0.2
print(f"{x:.2f}")  # Output: 0.30

0 Comments:

Post a Comment