我怎么能在两个双打比较中平等?

时间:2015-11-05 09:52:58

标签: java

在我的代码中:

else if (returnShortestTime() == shortTime[1])

方法returnShortestTime返回最小的double,并与存储的double进行比较,因为这并不是简单地使用double A == double B我如何比较代码中的两个双精度数以查看它们是否相等?

1 个答案:

答案 0 :(得分:2)

一般而言,您实际上可以在Java中使用==作为原始数据类型。将浮点数与相等性进行比较通常不是一个好主意的原因是floating point precision error。有两种解决方案可以比较两个浮点数(双精度)的相等性,你可以使用Java BigDecimal或者检查这两个数字之间的差异是否小于某个阈值(这通常称为Epsilon value)。

使用BigDecimal

BigDecimal foo = new BigDecimal(returnShortestTimeAsString() /*String Representation of your returnShortestTime() method*/);
BigDecimal bar = new BigDecimal(shortTimeAsString[1] /*String Representation of this array value*/);
if(foo.compareTo(bar) == 0 /*If they are equal*/) doStuff();

使用Epsilon

if(Math.abs(returnShortestTime() - shortTime[1]) < Math.ulp(1.0) /*This is the Epsilon value*/) doStuff();
相关问题