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?
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
You can simply use:
fabs(a-b) < eps // eps is the precision you want to achieve
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;
}