c++c++11floating-point

Modern practice to compare double/float for equality in modern C++


if (std::abs(double1 - double2) < std::numeric_limits<double>::epsilon())
  std::cout<<"Equal";
else
  std::cout<<"Not equal";

Is this code with modern C++11/14/17/21 is still the way we should compare float and doubles, or now it's ok just to write

if (double1 == double2)

And compiler will handle the epsilon issue for us?

BTW: is it better to write < or <= when checking against epsilon?


Solution

  • Is this code with modern C++11/14/17/21 is still the way we should compare float and doubles, or now it's ok just to write if (double1 == double2) And compiler will handle the epsilon issue for us?

    Both approaches function the same in modern C++ as they did in early C++.

    Both approaches are also flawed.

    A wise approach may be to avoid writing code that depends on whether floating point numbers are equal. Instead test if they are relatively close, by some factor.

    The code below will test whether two numbers are within about 0.01% of each other. Regardless of their scale.

    constexpr bool relatively_close( double d1, double d2 )
    {
      static constexpr auto relative_difference_factor = 0.0001.    // 0.01%
      const auto greater_magnitude = std::max(std::abs(d1),std::abs(d2));
    
      return ( std::abs(d1-d2) < relative_difference_factor * greater_magnitude );
    }