What is the rationale for all comparisons returning false for IEEE754 NaN values?

問題:

Why do comparisons of NaN values behave differently from all other values?爲什麼 NaN 值的比較與所有其他值的表現不同? That is, all comparisons with the operators ==, <=, >=, <, > where one or both values is NaN returns false, contrary to the behaviour of all other values.也就是說,所有與運算符 ==、<=、>=、<、> 的比較,其中一個或兩個值爲 NaN,都返回 false,這與所有其他值的行爲相反。

I suppose this simplifies numerical computations in some way, but I couldn't find an explicitly stated reason, not even in the Lecture Notes on the Status of IEEE 754 by Kahan which discusses other design decisions in detail.我想這在某種程度上簡化了數值計算,但我找不到明確說明的原因,甚至在 Kahan 的關於 IEEE 754 狀態講義中也沒有,它詳細討論了其他設計決策。

This deviant behavior is causing trouble when doing simple data processing.在進行簡單的數據處理時,這種異常行爲會造成麻煩。 For example, when sorting a list of records wrt some real-valued field in a C program I need to write extra code to handle NaN as the maximal element, otherwise the sort algorithm could become confused.例如,當在 C 程序中對包含一些實值字段的記錄列表進行排序時,我需要編寫額外的代碼來處理 NaN 作爲最大元素,否則排序算法可能會變得混亂。

Edit: The answers so far all argue that it is meaningless to compare NaNs.編輯:到目前爲止的答案都認爲比較 NaN 是沒有意義的。

I agree, but that doesn't mean that the correct answer is false, rather it would be a Not-a-Boolean (NaB), which fortunately doesn't exist.我同意,但這並不意味着正確答案是錯誤的,而是它會是一個 Not-a-Boolean (NaB),幸運的是它不存在。

So the choice of returning true or false for comparisons is in my view arbitrary, and for general data processing it would be advantageous if it obeyed the usual laws (reflexivity of ==, trichotomy of <, ==, >), lest data structures which rely on these laws become confused.因此,在我看來,選擇返回 true 或 false 進行比較是任意的,對於一般的數據處理,如果它遵守通常的規律(== 的自反性,<、==、> 的三分法),以免數據結構依靠這些法律變得混亂。

So I'm asking for some concrete advantage of breaking these laws, not just philosophical reasoning.所以我要求打破這些法律的一些具體優勢,而不僅僅是哲學推理。

Edit 2: I think I understand now why making NaN maximal would be a bad idea, it would mess up the computation of upper limits.編輯 2:我想我現在明白爲什麼將 NaN 設爲最大值是一個壞主意,它會搞亂上限的計算。

NaN != NaN might be desirable to avoid detecting convergence in a loop such as NaN != NaN 可能需要避免檢測循環中的收斂,例如

while (x != oldX) {
    oldX = x;
    x = better_approximation(x);
}

which however should better be written by comparing the absolute difference with a small limit.然而,最好通過將絕對差異與小限制進行比較來編寫。 So IMHO this is a relatively weak argument for breaking reflexivity at NaN.所以恕我直言,這是打破 NaN 反身性的一個相對較弱的論點。


解決方案:

參考一: https://en.stackoom.com/question/6ZAa
參考二: https://stackoom.com/question/6ZAa
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章