Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Compare two double with .Equals()

Tags:

c#

compare

double

I use ReShaper and when I compare two double values with ==, it suggests that I should use the Math. ABS method with a tolerance. See: https://www.jetbrains.com/help/resharper/2016.2/CompareOfFloatsByEqualityOperator.html

This example

double d = 0.0;
double d2 = 0.0;
if (d == d2)
{
    /* some code */
}

is then converted to

double d = 0.0;
double d2 = 0.0;
if (Math.Abs(d - d2) < TOLERANCE)
{
    /* some code */
}

But I think it's really complicated for a developer to think about the right tolerance. So I thought this may be implemented in the Double.Equals() method.

But this method is implemented like so

public override bool Equals(Object obj) {
    if (!(obj is Double)) { 
        return false;
    } 
    double temp = ((Double)obj).m_value; 
    // This code below is written this way for performance reasons i.e the != and == check is intentional.
    if (temp == m_value) { 
        return true;
    }
    return IsNaN(temp) && IsNaN(m_value);
}

public bool Equals(Double obj)
{ 
    if (obj == m_value) {
        return true; 
    } 
    return IsNaN(obj) && IsNaN(m_value);
}

Why is that? And what is the correct way to compare double values?

like image 862
Leon Husmann Avatar asked Nov 17 '16 11:11

Leon Husmann


1 Answers

You could create an extension method

public static class DoubleExtension 
{
    public static bool AlmostEqualTo(this double value1, double value2)
    {
        return Math.Abs(value1 - value2) < 0.0000001; 
    }
}

And use it like this

doubleValue.AlmostEqualTo(doubleValue2)
like image 186
Jan-Fokke Avatar answered Oct 11 '22 20:10

Jan-Fokke