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?
Assuming 64-bit IEEE double, there is a 52-bit mantissa and 11-bit exponent. Let’s break it to bits:
The smallest representable number greater than 1:
Therefore:
Are there any numbers between 0 and epsilon? Plenty… E.g. the minimal positive representable (normal) number is:
In fact there are
(1022 - 52 + 1)×2^52 = 4372995238176751616numbers between 0 and epsilon, which is 47% of all the positive representable numbers…