DEV Community

Nozibul Islam
Nozibul Islam

Posted on

8 4 4 4 4

Floating-Point Precision Error

๐Ÿงฎ 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.

Top comments (1)

Collapse
 
nadeem_zia_257af7e986ffc6 profile image
nadeem zia โ€ข

Interesting to read

Some comments may only be visible to logged-in visitors. Sign in to view all comments. Some comments have been hidden by the post's author - find out more