1

Possible Duplicate:
Most effective way for float and double comparison
How dangerous is it to compare floating point values?

I have const float M = 0.000001; and float input;. I want to not equality check on them. But I know direct check has side effect M != input. So, my question how I can compare two float value without side effect ?

Community
  • 1
  • 1
  • 3
    What do you mean by "side effect"? Comparing floats has no side effects in the usual meaning of the term. – Marcelo Cantos Nov 06 '12 at 11:14
  • `M != input` isn't a (doesn't have any) side effect. – James Kanze Nov 06 '12 at 11:14
  • You can find an excellent article about floating point comparison here: [Comparing floating point numbers](http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm). Basically, depending on your requirements, you can use - epsilon – absolute error: when the approx. range of values is known in advance - epsilon – relative error: when the approx. range of values is NOT known in advance - use the integer representation: when speed is of the essence. – Alex Nov 06 '12 at 11:16

2 Answers2

3
const double epsilon = 1e-12; 

if(fabs(input - M) < epsilon) //input == M
{
    //...
}
if(fabs(input - M) >= epsilon) // input != M
{
    //...
}

The smaller the value of epsilon the more accurate the comparison is, therefore the more the probablity that it will tell you that two values are not equal whereas you wanted them to be considered equal. The larger the value of epsilon, the more the probability that it will tell you the results are equal when in fact you wanted them to be not equal. The value of epsilon should be chosen in accordance with the specifics of the task at hand.

Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
  • It might be worth pointing out that the actual value of `epsilon` is application-dependant, you're supposed to plug in a value that makes them "equal enough" for your usage. – unwind Nov 06 '12 at 11:16
  • @user1802858 Switch the comparison operator to `>=`. – unwind Nov 06 '12 at 11:17
0

When comparing floats, you have to compare them for being "close" instead of "equal." There are multiple ways to define "close" based on what you need. However, a typical approach could be something like:

namespace FloatCmp {

const float Eps = 1e-6f;

bool eq(float a, float b, float eps = Eps) {
  return fabs(a - b) < eps;
}

//etc. for neq, lt, gt, ...

}

Then, use FloatCmp::eq() instead of == to compare floats.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455