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.
Using ==
assumes that your code has accounted for any floating point rounding errors, and it's very rare/difficult for code to do that.
Comparing against epsilon assumes that a reasonable amount of rounding error will be less than the constant epsilon, and that is very likely a wrong assumption!
- If your numbers have magnitude greater than
2.0
, your epsilon trick will be no different from direct comparison, and have the same flaws. Regardless of whether you use <
or <=
.
- If your numbers have the same sign and a magnitude smaller than epsilon, your epsilon trick will say they are always equal, even if one is hundreds of times larger than the other. They would both be equal to zero, too.
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.
const auto relative_difference_factor = 0.0001. // 0.01%
const auto greater_magnitude = std::max(std::abs(double1),std::abs(double2));
if ( std::abs(double1-double2) < relative_difference_factor * greater_magnitude )
std::cout<<"Relatively close";
else
std::cout<<"Not relatively close";