1

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?

2 Answers 2

6

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` 
Sign up to request clarification or add additional context in comments.

2 Comments

This is good, but picking a reasonable value for some_epsilon is tricky.
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.
3

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.

3 Comments

+1, but perhaps worth noting the difference in your function to standard equality (NaN != NaN)
oh and do you want Positive and Negative infinity to be considered equal?
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).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.