是否存在isnan()函数?
注:我在MinGW(如果这有区别的话)。
我使用isnan()从<math.h>解决了这个问题,这在<cmath>中不存在,我一开始是#包括在内的。
是否存在isnan()函数?
注:我在MinGW(如果这有区别的话)。
我使用isnan()从<math.h>解决了这个问题,这在<cmath>中不存在,我一开始是#包括在内的。
当前回答
inline bool IsNan(float f)
{
const uint32 u = *(uint32*)&f;
return (u&0x7F800000) == 0x7F800000 && (u&0x7FFFFF); // Both NaN and qNan.
}
inline bool IsNan(double d)
{
const uint64 u = *(uint64*)&d;
return (u&0x7FF0000000000000ULL) == 0x7FF0000000000000ULL && (u&0xFFFFFFFFFFFFFULL);
}
如果sizeof(int)为4,sizeof(long long)为8,则此方法有效。
在运行时,它只是比较,类型转换不需要任何时间。它只是改变比较标志配置来检查是否相等。
其他回答
在我看来,最好的真正跨平台的方法是使用联合,并测试double的位模式来检查nan。
我还没有彻底测试这个解决方案,可能有一种更有效的方法来处理比特模式,但我认为它应该有效。
#include <stdint.h>
#include <stdio.h>
union NaN
{
uint64_t bits;
double num;
};
int main()
{
//Test if a double is NaN
double d = 0.0 / 0.0;
union NaN n;
n.num = d;
if((n.bits | 0x800FFFFFFFFFFFFF) == 0xFFFFFFFFFFFFFFFF)
{
printf("NaN: %f", d);
}
return 0;
}
这可以在Visual Studio中通过检查它是否在双重限制范围内来检测无穷大和NaN:
//#include <float.h>
double x, y = -1.1; x = sqrt(y);
if (x >= DBL_MIN && x <= DBL_MAX )
cout << "DETECTOR-2 of errors FAILS" << endl;
else
cout << "DETECTOR-2 of errors OK" << endl;
可以使用isnan()函数,但需要包含C数学库。
#include <cmath>
因为这个函数是C99的一部分,所以并不是所有地方都可用。如果您的供应商没有提供该功能,您也可以定义自己的变体以实现兼容性。
inline bool isnan(double x) {
return x != x;
}
inline bool IsNan(float f)
{
const uint32 u = *(uint32*)&f;
return (u&0x7F800000) == 0x7F800000 && (u&0x7FFFFF); // Both NaN and qNan.
}
inline bool IsNan(double d)
{
const uint64 u = *(uint64*)&d;
return (u&0x7FF0000000000000ULL) == 0x7FF0000000000000ULL && (u&0xFFFFFFFFFFFFFULL);
}
如果sizeof(int)为4,sizeof(long long)为8,则此方法有效。
在运行时,它只是比较,类型转换不需要任何时间。它只是改变比较标志配置来检查是否相等。
有三种“正式”的方法:posix isnan宏,c++0x isnan函数模板,或visual c++ _isnan函数。
不幸的是,要检测使用哪一种是相当不切实际的。
不幸的是,没有可靠的方法来检测是否有IEEE 754表示的nan。标准库提供了一种正式的方法(numeric_limits<double>::is_iec559)。但在实践中,g++之类的编译器会搞砸这一点。
理论上,我们可以简单地使用x != x,但g++和visual c++之类的编译器却搞砸了。
因此,最后,测试特定的NaN位模式,假设(并希望在某些时候强制执行!)一个特定的表示,例如IEEE 754。
编辑:作为一个“像g++这样的编译器……搞砸了”的例子,考虑一下
#include <limits>
#include <assert.h>
void foo( double a, double b )
{
assert( a != b );
}
int main()
{
typedef std::numeric_limits<double> Info;
double const nan1 = Info::quiet_NaN();
double const nan2 = Info::quiet_NaN();
foo( nan1, nan2 );
}
使用g++ (TDM-2 mingw32) 4.4.1编译:
C:\test> type "C:\Program Files\@commands\gnuc.bat" @rem -finput-charset=windows-1252 @g++ -O -pedantic -std=c++98 -Wall -Wwrite-strings %* -Wno-long-long C:\test> gnuc x.cpp C:\test> a && echo works... || echo !failed works... C:\test> gnuc x.cpp --fast-math C:\test> a && echo works... || echo !failed Assertion failed: a != b, file x.cpp, line 6 This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information. !failed C:\test> _