Computer Arithmetic
In many programming languages, why is the double-precision comparison 0.1 + 0.2 == 0.3 false?
- AThe add instruction sometimes cannot add fractions correctly
- B0.3 is a special value that floating point cannot represent, so comparisons are always false
- CEach is a rounded approximation, so the values differ slightly
Show answer and explanation
Answer: C. Each is a rounded approximation, so the values differ slightly
None of 0.1, 0.2 and 0.3 is exact in binary; each is stored rounded to the nearest representable value. Adding the approximations of 0.1 and 0.2 and rounding gives 0.30000000000000004, which differs in the last digit from 0.3's approximation, 0.29999999999999998…. Floating-point values are therefore usually compared by checking whether the absolute difference is within a small tolerance. The add instruction rounds correctly per the standard, and 0.3 is representable as an approximation.
- A. The add instruction rounds correctly as the standard requires.
- B. 0.3 can be represented as a nearby value.
- C. Correct. Each value's rounding error makes the results differ slightly.