Как проверить С#, если данный двойной номер является нормальным, то есть не равен нулю, субнормальным, бесконечным или NaN.
В C++ существовал метод std :: isnormal, который точно проверял это условие. Есть ли эквивалент в С#?
Матиас дал базовый подход к обнаружению субнормальных значений в комментарии. Здесь он закодирован:
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);
}
IsNormal
нулевую тестовую строку из IsNormal
.
IsNaN
иIsInfinity
.