Comparing floating point number to zero

后端 未结 9 987
时光说笑
时光说笑 2020-11-28 23:04

The C++ FAQ lite \"[29.17] Why doesn\'t my floating-point comparison work?\" recommends this equality test:

#include   /* for std::abs(double) *         


        
9条回答
  •  爱一瞬间的悲伤
    2020-11-28 23:25

    You can use std::nextafter with a fixed factor of the epsilon of a value like the following:

    bool isNearlyEqual(double a, double b)
    {
      int factor = /* a fixed 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;
    }
    

提交回复
热议问题