Question
Why do multiple additions of 0.1 sometimes yield accurate results in Java despite precision issues?
double sum = 0, d = 0.1;
for (int i = 0; i < 5; i++)
sum += d;
System.out.println(sum == 0.5); // Prints true
Answer
In Java, the representation of decimal numbers in binary can lead to precision issues. However, certain results may appear accurate due to the nature of specific numbers being added together.
double sum = 0, d = 0.1;
for (int i = 0; i < 5; i++)
sum += d;
System.out.println(sum == 0.5); // Prints true
Causes
- 0.1 is represented as a binary floating-point number, which is inherently imprecise.
- The binary system cannot exactly represent certain fractions, like 0.1, but can represent exact multiples of powers of two, like 0.5.
Solutions
- Adding 0.1 three times results in a floating-point number that is very close to, but not exactly, 0.3 due to rounding errors.
- When adding 0.1 five times, the result aggregates more accurately to 0.5, which has a precise binary representation, hence returning true when compared.
Common Mistakes
Mistake: Assuming all decimal additions will produce accurate results in floating-point arithmetic.
Solution: Always test floating-point values for equality with a tolerance (epsilon) rather than exact matching.
Mistake: Neglecting that not all decimal fractions can be exactly represented in binary format.
Solution: Be aware of which decimal fractions can and cannot be accurately represented in floating-point.
Helpers
- Java floating-point precision
- adding decimal numbers in Java
- floating-point arithmetic
- binary representation of decimals