执行检查java.lang.Double的相等方法 [英] Performant way to check java.lang.Double for equality

查看:240
本文介绍了执行检查java.lang.Double的相等方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我理解

  double a = 0.00023d; 
double b = 0.00029d;

boolean eq =(a == b);

很慢。



m使用

  double epsilon = 0.00000001d; 
eq = Math.abs(a-b) epsilon;






问题是 Infinitest 表示考试时间太长。



其他信息



是硬编码,因为它是期望值, b

  // fyi:current = int,max = int 
public double getStatus()
{
double值= 0.0;
if(current!= 0&& max!= 0)
value =((double)current)/ max;
返回值;
}

更新

java.lang.Double会这样。

  public boolean equals(Object obj){
return(obj instanceof Double)
&& (doubleToLongBits(((Double)obj).value)==
doubleToLongBits(value));
}

因此可以假设这是最佳做法。

解决方案

JUnit有一个方法检查 Double / p>

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

请参阅此API文档



如评论,JUnit实际上最可能比比较手动与给定增量慢。 JUnit首先执行 Double.compare(expected,actual)后跟(如果不等于) Math.abs(expected - actual)< =希望这个答案对于没有意识到JUnit实际上提供了一个不精确的方法的人有用 Double / code>等同测试。


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.

解决方案

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.

这篇关于执行检查java.lang.Double的相等方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆