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)
Bottom line: Never use == to compare two floating point numbers. Here's a simple example: double x = 1.0 / 10.0; double y = x * 10.0; if (y !=
Using the == Operator As a result, we can't have an exact representation of most double values in our computers. They must be rounded to be saved. In that case, comparing both values with the == operator would produce a wrong result.
The compare() method of Float Class is a built-in method in Java that compares the two specified float values. The sign of the integer value returned is the same as that of the integer that would be returned by the function call. Parameters: The function accepts two parameters: f1: The first float value to be compared.
Floating point comparison in C++To compare two floating point values, we have to consider the precision in to the comparison. For example, if two numbers are 3.1428 and 3.1415, then they are same up to the precision 0.01, but after that, like 0.001 they are not same.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With