c++ comparing two floating point values

前端 未结 5 1312
陌清茗
陌清茗 2020-12-30 15:58

I\'m wondering what is the difference for comparing two double between this two manner :

double a1 = ...;
double a2 = ....;
  1. fabs(a1-a
5条回答
  •  情深已故
    2020-12-30 16:11

    Personally, I'm using std::nextafter for comparing two double. This use the smallest epsilon on a value (or a factor of the smallest epsilon).

    bool nearly_equal(double a, double b)
    {
      return std::nextafter(a, std::numeric_limits::lowest()) <= b
        && std::nextafter(a, std::numeric_limits::max()) >= b;
    }
    
    bool nearly_equal(double a, double b, int factor /* a factor of epsilon */)
    {
      double min_a = a - (a - std::nextafter(a, std::numeric_limits::lowest())) * factor;
      double max_a = a + (std::nextafter(a, std::numeric_limits::max()) - a) * factor;
    
      return min_a <= b && max_a >= b;
    }
    

提交回复
热议问题