Java 双重比较

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11390853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 04:53:46  来源:igfitidea点击:

Java Double Comparison

javadouble

提问by DD.

Are there any java libraries for doing double comparison? e.g.

是否有任何用于进行双重比较的 Java 库?例如

public static boolean greaterThanOrEqual(double a, double b, double epsilon){
     return a - b > -epsilon;
}

Every project I start I end up re-implementing this and copy-pasting code and test.

我开始的每个项目最终都会重新实现并复制粘贴代码和测试。

NB a good example of why its better to use 3rd party JARs is that IBM recommend the following:

请注意,为什么最好使用 3rd 方 JAR 的一个很好的例子是 IBM 推荐以下内容:

"If you don't know the scale of the underlying measurements, using the test "abs(a/b - 1) < epsilon" is likely to be more robust than simply comparing the difference"

“如果您不知道基础测量的规模,使用测试“abs(a/b - 1) < epsilon”可能比简单地比较差异更可靠”

I doubt many people would have thought of this and illustrates that even simple code can be sub-optimal.

我怀疑很多人会想到这一点,并说明即使是简单的代码也可能是次优的。

回答by Lucian Enache

In the standard Java library there are no methods to handle your problem actually I suggest you to follow Joachim's link and use that library which is quite good for your needs, even though my suggestion would be to create an utils library in which you could add frequently used methods as the one you've stated in your question, as for different implementations of your problem you should consider looking into this :

在标准 Java 库中,实际上没有任何方法可以处理您的问题,我建议您遵循 Joachim 的链接并使用该库,这非常适合您的需求,尽管我的建议是创建一个您可以经常添加的 utils 库使用方法作为您在问题中陈述的方法,至于您的问题的不同实现,您应该考虑研究:

Java double comparison epsilon

Java双重比较epsilon

Feel free to ask out any other ambiguities

随意提出任何其他歧义

回答by Franz D.

You should abstain from any library that uses the naive "maximum absolute difference" approach (like Guava). As detailed in the Bruce Dawson's excellent article Comparing Floating Point Numbers, 2012 edition, it is highly error-prone as it only works for a very limited range of values. A much more robust approach is to use relative differences or ULPs for approximate comparisons.

您应该避免使用任何使用天真的“最大绝对差异”方法的库(如 Guava)。正如 Bruce Dawson 的优秀文章Comparing Floating Point Numbers, 2012 edition 中详述的那样,它非常容易出错,因为它只适用于非常有限的值范围。更可靠的方法是使用相对差异或 ULP 进行近似比较。

The only library I know of that does implement a correct approximate comparison algorithm is apache.common.math.

我所知道的唯一实现正确近似比较算法的库是apache.common.math.