Floating Point Comparison Anomalies
The concept of floating point comparisons can be misleading, especially when dealing with float data types. Consider the following example:
int main() { float a = 0.7; float b = 0.5; if (a < 0.7) { if (b < 0.5) printf("2 are right"); else printf("1 is right"); } else printf("0 are right"); }
Intuitively, one might assume this code would output "0 are right" since the initial condition is false. However, surprisingly, the actual output is "1 is right."
Explanation
The explanation lies in the internal representation of floating-point numbers. In C, floats are promoted to doubles during comparisons, and doubles are more precise than floats. As a result, 0.7 as a float is not exactly the same as 0.7 as a double. When 0.7 (as a float) is promoted to a double, it becomes slightly less than 0.7 (as a double).
On the other hand, 0.5 (as a float) happens to be an exact representation in double precision. Therefore, when the condition b < 0.5 is evaluated, it returns false because 0.5 (as a double) is not less than itself.
Solutions
To resolve this issue, one can either:
By implementing either of these solutions, you can obtain the desired output of "0 are right."
The above is the detailed content of Why Does Floating-Point Comparison in C Sometimes Produce Unexpected Results?. For more information, please follow other related articles on the PHP Chinese website!