๐งฎ 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
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
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
โ Use Rounding (when slight imprecision is okay):
console.log((0.1 + 0.2).toFixed(2)); // Output: "0.30"
โ Use Epsilon Comparison (machine precision check):
import math
print(math.isclose(0.1 + 0.2, 0.3)) # Output: True
๐ 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)
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