How do I find if two variables are approximately equals?

Define a tolerance value (aka an ‘epsilon’ or ‘delta’), for instance, 0.00001, and then use to compare the difference like so:

if (Math.Abs(a - b) < delta)
{
   // Values are within specified tolerance of each other....
}

You could use Double.Epsilon but you would have to use a multiplying factor.

Better still, write an extension method to do the same. We have something like Assert.AreSimiliar(a,b) in our unit tests.

Microsoft’s Assert.AreEqual() method has an overload that takes a delta: public static void AreEqual(double expected, double actual, double delta)

NUnit also provides an overload to their Assert.AreEqual() method that allows for a delta to be provided.

Leave a Comment