0

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?

  • 1
    If you subtract two very large almost equal floating point numbers (say about 10e20) their difference could be 1,000,000 (or greater) for example. Epsilon needs to be chosen with respect to the magnitude of numbers being tested. – Richard Critten Nov 19 '21 at 13:43
  • 3
    Have an article with a detailed explanation: https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ and some possibly better ways to compare floats: https://stackoverflow.com/a/253874/14215102 –  Nov 19 '21 at 13:44
  • The float comparison itself does not require an epsilon. But in many applications you need to take into account the possible error which accumulated while computing the values. And there is no generic solution which works for every use case, i.e., you need to show more context. – chtz Nov 19 '21 at 15:01

2 Answers2

3

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.

Sneftel
  • 40,271
  • 12
  • 71
  • 104
1

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.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312