Floating Point Comparison Discrepancy
In the provided code snippet:
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"); }
the expected output of "0 are right" is not obtained. Instead, "1 is right" is printed. This discrepancy arises due to the inherent imprecision of floating-point numbers.
When performing comparisons with floating-point operands, they are automatically promoted to double-precision values. Floats, being less precise than doubles, may not represent the intended value exactly. In this case, when a (a float) is compared to 0.7 (a double), a is internally converted to a double and loses precision. This results in a being slightly less than 0.7, causing the a < 0.7 comparison to evaluate to true.
To resolve this issue, one can either:
double a = 0.7; double b = 0.5;
float a = 0.7f; float b = 0.5f;
Both approaches ensure that the operands remain as floats and avoid the precision loss during promotion to double.
The above is the detailed content of Why Does My Floating-Point Comparison Produce Unexpected Results?. For more information, please follow other related articles on the PHP Chinese website!