Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find if two variables are approximately equals?

Tags:

c#

.net-3.5

I am writing unit tests that verify calculations in a database and there is a lot of rounding and truncating and stuff that mean that sometimes figures are slightly off.

When verifying, I'm finding a lot of times when things will pass but say they fail - for instance, the figure will be 1 and I'm getting 0.999999

I mean, I could just round everything into an integer but since I'm using a lot of randomized samples, eventually i'm going to get something like this

10.5 10.4999999999

one is going to round to 10, the other will round to 11.

How should I solve this problem where I need something to be approximately correct?

like image 819
Diskdrive Avatar asked Aug 06 '10 03:08

Diskdrive


People also ask

How do you check if two values are equal in C#?

You can use the == operator, as shown in the following example. int a = GetOriginalValue(); int b = GetCurrentValue(); // Test for value equality. if (b == a) { // The two integers are equal. }

How to check if two numbers are equal in JavaScript?

==) operator to check if two numbers are not equal to one another, e.g. a !== b . The strict inequality operator returns true if the numbers are not equal and false otherwise. Copied!


2 Answers

You could provide a function that includes a parameter for an acceptable difference between two values. For example

// close is good for horseshoes, hand grenades, nuclear weapons, and doubles static bool CloseEnoughForMe(double value1, double value2, double acceptableDifference) {     return Math.Abs(value1 - value2) <= acceptableDifference;  } 

And then call it

double value1 = 24.5; double value2 = 24.4999;  bool equalValues = CloseEnoughForMe(value1, value2, 0.001); 

If you wanted to be slightly professional about it, you could call the function ApproximatelyEquals or something along those lines.

static bool ApproximatelyEquals(this double value1, double value2, double acceptableDifference) 
like image 36
Anthony Pegram Avatar answered Sep 19 '22 14:09

Anthony Pegram


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.

like image 186
Mitch Wheat Avatar answered Sep 21 '22 14:09

Mitch Wheat