Floating-Point Precision Error
Nozibul Islam

Nozibul Islam @nozibul_islam_113b1d5334f

About: I am a Full-Stack Developer specialized Front-end Developer. Passionate about algorithms, data structures, and coding challenges & always ready to face new challenges.

Location:
Dhaka, Bangladesh
Joined:
Aug 24, 2024

Floating-Point Precision Error

Publish Date: Apr 9
24 3

🧮 Floating-Point Precision Error: Why 0.1 + 0.2 ≠ 0.3?

We often encounter strange results like:

console.log(0.1 + 0.2); 
// Output: 0.30000000000000004
Enter fullscreen mode Exit fullscreen mode

But why does this happen?

The reason is Floating-Point Precision Error!

💡 What is Floating-Point Precision Error?

Computers use the binary number system to store decimal values. However, some decimal numbers like 0.1, 0.2, and 0.3 have infinite binary representations. This means they can’t be stored precisely, and tiny inaccuracies (known as precision errors) occur.

📌 Example:

console.log(0.1 + 0.2); 
// Expected: 0.3
// Actual:   0.30000000000000004
Enter fullscreen mode Exit fullscreen mode

We expected 0.3, but got something slightly off. That’s due to how floating-point numbers are represented in memory.

🖥️ Why Does This Happen? (IEEE 754 Standard)

Computers follow the IEEE 754 Standard to represent decimal numbers in binary. Each number is broken into three parts:

  • Sign Bit → Indicates if the number is positive or negative
  • Exponent → Determines how many times to multiply by powers of 2
  • Mantissa (or Fraction) → Holds the actual number value

However, the mantissa has limited length, so many decimal numbers can't be stored exactly, resulting in rounding errors.

🛠️ How to Reduce Precision Errors

✅ Use a Decimal Library (for exact decimal math):

from decimal import Decimal
print(Decimal('0.1') + Decimal('0.2'))  # Output: 0.3
Enter fullscreen mode Exit fullscreen mode

✅ Use Rounding (when slight imprecision is okay):

console.log((0.1 + 0.2).toFixed(2)); // Output: "0.30"
Enter fullscreen mode Exit fullscreen mode

✅ Use Epsilon Comparison (machine precision check):

import math
print(math.isclose(0.1 + 0.2, 0.3))  # Output: True
Enter fullscreen mode Exit fullscreen mode

🚀 Why Does It Matter in Real Life?

🔹 Banking Systems – Even a tiny error can cause massive financial loss

🔹 Scientific Computation – Tiny mistakes can derail space missions

🔹 Game Development – A small glitch in the physics engine can ruin the player experience

Conclusion

  • 🔸 Computers can’t store all decimal numbers exactly.
  • 🔸 Floating-point precision errors cause small but important inaccuracies.
  • 🔸 Using techniques like decimal libraries, rounding, or epsilon comparison can help minimize these issues.

Comments 3 total

Add comment