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?
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?
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`
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.