Blog

Filter posts by Category Or Tag of the Blog section!

Never compare double with == operator in C#

Thursday, 04 July 2019

In C#, it is not recommended to compare two doubles using the == operator because of the way that floating point numbers are represented and handled by the computer. Floating point numbers are represented as a finite number of bits, and this representation is not always exact. This can lead to issues with precision and accuracy when comparing floating point numbers.

For example, two numbers that should be equal might not have exactly the same representation in memory due to rounding errors, leading to unexpected results when using the == operator. Instead of using the == operator to compare doubles, it is recommended to use a comparison function that takes into account the potential for small differences in the representation of floating point numbers. One such function is System.Math.Approximately(), which compares two doubles with a small tolerance for differences between them:

 

double a = 1.23456;

double b = 1.23456;



if (Math.Abs(a - b) < 0.00001)

{

    Console.WriteLine("a and b are approximately equal");

}

 

This code compares two doubles a and b with a tolerance of 0.00001, and considers them equal if their difference is within that tolerance. By using a tolerance value, you can avoid issues with floating point precision and ensure that your comparisons are accurate. Take a look at another example of floating point rounding errors:

 

double a = 0.1 + 0.2;

double b = 0.3;

Console.WriteLine(a == b); // false


As I mentioned it’s because of the way that computers represent floating point numbers. In this case, a and b should be equal, but the rounding errors introduced by the floating point arithmetic cause them to be slightly different. Comparing them with the == operator would result in a false comparison. But if we compare the above code with Approximately() the result would be different:
 

double a = 0.1 + 0.2;

double b = 0.3;



if (System.Math.Approximately(a, b))

{

    Console.WriteLine("a and b are approximately equal");

}

else

{

    Console.WriteLine("a and b are not approximately equal");

}

Category: Software

Tags: C#

comments powered by Disqus