Feature suggestion: Add static equals methods to Float and Double
Joe Darcy
joe.darcy at oracle.com
Mon Jan 7 19:41:12 UTC 2019
Hello 99206970363698485155,h
On 1/4/2019 3:11 PM, some-java-user-99206970363698485155 at vodafonemail.de
wrote:
> To test whether primitive float or double values are equal according to `Float.equals` and `Double.equals` you either have to create wrapper instances for them (possible performance decrease), use the respective static `compareTo` (verbose) or have to use the appropriate methods (`floatToIntBits` / `doubleToLongBits`) (verbose and error-prone since you could confuse them with the other conversion methods).
In the context of a mathematics course, it is common to define multiple
equivalence relations over the same set of values. For objects in Java,
we see this in object identity under "a == b" as possibly distinct from
"a.equals(b)". For floating-point, I've written about this years back,
please excuse some artifacts introduced by blog conversions:
"Notions of Floating-Point Equality"
https://blogs.oracle.com/darcy/notions-of-floating-point-equality
tl;dr it would be helpful in some contexts to have an "is-equivalent"
test for floating-point values. When I need this, say in numerics
regression tests, I use
Double.compare(a, b) == 0
or a method wrapping that or an equivalent expression. This expression
distinguishes -0.0 from +0.0, but treats all NaNs as equivalent.
If writing test vectors for a specific chip, then the semantics of which
NaN bit pattern is returned are generally defined and a
"doubleToRawLongBits" notion of equality would be appropriate instead.
If a static two-argument equals method were to to added to Double, to
avoid confusion I think it would need to be added as
public boolean equals(double a, double b) {
return a == b;
}
say, to provide the ability to have a method reference to the double ==
operation.
However, I don't think it is necessary to add that method and I don't
find a sufficiently compelling case to add "isEquivalent" at this time.
Cheers,
-Joe
>
> It would be good to provide static methods for testing for equality of the primitive values:
>
> // In Float.java
>
> public static boolean equals(float a, float b) {
> return Float.floatToIntBits(a) == Float.floatToIntBits(b);
> }
>
> // In Double.java
>
> public static boolean equals(double a, double b) {
> return Double.doubleToLongBits(a) == Double.doubleToLongBits(b);
> }
>
> This would be very convenient for developers and prevent them from writing (possibly faulty) code for this themselves.
More information about the core-libs-dev
mailing list