如何比较该双打序列都是“大致相等”的。在Java? [英] How to compare that sequence of doubles are all "approximately equal" in Java?
问题描述
我在java中有一个返回双数的方法,我想比较每次调用方法时返回的每个双数(比如说5次),这样我就可以得出结论返回的数字几乎是一样的每一次。
I have a method in java that returns a double number and I want to compare every double number that is returned every time I call the method(say 5 times), so that I can conclude that the number returned is almost the same every time.
我该怎么做?
推荐答案
您必须先确定几乎相同的含义。例如, java.lang.Math
中有一个名为 ulp(),给定一个double,返回该double和next之间的距离;即,该数字与任何其他数字之间的最小可能差异。您可以简单地比较两个双打之间的差异以及调用该方法的结果。
You must first decide what "almost the same" means. For example, there's a method in java.lang.Math
called ulp() which, given a double, returns the distance between that double and the next; i.e., the smallest possible difference between that number and any other. You might simply compare the difference between the two doubles and the result of calling that method.
另一方面,也许您希望两个数字仅在1%之内彼此。在这种情况下,执行相同的计算,但使用第一个数字乘以 0.01
而不是 ulp()
作为最大可接受距离。
On the other hand, maybe you want two numbers to just be within 1% of eachother. In that case, do the same computation, but use the first number multiplied by 0.01
instead of ulp()
as the largest acceptable distance.
这篇关于如何比较该双打序列都是“大致相等”的。在Java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!