#79 – Equality Checks for NaN

You should use the float and double static methods for checking for NaN values (E.g. float.isNaN), rather than using the equality operator.  The equality operator will not work to compare a value against double.NaN and float.NaN.

 // Easiest way--use static method
 bool b1 = double.IsNaN(0.0 / 0.0);     // true

 // == operator doesn't work
 bool b2 = (0.0 / 0.0) == double.NaN;   // false !

 // object.Equals does work
 bool b3 = object.Equals(0.0 / 0.0, double.NaN);
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

3 Responses to #79 – Equality Checks for NaN

  1. Peter Chamberlin says:

    The reason the equality operator == returns false is due to the IEEE 754 floating point standard stating that NaN compared to NaN should always be considered false.

  2. kai zhou says:

    Thank you for the knowledge Sean.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: