What is the most performant way to check double values for equality.
I understand that
double a = 0.00023d;
double b = 0.00029d;
boolean eq = (a == b);
is slow.
So I'm using
double epsilon = 0.00000001d;
eq = Math.abs(a - b) < epsilon;
The problem is that Infinitest
is complaning about tests taking too much time. It's not a big deal (1 sec top), but it made me curious.
Additional info
a
is hard coded since it's the expected value, b
is computed by
// fyi: current = int, max = int
public double getStatus()
{
double value = 0.0;
if (current != 0 && max != 0)
value = ((double) current) / max;
return value;
}
Update
java.lang.Double does it that way
public boolean equals(Object obj) {
return (obj instanceof Double)
&& (doubleToLongBits(((Double)obj).value) ==
doubleToLongBits(value));
}
so one could assume that is the best practice.
Double
instead ofdouble
? – Gentlemanlyboolean eq = (a == b)
takes less than 10 nano-seconds. How faster do you need it to be? – AngoraDouble
is much slower than thandouble
and doesn't behave the same as double for equals so that is why the code is different. – Angora