1.#QNAN、1.#IND和1.#INF等「無效」浮點數說明及其判斷

在GIS視圖上發現部分小區不能正常呈現,經過跟蹤異常小區發現其所屬基站的經緯度座標都是-1.#QNAN00000000000無效值,致使小區繪製失敗,這些小區均屬新入網的3G基站,資源數據尚未維護起來,數據庫中對應字段爲空,通過TUXEDO接口後數據反映爲QNAN無效值。在基礎數據完善以前,可在SQL取數據時將空值轉化爲0,或在接收數據時對此類數據做進一步的過濾。
此處的1.#QNAN是一個打印呈現,QNAN是指Quiet Not a Number,相似的浮點錯誤還有SNaN(Signaling Not a Number),一般如0.0/0.0、給負數開平方根等溢出或無效運算就會產生一個NAN結果的表示值,NaN及兩種浮點錯誤的說明以下:
The value NaN (Not a Number) is used to represent a value that does not represent a real number. NaN’s are represented by a bit pattern with an exponent of all 1s and a non-zero fraction. There are two categories of NaN: QNaN (Quiet NaN) and SNaN (Signalling NaN).
QNaN is a NaN with the most significant fraction bit set. QNaN’s propagate freely through most arithmetic operations. These values pop out of an operation when the result is not mathematically defined.
An SNaN is a NaN with the most significant fraction bit clear. It is used to signal an exception when used in operations. SNaN’s can be handy to assign to uninitialized variables to trap premature usage.
Semantically, QNaN’s denote indeterminate operations, while SNaN’s denote invalid operations. If a return value is a QNaN, it means that it is impossible to determine the result of the operation, a SNaN means that the operation is invalid.
這樣的特殊浮點數還有INF和IND:INF就是Infinity,表示一個無窮大的數,包括正無窮和負無窮;IND則表示無限小,但不肯定。如1.0/0.0會產生一個INF無窮大,-1.0/0.0會產生一個負無窮大。

回到最初的錯誤上,這種無效數據之因此經過了經緯度有效值判斷,是由於常規的浮點範圍對這類浮點數無效。咱們知道常規的浮點數不能直接判0等於,而若是這個浮點數爲NaN,那if (f==f) 會獲得false結果。可是利用這個結果來判斷一個浮點數是否爲NaN並不老是安全的,例如用這個宏定義#define isnan(x) ((x) != (x)) ,在某些編譯環境下可能就會脫離了你的預期。那如何判斷特殊的浮點數呢?各類語言應該都能找到對應的輔助函數或者類方法,在C語言中,能夠用float.h中的int _isnan(double x)、int _finite(double x)、int _fpclass(double x)函數來判斷,返回結果表明意義分別爲:_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()等方法。
相關文章
相關標籤/搜索