Properly testing two floating-point numbers for equality is something that a lot of people, including me, don\'t fully understand. Today, however, I thought about how some s
The following code (which I changed so it compiles: Specifically the call to floateq was changed to floatcmp) prints out float->double vs double: 1 0 , not 0 0 (as one would expect when comparing those two values as floats).
#include
bool floatcmp(float a, float b) {
//check NaN
return !(a < b) && !(b < a);
}
int main()
{
std::cout << "float->double vs double: "
<< floatcmp(static_cast(0.7f), 0.7) << " "
<< (static_cast(0.7f) == 0.7) << "\n";
}
However what matters for the standard library is that operator< defines a strict weak ordering, which it in fact does for floating point types.
The problem with equality is that two values may look the same when rounded to say 4 or 6 places but are in fact totally different and compare as not equal.