How to correctly and standardly compare floats?

后端 未结 8 1357
夕颜
夕颜 2020-11-27 04:30

Every time I start a new project and when I need to compare some float or double variables I write the code like this one:

if (fabs(prev.min[i] - cur->min         


        
8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 04:41

    You can use std::nextafter for testing two double with 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;
    }
    

提交回复
热议问题