首页 > 解决方案 > 为什么 double.IsNegative(double.NaN) 返回 true?

问题描述

为什么double.IsNegative(double.NaN)意外返回true而按预期double.NaN < 0返回false

标签: c#floating-pointdouble

解决方案


好吧,根据参考来源double.IsNegative只需检查最重要的位

    [Pure]
    [System.Security.SecuritySafeCritical]  // auto-generated
    internal unsafe static bool IsNegative(double d) {
        return (*(UInt64*)(&d) & 0x8000000000000000) == 0x8000000000000000;
    }

如果设置double.NaN最重要的位:

    11111111 11111000 00000000 00000000 00000000 00000000 00000000 00000000   
    ||           ||                                                       |
    |<-   Exp   -><-                     Mantissa                        ->
    Sign

这就是为什么double.IsNegative返回true

当我们使用 put<> FPU命令时,这些命令都知道指数一种特殊的浮点值,应该以特殊的方式处理。

同样的图片与Single.NaN.

请注意,我们可以构造另一个奇怪的值,负零

    10000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000   
    ||           ||                                                       |
    |<-   Exp   -><-                          Mantissa                   ->
    Sign

敬请期待:

  double negativeZero = BitConverter.ToDouble(new byte[] { 
    0, 0, 0, 0, 0, 0, 0, 128
  });

  Console.WriteLine(negativeZero == 0 ? "Zero" : "???");

  Console.WriteLine(double.IsNegative(negativeZero) ? "Negative" : "???");

推荐阅读