Reputation: 65
I am coding a small app in cpp, and I need to compare floats.
I have read in many places that I need to use an epsilon.
The most common approach seems to be
static inline bool compareFloat(float x, float y) {return (fabs(x - y) < FLT_EPSILON);}
but I have read in some places that this solution is not enough. Does anyone have a real example where this approach is not enough?
Upvotes: 0
Views: 290
Reputation: 224546
compareFloat(2.f/41*41, 2.f*41/41)
returns zero, reporting as unequal these expressions that we would like to be equal.
(This is when float
is the IEEE-754 32-bit binary format, which is common.)
Do not seek kludges for floating-point comparison. If you are having problems comparing floating-point numbers, you should probably not be comparing floating-point numbers rather than trying to make the comparisons work. Instead, post a question explaining your design and why you think you need to compare numbers and what you are trying to achieve by it and ask about solutions.
Upvotes: 1
Reputation: 41542
Sure. If x is 1e-10 and y is 5e-10, your function will return that the two are equal, even though one is five times as large as the other.
And in the other direction, if you compare 1e10 with 1e10+1, they’ll compare equal (since the precision was already lost during the addition).
As for false negatives (again, because of precision loss), 10000.0f / 71 * 71 will compare unequal with 10000.0f.
Trying to use an epsilon tolerance to “fix” floating point error will never result in a robust comparison.
Upvotes: 3