如何在 C# 中检查给定的双精度数是否正常,即既不是零、次正规、无限也不是 NaN

Seb*_*idz 2 c# c++ double std

如何在 C# 中检查给定的双精度数是否正常,即既不是零、次正规、无限也不是 NaN。

在 C++ 中,有一个方法 std::isnormal 正是在检查这种情况。C# 中是否有等价物?

Mic*_*ter 6

.NET 的最新版本具有Double.IsNormal()

public static bool IsNormal(double d);
Run Code Online (Sandbox Code Playgroud)

true如果值正常则返回;false除此以外。

适用于

  • .NET 核心 3.1、3.0、2.2、2.1
  • .NET 标准 2.1

不幸的是 .NET Framework(直到 4.8)没有它。


Ben*_*igt 5

Mathias 在评论中给出了检测次正常值的基本方法。这里编码了:

const long ExponentMask = 0x7FF0000000000000;
static bool IsSubnormal(double v)
{
    if (v == 0) return false;
    long bithack = BitConverter.DoubleToInt64Bits(v);
    return (bithack & ExponentMask ) == 0;
}

static bool IsNormal(double v)
{
    long bithack = BitConverter.DoubleToInt64Bits(v);
    bithack &= ExponentMask;
    return (bithack != 0) && (bithack != ExponentMask);
}
Run Code Online (Sandbox Code Playgroud)

现在它已经过测试。测试套件:

static void TestValue(double d)
{
    Console.WriteLine("value is {0}, IsSubnormal returns {1}, IsNormal returns {2}", d, IsSubnormal(d), IsNormal(d));
}

static void TestValueBits(ulong bits)
{
    TestValue(BitConverter.Int64BitsToDouble((long)bits));
}

public static void Main(string[] args)
{
    TestValue(0.0);
    TestValue(1.0);
    TestValue(double.NaN);
    TestValue(double.PositiveInfinity);
    TestValue(double.NegativeInfinity);
    TestValue(double.Epsilon);
    TestValueBits(0xF000000000000000);
    TestValueBits(0x7000000000000000);
    TestValueBits(0xC000000000000000);
    TestValueBits(0x4000000000000000);
    TestValueBits(0xFFF0000000000005);
    TestValueBits(0x7FF0000000000005);
    TestValueBits(0x8010000000000000);
    TestValueBits(0x0010000000000000);
    TestValueBits(0x8001000000000000);
    TestValueBits(0x0001000000000000);
}
Run Code Online (Sandbox Code Playgroud)

演示:https : //rextester.com/CMFOR3934