Re: Interesting behavior of double.NaN
Sébastien Lorion <[email protected]> Mon, 23 Mar 2009 11:44:23 -0400
| Newsgroups | gmane.comp.windows.devel.dotnet.advanced |
|---|---|
| Message-ID | <[email protected]> |
If NaN is used as a null indicator, maybe using Nullable<double> would be more appropriate. If you are worried that NaN may be passed as an argument to a function or may be the result of a prior calculation, testing if width >= 0 would allow you to catch those edge cases. Sébastien On Mon, Mar 23, 2009 at 10:40, 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 > =================================== View archives and manage your subscription(s) at http://peach.ease.lsoft.com/archives