65.9K
CodeProject is changing. Read more.
Home

C#: Never Test For NaN With Equality Test

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.56/5 (14 votes)

Jan 16, 2020

CPOL
viewsIcon

19733

downloadIcon

51

Never compare NaN with itself!

Let's write a simple program to test. To get a NaN, we do a 0/0 and store it in num. First of all, the divisor has to be a float-point type because DivideByZeroException shall be thrown for integer or decimal zero divisor. Note: Non-zero number divided by zero (float) gives an infinity number. In our program, we compare num to NaN and next, compare num to itself and then, we compare 2.0 to NaN. Lastly, we check if num is NaN with Double.IsNaN().

double num = 0.0 / 0.0; // Result of 0 divided by 0 is a NaN

Console.WriteLine("num == NaN is {0}", (num == double.NaN));
Console.WriteLine("num == num is {0}", (num == num));
Console.WriteLine("2.0 == NaN is {0}", (2.0 == double.NaN));
Console.WriteLine("double.IsNaN(num) is {0}", double.IsNaN(num));

This is the output. All the 3 NaN comparisons return False while IsNaN() check on num returns True. This is exactly the same behaviour with C++. The advice for this tip is never test for NaN with equality test, use IsNaN() instead.

num == NaN is False
num == num is False
2.0 == NaN is False
double.IsNaN(num) is True

If you are interested to know more about floating-point format, read my Succinct Guide to Floating Point Format For C++ and C# Programmers.

History

  • 16th January, 2020: Initial version