Can someone explain this to me? In C# double.NaN is not equal to double.NaN
bool huh = double.NaN == double.NaN; // huh = false
bool huh2 = double.NaN >=
The reason of Double.NaN != Double.NaN
is simple:
Do you expect 0/0
to be the same as Math.Sqrt(-3)
? And same as Math.Sqrt(-7)
?
There is a bug in C# in my opinion where Equals()
is not overridden for NaN.
Assert.IsTrue(Double.NaN != Double.NaN);
Assert.IsTrue(Double.NaN.Equals(Double.NaN));
At the same time
Assert.IsTrue(Double.PositiveInfinity == Double.NegativeInfinity);
Assert.IsTrue(Double.PositiveInfinity.Equals(Double.PositiveInfinity));
// same for Double.NegativeInfinity and Single
Use static functions for Double
and Single
, e.g.
Double.IsNaN(value) && Double.IsInfinity(value);
Or more specific:
Double.IsPositiveInfinity(value);
Double.IsNegativeInfinity(value);
There's a specialized function for this:
double.IsNan(huh);
The Equality operator considers two NaN values to be unequal to one another. In general, Double operators cannot be used to compare Double.NaN with other Double values, although comparison methods (such as Equals and CompareTo) can. see below examples
Referenced from msdn
class Program
{
static void Main(string[] args)
{
Double i = Double.NaN;
while (!i.Equals(i)) //this would be result in false
//while(i != i) // this would result in true.
{
Console.WriteLine("Hello");
}
}
}
here is .net fiddle for the same.
Use Double.IsNan() to test for equality here. The reason is that NaN is not a number.
Use Double.IsNaN.
The behavior is on purpose. The reason being NaN represents something that is not a number and so that is sort of a catch-all for many things.
The proper way to compare something to being NaN is to use the IsNaN function.