我在一个几乎没有双/数学库(NETMF)的环境中工作。我写这篇课程是为了让事情变得更轻松:
public struct DoubleEx
{
public const double NaN = 0.0d / 0.0d;
public static bool IsNaN(double x)
{
return x != x;
}
...
}
好像应该有用,对吧?
好吧,当我运行此代码时:
Debug.Print("Method call: " + DoubleEx.IsNaN(DoubleEx.NaN));
Debug.Print("Method call: " + DoubleEx.NaN != DoubleEx.NaN);
我得到了这个输出:
False
True
不知何故,把它放在一个函数中的行为打破了它!这里有什么样的优化吗?或硬件是否误解了指令?
答案 0 :(得分:3)
以下内容基于IEEE标准754:
// @struct IEEE_DOUBLEREP | allows bit access to 8 byte floats
//[StructLayout(LayoutKind.Sequential)]
//public struct ieee_doublerep
//{
// ulong low_mantissa; // @field low 16 bits of mantissa
// ushort mid_mantissa; // @field mid 16 bits of mantissa
// uint high_mantissa:4; // @field high 4 bits of mantissa
// uint exponent:11; // @field exponent of floating point number
// uint sign:1; // @field sign of floating point number
//};
public struct DoubleEx
{
public const long NANMASK = 0x7FF0000000000000;
public const long INFINITYMASK = 0x000FFFFFFFFFFFFF;
public const double NaN = 0.0f / 0.0f;
public const double NegativeInfinity = -1.0f / 0.0f;
public const double PositiveInfinity = 1.0f / 0.0f;
public static bool IsNaNBad(double x)
{
return x != x;
}
public unsafe static bool IsNaN(double value)
{
long rep = *((long*)&value);
return ((rep & NANMASK) == NANMASK &&
((rep & INFINITYMASK) != 0));
}
public unsafe static bool IsPositiveInfinity(double value)
{
double negInf = DoubleEx.PositiveInfinity;
return *((long*)&value) == *((long*)&negInf);
}
public unsafe static bool IsNegativeInfinity(double value)
{
double posInf = DoubleEx.PositiveInfinity;
return *((long*)&value) == *((long*)&posInf);
}
public unsafe static bool IsInfinite(double x)
{
long rep = *((long*)&x);
return ((rep & NANMASK) == NANMASK &&
((rep & INFINITYMASK) == 0));
}
}
答案 1 :(得分:0)
您有一个运算符优先级问题,并将其置于函数内会更改表达式。
尝试:
Debug.Print("Method call: " + (DoubleEx.NaN != DoubleEx.NaN));
那怎么样:
static bool DoubleInequal(double a, double b) { return a != b; }
static bool IsNaN(double x) { return DoubleInequal(x, x + 0.0); }
答案 2 :(得分:-1)
你试过return x == NaN
吗?假设x!= x与“IsNaN”同义,对我来说似乎不是一种好习惯。