Is Float.equals (nearly) completely useless and what should I use instead?
Considering that:
It would seem like Float.equals in its current form is almost completely useless.
Am I missing something, or are there times when it is appropriate to use Float.equals, except in the staggeringly rare case that you want to test for binary equality?
And if so, is it genuinely the done thing to roll your own identikit epsilon function (as recommended in the first link), or is there an existing wrapper for this staggeringly common operation?
Also, does Double/Float.compare suffer from the same issue, or is there a existing comparator that takes an epsilon?
(Note that I can't change the existing libraries from Floats to BigD)
Float.equals
is useless if you're sure to compare Floats yourself, but it also checks the type of the argument and is reflexive. Don't forget equals
is automatically called in collections for example.
Here's the source code:
public boolean equals(Object obj) {
return (obj instanceof Float)
&& (floatToIntBits(((Float)obj).value) == floatToIntBits(value));
}
This allows any instance of Float
, including new Float("NaN")
, to be equal to itself, which is part of the general contract of equals, and new Float("-0")
to be different from new Float("0")
which might be useful (and is consistent with hashCode
).
As for the second part : there's not a lot of cases, when you deal with real problems, where your epsilon isn't related to some context or physical dimension (or you probably shouldn't be using Float
but BigDecimal
). Semantically, equality for floating point numbers doesn't really make sense. At best you're interested in distances.
上一篇: Web API帮助页面不显示XML