【Z】1.#QNAN、1.#IND和1.#INF等“…

来源:互联网 发布:日用品数据分析网站 编辑:程序博客网 时间:2024/05/15 08:17
首先说明:1.#QNAN是一个打印呈现,QNAN是指QuietNot a Number,类似的浮点错误还有SNaN(Signaling Not aNumber),通常如0.0/0.0、给负数开平方根等溢出或无效运算就会产生一个NAN结果的表示值。

NaN及两种浮点错误的说明如下:
The value NaN (Not a Number) is used to represent a value that doesnot represent a real number. NaN’s are represented by a bitpattern with an exponent of all 1s and a non-zero fraction. Thereare two categories of NaN: QNaN (Quiet NaN) and SNaN (SignallingNaN).A QNaN is a NaN with the most significant fraction bit set.QNaN’s propagate freely through most arithmetic operations. Thesevalues pop out of an operation when the result is notmathematically defined.An SNaN is a NaN with the most significantfraction bit clear. It is used to signal an exception when used inoperations. SNaN’s can be handy to assign to uninitializedvariables to trap premature usage.Semantically, QNaN’s denoteindeterminate operations, while SNaN’s denote invalid operations.If a return value is a QNaN, it means that it is impossible todetermine the result of the operation, a SNaN means that theoperation is invalid.
  这样的特殊浮点数还有INF和IND:INF就是Infinity,表示一个无穷大的数,包括正无穷和负无穷;IND则表示无限小,但不确定。如1.0/0.0会产生一个INF无穷大,-1.0/0.0会产生一个负无穷大。 
  之所以会出现这种错误,是因为常规的浮点范围对这类浮点数无效。我们知道常规的浮点数不能直接判0等于,而如果这个浮点数为NaN,那if(f==f)会得到false结果。但是利用这个结果来判断一个浮点数是否为NaN并不总是安全的,例如用这个宏定义#defineisnan(x) ((x) != (x)),在某些编译环境下可能就会脱离了你的预期。

那如何判断特殊的浮点数呢?

各种语言应该都能找到对应的辅助函数或者类方法.
在C语言中,可以用float.h中的int _isnan(double x)、int_finite(double x)、int _fpclass(doublex)函数来判断,返回结果代表意义分别为:_FPCLASS_SNAN(Signaling NaN)、_FPCLASS_QNAN (Quiet NaN)、_FPCLASS_NINF(Negative Infinity, –INF)、_FPCLASS_PINF (Positive Infinity,+INF);
在C++中,可以用STL中的limits类:numeric_limits::quiet_NaN()、numeric_limits::signaling_NaN()、numeric_limits::infinity()等方法。

 更多信息可参考下面的文章:
http://www.ibm.com/developerworks/cn/java/j-jtp0114/
http://steve.hollasch.net/cgindex/coding/ieeefloat.html
http://www.topcoder.com/tc?module=Static&d1=tutorials&d2=integersReals2