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
Generally all comparison operations on floating point numbers should be done within a specified precision limit. Otherwise, you may be bitten by accumulated rounding error which is not seen at low precision, but will be taken into account by comparison operators. It just often doesn't matter much for sorting.
Another code sample which does show that your comparison doesn't work (http://ideone.com/mI4S76).
#include
bool floatcmp(float a, float b) {
//check NaN
return !(a < b) && !(b < a);
}
int main() {
using namespace std;
float a = 0.1;
float b = 0.1;
// Introducing rounding error:
b += 1;
// Just to be sure change is not inlined
cout << "B after increase = " << b << endl;
b -= 1;
cout << "B after decrease = " << b << endl;
cout << "A " << (floatcmp(a, b) ? "equals" : "is not equal to") << "B" << endl;
}
Output:
B after increase = 1.1
B after decrease = 0.1
A is not equal toB