Re: Interesting behavior of double.NaN

Sam Baskinger <[email protected]> Mon, 23 Mar 2009 13:25:57 -0500
Newsgroups gmane.comp.windows.devel.dotnet.advanced
Message-ID <[email protected]>
Reminds me very much of how in SQL NULL is equal to NULL, nor is it
not-equal to a number. Thanks for sharing this!

Sam

On Mon, Mar 23, 2009 at 9:40 AM, Brink, Paul ten <[email protected]
> wrote:

> 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
>



-- 
"For it is a doctrine not of the tongue but of life.  It is not apprehended
by the understanding and memory alone, as other disciplines are, but it is
received only when it possesses the whole soul, and finds a seat and resting
place in the inmost affection of the heart."

John Calvin, The Institutes, Book III, Chapter VI, Section 4.

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