Why is double.NaN not equal to itself?

后端 未结 11 1216
心在旅途
心在旅途 2020-11-27 17:42

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 >=          


        
相关标签:
11条回答
  • 2020-11-27 18:07

    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);
    
    0 讨论(0)
  • 2020-11-27 18:10

    There's a specialized function for this:

    double.IsNan(huh);
    
    0 讨论(0)
  • 2020-11-27 18:10

    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.

    0 讨论(0)
  • 2020-11-27 18:11

    Use Double.IsNan() to test for equality here. The reason is that NaN is not a number.

    0 讨论(0)
  • 2020-11-27 18:15

    Use Double.IsNaN.

    0 讨论(0)
  • 2020-11-27 18:16

    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.

    0 讨论(0)
提交回复
热议问题