.NET 的最新版本具有Double.IsNormal():
Run Code Online (Sandbox Code Playgroud)public static bool IsNormal(double d);
true如果值正常则返回;false除此以外。适用于
- .NET 核心 3.1、3.0、2.2、2.1
- .NET 标准 2.1
不幸的是 .NET Framework(直到 4.8)没有它。
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
| 归档时间: |
|
| 查看次数: |
1993 次 |
| 最近记录: |