Comparing Two Floating-Point Numbers
The mathematician Leopold Kronecker is believed to have said:
God made the integers, all else is the work of man.
And Kronecker didn’t even know the floating-point numbers “made” for computers. Comparing two numbers of type float
or double
in C++ and related languages is a source for regular errors. When are the if-conditions in the following code snippet true?
float actual = calculate(10.0f, 0.2f, 45); // 10 - 0.2 * 45 = 1
if (actual == 1.0f) {
// is this ever executed?
}
if (actual - 1.0f == 0.0f) {
// is this ever executed?
}
The function calculate
produces the result 10 – 0.2 * 45 = 10 – 9 = 1 – at least for human beings. So, both conditions should be true. However, they are both false.
If we turn on the warning -Wfloat-equal
, the compiler will warn us that comparing floating point with == or != is unsafe. The compiler tells us what is wrong, but not how to fix it. I’ll explain why the above “solution” is wrong, why another obvious “solution” is nearly as bad, and why even the Qt function qFuzzyCompare
can still be improved.