Strange Floating-Point Behavior in Java Programs
In this question, a user encounters peculiar behavior while summing double values in an array. Specifically, the result gradually deviates from the expected sum. This phenomenon can be attributed to the way floating-point values are represented in digital systems.
IEEE singles and doubles, the most prevalent floating-point representations in programming languages, employ binary storage rather than decimal storage. Consequently, only certain decimal fractions can be accurately represented in binary form. These fractions are limited to values that are expressible as sums of negative powers of two, such as:
0.5 (2^-1) 0.125 (2^-3) 0.625 (2^-1 + 2^-3)
Fractions that cannot be represented as sums of negative powers of two, like 0.96, contain an inherent error in their binary representation. When these fractions are displayed as decimal values with complete precision, they do not match the original value due to this unavoidable approximation.
The above is the detailed content of Why Does Summing Doubles in Java Result in Unexpected Values?. For more information, please follow other related articles on the PHP Chinese website!