Today, I was looking through some C++ code (written by somebody else) and found this section:
double someValue = ...
if (someValue < std::numeric_limits<double>::epsilon() &&
someValue > -std::numeric_limits<double>::epsilon()) {
someValue = 0.0;
}
I'm trying to figure out whether this even makes sense.
The documentation for epsilon()
says:
The function returns the difference between 1 and the smallest value greater than 1 that is representable [by a double].
Does this apply to 0 as well, i.e. epsilon()
is the smallest value greater than 0? Or are there numbers between 0
and 0 + epsilon
that can be represented by a double
?
If not, then isn't the comparison equivalent to someValue == 0.0
?
numeric_limits<>::epsilon
is misleading and irrelevant. What we want is to assume 0 if the actual value differs by no more than some ε from 0. And ε should be chosen based on the problem specification, not on a machine-dependent value. I'd suspect that the current epsilon is useless, as even just a few FP operations could accumulate an error greater than that.