java – Float. Equals is completely useless. What should I use?
in consideration of:
> == should never be used to compare doubles/floats > it appears from the docs that (beyond some type-checking and checking against NaN) that’s all that Double/Float. equals does
Looks like a float in its current form Equals is almost completely useless
Do I miss something, or sometimes use float Equals is appropriate unless you want to test extremely rare cases of binary equality?
If so, is scrolling your own identikit epsilon function (as recommended in the first link) really something to do, or is there an existing wrapper for this incredibly common operation?
In addition, double / float Will compare encounter the same problem, or is there an existing comparator that requires epsilon?
(note that I cannot change an existing library from floats to bigd)
Solution
If you are sure you want to compare floats, float Equals is useless, but it also checks the type of parameter and is reflexive For example, don't forget to call equals. Automatically in the collection
This is the source code:
public boolean equals(Object obj) { return (obj instanceof Float) && (floatToIntBits(((Float)obj).value) == floatToIntBits(value)); }
This allows any float instance (including the new float ("Nan") to be equal to itself, which is part of the general contract of equals, and the new float ("– 0") is different from the new float ("0"), which is very useful (and consistent with hashcode)
As for the second part: when you deal with real problems, your epsilon has nothing to do with some context or physical dimensions (or you may not use float but BigDecimal), not many cases Semantically, the equality of floating point numbers does not really make sense You'd better be interested in distance