问题
I have a specific question about floating point comparisons. I know that it's not recommended to use the == comparison due to precision issues, but in this specific case, I am wondering if, in all cases / compilers, this statement will hold true?
float a = 1.02f;
float b = 1.02f;
if(a == b)
{
print(true);
}
else
{
print(false);
}
In other words, if I assign floating point numbers exactly, with no addition, subtraction, demotion, or promotion, will this always hold true?
回答1:
Yes, the compiler should consistently translate floating point constants that are identical to the same value - if not, it's a bug in the compiler [which of course is not impossible]. However, as soon as you do ANYTHING ELSE to the value (such as reading it from a file including cin
) or do simple math (add 1.0, then subtract 1.0), the value is not guaranteed to be the same any longer.
As pointed out, the value "Not A Number" or "NaN" is guaranteed to NEVER be equal to anything, and all comparisons except !=
will be false
, no matter what it is compared to - this is part of the specification for floating point. But all other constants, as long as you are JUST using a constant to assign to a variable, it should remain the same throughout the code.
Of course, you can't rely on TWO DIFFERENT compilers coming up with the same exact value from the same source-code [many times they will, but sometimes they simply will do some different rounding of the last bit, or something like that which causes differences]
来源:https://stackoverflow.com/questions/31573514/floating-point-comparison-specific