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

问题描述 投票:1回答:2

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

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

c# c++ double std
2个回答
3
投票
const long ExponentMask = 0x7FF0000000000000; static bool IsSubnormal(double v) { long bithack = BitConverter.DoubleToInt64Bits(v); if (bithack == 0) return false; return (bithack & ExponentMask ) == 0; } static bool IsNormal(double v) { long bithack = BitConverter.DoubleToInt64Bits(v); bithack &= ExponentMask; return (bithack != 0) && (bithack != ExponentMask); }

现在已经过测试。测试套件:
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); }

演示:http://rextester.com/DGMCM42070


0
投票

public static bool IsNormal(double d);

如果值正常,则返回true;否则,返回0。 false否则。
适用于

。NET Core 3.1、3.0、2.2、2.1

    。NET Standard 2.1
© www.soinside.com 2019 - 2024. All rights reserved.