IEEE float 的 NaN 是出於什麼理由設計的?

整數出現零除錯誤會觸發一個 trap,相似的情況下浮點數用一個 NaN 來取代了是出於什麼樣的理由呢

NaN 浪費了許多編碼,都用來表示一個值,這些編碼是不是利用起來更好呢

最後 NaN 破壞了浮點數類型的全序性,引入了不少 bug,甚至許多編程語言的 sort 對於有 NaN 的值不能正確地處理,這值得嗎


使浮點數的運算具有封閉性。同時解決浮點數標準前作為未初始化數據的初始值的替代。

There are three kinds of operations that can return NaN:[4]

Operations with a NaN as at least one operand.

Indeterminate forms:

The divisions 0/0 and ±∞/±∞.

The multiplications 0×±∞ and ±∞×0.

The additions ∞ + (?∞), (?∞) + ∞ and equivalent subtractions.

The standard has alternative functions for powers:

The standard pow function and the integer exponent pown function define 00, 1∞, and ∞0 as 1.

The powr function defines all three indeterminate forms as invalid operations and so returns NaN.

Real operations with complex results, for example:

The square root of a negative number.

The logarithm of a negative number.

The inverse sine or cosine of a number that is less than ?1 or greater than +1.

NaNs may also be explicitly assigned to variables, typically as a representation for missing values. Prior to the IEEE standard, programmers often used a special value (such as ?99999999) to represent undefined or missing values, but there was no guarantee that they would be handled consistently or correctly.

NaNs are not necessarily generated in all the above cases. If an operation can produce an exception condition and traps are not masked then the operation will cause a trap instead.[5] If an operand is a quiet NaN, and there isn"t also a signaling NaN operand, then there is no exception condition and the result is a quiet NaN. Explicit assignments will not cause an exception even for signaling NaNs.

參見:NaN | Wikiwand

另外NaN還分為Quiet NaN與Signaling NaN


1. 沒有浪費編碼,浮點數用小數+指數表示的,小數為0指數非0,為nan。

2.實數有很多函數有定義域要求,不滿足定義域應該返回nan,比如sqrt(-1),acos(2)。


個人理解:就是為了讓你拋出錯誤用的。

不然等你寫的東西發射上了天,再因為數據錯誤發生問題,不是要命么。


實數是全序的,但實數數學運算的結果不一定是實數。IEEE754引入NAN能提供數據結構級的容錯,非全序導致的最值、排序問題可交給演算法解決,一種trade off吧。


推薦閱讀:

程序员敲代码都喜欢听什么?
有哪些新手程序猿不知道(或容易忽視)的大殺技?
西門子Step7編寫程序中 複位和置位優先型起保停電路有什麼不同 意義在哪?
怎麼理解coroutine ?
php創建的文件夾名里含有「黒」字時,「黒」字較大概率會重複出現,請問是何原因?

TAG:中央處理器CPU | 編程 | 編碼 | 數據類型 | 浮點數 |