-1

Is there built-in library can compare float or double

I do not think compare like a == b or a !=b makes any sense. Any suggestion?

Adam Lee
  • 24,710
  • 51
  • 156
  • 236

3 Answers3

5

the technique to compare floats or doubles is to use fabs

bool isEqual(const float a,const float b)
{
    return fabs(a - b) < std::numeric_limits<float>::epsilon();
}

You can use epsilon for the floats or doubles from std::numeric_limits

Raxvan
  • 6,257
  • 2
  • 25
  • 46
4

You can simply use:

fabs(a-b) < eps  // eps is the precision you want to achieve
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
-1

I use this function :

template <typename T>
bool approx(const T& x, const T& y, const T& eps = 1.0e-10)
{
  if(x == y)
    return true;
  if(x == 0.0)
    return (y < 0.0 ? -y : y) < eps;
  if(y == 0.0)
    return (x < 0.0 ? -x : x) < eps;
  return (x < y ? y - x : x - y) < eps * ((x < 0.0 ? -x : x) + (y < 0.0 ? -y : y)) / 2.0;
}
Caduchon
  • 4,574
  • 4
  • 26
  • 67