views:

78

answers:

2

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?

+6  A: 

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`
Mehrdad Afshari
This is good, but picking a reasonable value for some_epsilon is tricky.
Reed Copsey
Indeed it's tricky; and no general recommendation works. Personally, I've experienced its trickiness in ACM/ICPC geometry questions and those that require binary searching the solution space.
Mehrdad Afshari
+3  A: 

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.

Reed Copsey
+1, but perhaps worth noting the difference in your function to standard equality (NaN != NaN)
ShuggyCoUk
oh and do you want Positive and Negative infinity to be considered equal?
ShuggyCoUk
Yeah - it's easy to add some extra checks, depending on your conditions. I've also taken out the 0 check at times, although that requires changing the last line slightly. (Currently, 0!=1e-20, which you may want to be equal).
Reed Copsey