如何比较浮点数或双倍?

时间:2014-03-19 11:06:50

标签: c++

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

我认为a == ba !=b之间的比较没有任何意义。有什么建议吗?

3 个答案:

答案 0 :(得分:5)

比较浮点数或双打数的技巧是使用fabs

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

您可以将epsilon用于来自std::numeric_limits

的花车或双打

答案 1 :(得分:4)

您可以简单地使用:

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

答案 2 :(得分:-1)

我使用这个功能:

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;
}
相关问题