javajunitcomparisondoubleinfinitest

Performant way to check java.lang.Double for equality


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.


Solution

  • JUnit has a method of checking a Double for 'equality' with a given delta:

    Assert.assertEquals(0.00023d, 0.00029d, 0.0001d);
    

    See this API documentation.

    As noted in the comments, JUnit actually most likely is slower than comparing manually with a given delta. JUnit first does a Double.compare(expected, actual) followed (if not equal) by a Math.abs(expected - actual) <= delta.

    Hopefully this answer still is useful for people not aware that JUnit actually provides a way for inexact Double equality testing.