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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…