double 中有多个 Nans 吗?

Are there multiple Nans in double?

此代码:

    double d = BitConverter.Int64BitsToDouble(long.MaxValue);
    Console.WriteLine(d);
    Console.WriteLine(double.IsNaN(d));
    Console.WriteLine(BitConverter.DoubleToInt64Bits(d) == BitConverter.DoubleToInt64Bits(double.NaN));

    NaN
    True
    False

这意味着 NaN 并不总是相同的双精度数,对吗?

根据 IEEE 754 标准,所有指数位为一且至少一个有效位为一的任何位模式都是 NaN。根据该规则,64 位浮点数有 253-2 个 NaN。

您没有指定语言。某些使用 IEEE 754 的语言或语言实现可能更喜欢 NaN 的特定位模式,并尝试将 NaN 强制为该模式。例如,Java Language Specification 表示:

For the most part, the Java SE platform treats NaN values of a given type as though collapsed into a single canonical value, and hence this specification normally refers to an arbitrary NaN as though to a canonical value.

要全面了解浮点运算在您的程序中的行为方式,您需要考虑适当的语言规则以及底层浮点实现。