C# Compare two double with .Equals()

我的未来我决定 提交于 2021-01-22 05:01:31

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/40653375/c-sharp-compare-two-double-with-equals

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!