Rule of thumb to test the equality of two doubles in C#?

后端 未结 6 1905
忘掉有多难
忘掉有多难 2020-12-06 17:00

Let\'s say I have some code that does some floating point arithmetic and stores the values in doubles. Because some values can\'t be represented perfectly in binary, how do

6条回答
  •  感情败类
    2020-12-06 17:03

    double d1 = GetRandomDouble();
    double d2 = GetRandomDouble();
    
    if (Math.Abs(d1 - d2) < double.Epsilon)
    {
       // the doubles are equal
    }
    

    Note that in practice this code is equivalent to just d1 == d2, because epsilon is defined as the smallest possible positive value > 0. Thus you'll never have a value between 0 and epsilon, and if you have the kind of rounding/precision error that would cause problems with the == operator you'll see it here, too.

    But what you can do is use the technique to define your own precision level — you're own epsilon. I would expect double.Equals() to have an overloaded for this technique, but the documentation is clear that one strangely does not exist. So let's make our own:

    public static bool IsEqual(this double d1, double d2, unsigned int precisionFactor)
    {
       return Math.Abs(d1 - d2) < precisionFactor * double.Epsilon;
    }
    

提交回复
热议问题