2つのダブルスがほぼ等しいかどうかを判断するためにJavaコードを見つけようとしています。私はグーグルで多くのことをして、私がここにまとめたものを見つけました。私がエスケープし始めるところは「相対的イプシロン」の使用です。このアプローチは、私が探しているもののようです。私はイプシロンを直接指定する必要はないが、2つの引数の大きさに基づいてイプシロンを使用したいと思う。ここに私がまとめたコードがあります。私はそれについての健全性チェックが必要です。 (P.S.私は危険なことができるだけの数学を知っている。)2つのダブルスがほぼ等しいかどうかを調べる方法
public class MathUtils
{
// http://stackoverflow.com/questions/3728246/what-should-be-the-
// epsilon-value-when-performing-double-value-equal-comparison
// ULP = Unit in Last Place
public static double relativeEpsilon(double a, double b)
{
return Math.max(Math.ulp(a), Math.ulp(b));
}
public static boolean nearlyEqual(double a, double b)
{
return nearlyEqual(a, b, relativeEpsilon(a, b));
}
// http://floating-point-gui.de/errors/comparison/
public static boolean nearlyEqual(double a, double b, double epsilon)
{
final double absA = Math.abs(a);
final double absB = Math.abs(b);
final double diff = Math.abs(a - b);
if(a == b)
{
// shortcut, handles infinities
return true;
}
else if(a == 0 || b == 0 || diff < Double.MIN_NORMAL)
{
// a or b is zero or both are extremely close to it
// relative error is less meaningful here
// NOT SURE HOW RELATIVE EPSILON WORKS IN THIS CASE
return diff < (epsilon * Double.MIN_NORMAL);
}
else
{
// use relative error
return diff/Math.min((absA + absB), Double.MAX_VALUE) < epsilon;
}
}
}
1つのulpがおそらく小さ過ぎるεです。 –
どのように私はそれをバンプする必要がありますに関するお勧め? – careysb
ああ、@ルイスワッサーマンは、クラウスが言ったあなたのもののようです。 – careysb