It depends on the application but most of time floats should not be hashed because hashing is used for fast lookup for exact matches and most floats are the result of calculations that produce a float which is only an approximation to the correct answer. The usually way to check for floating equality is to check if it is within some delta (in absolute value) of the correct answer. This type of check does not lend itself to hashed lookup tables.
EDIT:
Normally, because of rounding errors and inherent limitations of floating point arithmetic, if you expect that floating point numbers a
and b
should be equal to each other because the math says so, you need to pick some relatively small delta > 0
, and then you declare a
and b
to be equal if abs(a-b) < delta
, where abs
is the absolute value function. For more detail, see this article.
Here is a small example that demonstrates the problem:
float x = 1.0f;
x = x / 41;
x = x * 41;
if (x != 1.0f)
{
std::cout << "ooops...
";
}
Depending on your platform, compiler and optimization levels, this may print ooops...
to your screen, meaning that the mathematical equation x / y * y = x
does not necessarily hold on your computer.
There are cases where floating point arithmetic produces exact results, e.g. reasonably sized integers and rationals with power-of-2 denominators.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…