Interesting behavior of double.NaN

"Brink, Paul ten" <[email protected]> Mon, 23 Mar 2009 15:40:42 +0100
Newsgroups gmane.comp.windows.devel.dotnet.advanced
Message-ID <D64DDB436E7D0F44AE255474D6320CCA6C9D941A35@NLCLUEXM03.connect1.local>
Hello,

After a long search I finally found why my program is not working properly: double.NaN != double.NaN

You can try this for yourself in the Quick Watch window.

This interesting behavior is by design. From the documentation:

----------------------------
Double.NaN Field

Represents a value that is not a number (NaN). This field is constant.

Use IsNaN<http://msdn.microsoft.com/en-us/library/system.double.isnan.aspx> to determine whether a value is not a number. It is not possible to determine whether a value is not a number by comparing it to another value equal to NaN.
----------------------------

Hm, a constant that is not equal to itself. Interesting...

But it is very dangerous:

If (width != this.Width)

returns true if both are double.NaN

Don't say Microsoft did not warn you...     ;-)

I now use:

private bool DoubleEquals(double d1, double d2)
{
    bool result = false;

    bool isNaN1 = double.IsNaN(d1);
    bool isNaN2 = double.IsNaN(d2);

    if (isNaN1)
    {
        result  = isNaN2;
    }
    else
    {
        if (! isNaN2)
        {
            result = (d1 == d2);
        }
    }

    return result;
}

Paul ten Brink
[email protected]

________________________________
The information contained in this message may be confidential and legally protected under applicable law. The message is intended solely for the addressee(s). If you are not the intended recipient, you are hereby notified that any use, forwarding, dissemination, or reproduction of this message is strictly prohibited and may be unlawful. If you are not the intended recipient, please contact the sender by return e-mail and destroy all copies of the original message.

===================================
View archives and manage your subscription(s) at http://peach.ease.lsoft.com/archives