How to correctly and standardly compare floats?

后端 未结 8 1368
夕颜
夕颜 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:38

    Here is a c++11 implementation of @geotavros 's solution. It makes use of the new std::numeric_limits::epsilon() function and the fact that std::fabs() and std::fmax() now have overloads for float, double and long float.

    template
    static bool AreEqual(T f1, T f2) { 
      return (std::fabs(f1 - f2) <= std::numeric_limits::epsilon() * std::fmax(std::fabs(f1), std::fabs(f2)));
    }
    

提交回复
热议问题