Few days ago, I was in a situation where I was stuck in a scenario when I had to compare two double type variables for equality in IF statement clause.
Now sounds simple, but when our smart visual studio starts complaining about our code with wiggly under lines we know some things not right.
Problem: I take two double variables and assign them values with large decimal values.
Upon comparison of these values, my logic seemed incorrect as double and float are floating types variable which did not accurately represented my numbers during run time.
Then how can I guarantee that the comparison would happen robust all the time with varied data values and under different scenarios.
Solution: The solution was more geared towards simple mathematics, with degree of freedom specified beforehand as follows.
class Program { private static double EPSILON = 0.000001; static void Main(string[] args) { double valueA, valueB; valueA = 22.12345678910236; valueB = 22.12345678910233; if (Math.Abs(valueA - valueB) < EPSILON) { System.Diagnostics.Debug.WriteLine("The decimal objects are equal."); } else { System.Diagnostics.Debug.WriteLine("The decimal objects are NOT equal."); } } }
With the above logic one has to specify the level of accuracy before hand for the program being developed, and this would be the most accurate way to make the program robust.
Some suggest why you don’t opt for Decimal data types instead of all the hassles of arithmetic evaluation of Double or Float’s?
My answer to them would be, “Why would you use a sword to kill a fly” as the saying goes.
Surely use decimal when accuracy is critical like financial/medical applications, but one has to pay the high price of memory used up by decimals.
Whereas double and floats come in handy for GUI/Assitive applications where near approximation wouldn’t do much harm, and the performance is also optimal by the fractions of memory saves for each variable declared by the same.
Use the right tool for the purpose, with the right knowledge in place.
References:
http://msdn.microsoft.com/en-us/library/47zceaw7%28v=vs.71%29.aspx