如何比较浮点数或双精度

How to compare float or double?

本文关键字:浮点数 双精度 比较 何比较      更新时间:2023-10-16

是否有内置库可以比较float或double

我不认为比较a == ba !=b有任何意义。任何建议吗?

比较浮点数或双精度数的技术是使用fabs

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

对于std::numeric_limits

中的浮点数或双精度数,可以使用epsilon

您可以简单地使用:

fabs(a-b) < eps  // eps is the precision you want to achieve

我使用这个函数:

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;
}