Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
497 views
in Technique[技术] by (71.8m points)

junit - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...