問題描述
我在 python 的輸出中遇到負零;例如,它的創建如下:
I encountered negative zero in output from python; it's created for example as follows:
k = 0.0
print(-k)
輸出將是 -0.0
.
但是,當我將 -k
與 0.0 進行比較時,結果為 True.0.0
和 -0.0
之間有什么區別嗎(我不在乎它們可能具有不同的內部表示;我只關心它們在程序中的行為.)有什么我應該注意的隱藏陷阱嗎?
However, when I compare the -k
to 0.0 for equality, it yields True. Is there any difference between 0.0
and -0.0
(I don't care that they presumably have different internal representation; I only care about their behavior in a program.) Is there any hidden traps I should be aware of?
推薦答案
查看 -0(維基百科中的數字)
基本上 IEEE 確實定義了一個負零.
Basically IEEE does actually define a negative zero.
并且根據這個定義用于所有目的:
And by this definition for all purposes:
-0.0 == +0.0 == 0
我同意 aaronasterling -0.0
和 +0.0
是不同的對象.使它們相等(相等運算符)可確保代碼中不會引入細微的錯誤.
想想 a * b == c * d
I agree with aaronasterling that -0.0
and +0.0
are different objects. Making them equal (equality operator) makes sure that subtle bugs are not introduced in the code.
Think of a * b == c * d
>>> a = 3.4
>>> b =4.4
>>> c = -0.0
>>> d = +0.0
>>> a*c
-0.0
>>> b*d
0.0
>>> a*c == b*d
True
>>>
當我出于所有實際目的說這個詞時,我是相當倉促地選擇了這個詞.我的意思是標準的平等比較.
When I said for all practical purposes, I had chosen the word rather hastily. I meant standard equality comparison.
正如參考資料所說,IEEE 標準定義了比較,以便 +0 = -0
,而不是 -0
.+0代碼>.盡管總是可以忽略零的符號,但 IEEE 標準并沒有這樣做.當乘法或除法涉及帶符號的零時,通常的符號規則適用于計算答案的符號.
As the reference says, the IEEE standard defines comparison so that +0 = -0
, rather than -0 < +0
. Although it would be possible always to ignore the sign of zero, the IEEE standard does not do so. When a multiplication or division involves a signed zero, the usual sign rules apply in computing the sign of the answer.
divmod
和 atan2
等操作會表現出這種行為.事實上,atan2
符合 IEEE 定義和底層一樣C"庫.
Operations like divmod
and atan2
exhibit this behavior. In fact, atan2
complies with the IEEE definition as does the underlying "C" lib.
>>> divmod(-0.0,100)
(-0.0, 0.0)
>>> divmod(+0.0,100)
(0.0, 0.0)
>>> math.atan2(0.0, 0.0) == math.atan2(-0.0, 0.0)
True
>>> math.atan2(0.0, -0.0) == math.atan2(-0.0, -0.0)
False
一種方法是通過文檔找出實現是否符合 IEEE 行為.從討論中似乎也有微妙的平臺變化.
One way is to find out through the documentation, if the implementation complies with IEEE behavior . It also seems from the discussion that there are subtle platform variations too.
然而,這一方面(IEEE 定義合規性)并未在所有地方得到尊重.請參閱 PEP 754 因不感興趣而被拒絕!我不確定這是不是后來被撿到的.
However this aspect (IEEE definition compliance) has not been respected everywhere. See the rejection of PEP 754 due to disinterest! I am not sure if this was picked up later.
另請參閱每個計算機科學家都應該了解的關于浮動的知識-點算術.
這篇關于python中的負零的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!