【问题标题】:How to compare float or double? [duplicate]如何比较浮点数或双精度数? [复制]
【发布时间】:2014-04-25 13:54:08
【问题描述】:

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

我认为像a == ba !=b 这样比较没有任何意义。有什么建议吗?

【问题讨论】:

    标签: c++


    【解决方案1】:

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

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

    您可以将 epsilon 用于 std::numeric_limits 中的浮点数或双精度数

    【讨论】:

      【解决方案2】:

      我使用这个功能:

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

      【讨论】:

      • 这个函数看起来比它需要的复杂得多。
      【解决方案3】:

      你可以简单地使用:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-25
        • 1970-01-01
        • 2015-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-08
        相关资源
        最近更新 更多