Re: Interesting behavior of double.NaN
Peter Ritchie <[email protected]> Mon, 23 Mar 2009 14:34:53 -0400
| Newsgroups | gmane.comp.windows.devel.dotnet.advanced |
|---|---|
| Message-ID | <LISTSERV%[email protected]> |
In addition to what other's have said, I would be very careful in deciding whether NaN == NaN makes sense in your scenario. The reason a NaN value is neither equal to or not equal to another NaN value is because NaN doesn't represent a real value. For example, you're saying DoubleEquals(Math.Sqrt(-1.0), Math.Sqrt(-10000.0)); ...will be true. Conceptually the result of the square of two different values should not be equal (in a perfect world where rounding error didn't exist). -- Peter On Mon, 23 Mar 2009 15:40:42 +0100, 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; >} > =================================== View archives and manage your subscription(s) at http://peach.ease.lsoft.com/archives