29

Why float.NaN != double.NaN ?

while float.PositiveInfinity == double.PositiveInfinity and float.NegativeInfinity == double.NegativeInfinity are equal.

EXAMPLE:

bool PosInfinity = (float.PositiveInfinity == double.PositiveInfinity); //true
bool NegInfinity = (float.NegativeInfinity == double.NegativeInfinity); //true

bool isNanEqual = (float.NaN == double.NaN);  //false, WHY?
user
  • 5,119
  • 7
  • 45
  • 62
Javed Akram
  • 14,674
  • 24
  • 78
  • 117

3 Answers3

44

NaN is never equal to NaN (even within the same type). Hence why the IsNaN function exists:

Double zero = 0;
// This will return true.
if (Double.IsNaN(0 / zero)) 
{
    Console.WriteLine("Double.IsNan() can determine whether a value is not-a-number.");
}

You should also be aware that none of the comparisons you've shown are actually occurring "as is". When you write floatValue == doubleValue, the floats will actually be implicitly converted to doubles before the comparison occurs.

Damien_The_Unbeliever
  • 227,877
  • 22
  • 326
  • 423
29

Probably because NaN != NaN

Devin Jeanpierre
  • 87,853
  • 4
  • 54
  • 79
10

To quote wikipedia:

A comparison with a NaN always returns an unordered result even when comparing with itself.

Conrad Meyer
  • 2,810
  • 19
  • 24