Is Float.equals (nearly) completely useless and what should I use instead?

Considering that:

  • == 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
  • 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.

    链接地址: http://www.djcxy.com/p/26018.html

    上一篇: Web API帮助页面不显示XML

    下一篇: Float.equals(几乎)完全无用,我应该用什么来代替?