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,335
  • 7
  • 47
  • 63
Javed Akram
  • 15,024
  • 26
  • 81
  • 118

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
  • 234,701
  • 27
  • 340
  • 448
29

Probably because NaN != NaN

Devin Jeanpierre
  • 92,913
  • 4
  • 55
  • 79
10

To quote wikipedia:

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

Conrad Meyer
  • 2,851
  • 21
  • 24