Why is double.NaN not equal to itself?

后端 未结 11 1217
心在旅途
心在旅途 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:16

    Actually, you already found the way to check if a IEEE-754 floating point number is NaN: it is the only floating point value (or range of values, because there are several NaNs) that evaluates to False if compared to itself, i.e. :

    bool isNaN(double v) {
        return v != v;
    }
    

    Under the hood, the Double.IsNaN method might actually do the same thing. You should still use it, because the behavior is quite surprising to anybody who does not know about the FP standard.

    0 讨论(0)
  • 2020-11-27 18:27
    bool isNaN = Double.IsNaN(yourNumber)
    
    0 讨论(0)
  • 2020-11-27 18:31

    If you are curious, this is what Double.IsNaN looks like:

    public static bool IsNaN(double d)
    {
        return (d != d);
    }
    

    Funky, huh?

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

    Use the method "Double.IsNaN( value )" to check for this condition.

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

    The only thing that we know about NaN is that it's "Not a Number." That doesn't mean that it has a value that is associable with its state. For example:

    ∞ + (-∞) = NaN

    0/0 = NaN

    (∞ + (-∞)) <> (0/0)

    Here's some C# to demonstrate

    var infinity = 100d / 0;
    var negInfinity = -100d / 0;
    
    var notANumber = infinity + negInfinity;
    Console.WriteLine("Negative Infinity plus Infinity is NaN: {0}", double.IsNaN(notANumber));
    
    var notANumber2 = 0d / 0d;
    Console.WriteLine("Zero divided by Zero is NaN: {0}", double.IsNaN(notANumber2));
    
    Console.WriteLine("These two are not equal: {0}", notANumber == notANumber2);
    
    0 讨论(0)
提交回复
热议问题