Floating point equivalence?

邮差的信 提交于 2020-01-14 03:11:08

问题


I want to be able to compare two doubles disregarding a possible precision loss. Is there a method already that handles this case?

If not, is there a threshold/guideline to know how much is an adequate equivalence between two doubles?


回答1:


The threshold is completely dependent to the problem itself. For some problems, you might consider 1.001 equal to 1.002 and for some problems, you might need a much smaller threshold.

The general techique is:

Math.Abs(a - b) < some_epsilon    // `a` is roughly equivalent to `b`



回答2:


A very good, thorough option for this is:

public static bool DoubleEquality(double a, double b) 
{
    const double epsilonValue = 1e-15;
    if (double.IsNaN(a))
        return double.IsNaN(b);
    else if (double.IsInfinity(a))
        return double.IsInfinity(b);
    else if (a == 0) 
        return b == 0;
    else
        return Math.Abs(a - b) <= Math.Abs(a * epsilonValue);
}

Note that Double.Epsilon is NOT a good epsilon value for this. This creates an epsilon that scales somewhat with the magnitude of your first value, which helps quite a bit.



来源:https://stackoverflow.com/questions/1202903/floating-point-equivalence

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!