[英]float point arithmetic in python
>>> .1+.1+.1+.1 ==.4
True
>>> .1+.1+.1 ==.3
False
>>>
>>> Decimal(.4) Decimal('0.40000000000000002220446049250313080847263336181640625') >>> Decimal(.1+.1+.1+.1) Decimal('0.40000000000000002220446049250313080847263336181640625') >>> Decimal(.1+.1+.1) Decimal('0.3000000000000000444089209850062616169452667236328125') >>> Decimal(.3) Decimal('0.299999999999999988897769753748434595763683319091796875') >>> Decimal(.1) Decimal('0.1000000000000000055511151231257827021181583404541015625')
這可能解釋了為什么添加會以它們的方式發生
假設 Decimal 給出了存儲在下面的數字的確切輸出
但是那么 python 首先返回 True 而第二個返回 False 的原因是什么因為兩者都無法比較
浮點數絕對可以比較是否相等。 只有當您期望通過近似計算來保持精確相等時,才會出現問題。 但是浮點相等比較的語義是完美定義的。
當您在程序中寫入0.1
時,它會四舍五入為最接近的 IEEE 754 binary64 浮點數,即實數 0.100000000000000005551115123125782702118158340454101-5625,或 0x1.999999999999ap-4 的十六進制表示法中的“×2”部分⁴)。 每個(正常)二進制 64 浮點數都是 ±2ⁿ × (1 + /2⁵³) 形式的實數,其中 和 是整數,−1022 ≤ ≤ 1023 和 0 ≤ < 2⁵³; 這是最接近 0.1 的數字。
When you add that to itself three times in floating-point arithmetic, the exact result 0.3000000000000000166533453693773481063544750213623046875 is rounded to 0.3000000000000000444089209850062616169452667236328125 or 0x1.3333333333334p−2 (since there are only 53 bits of precision available), but when you write 0.3
, you get 0.299999999999999988897769753748434595763683319091796875 or 0x1.3333333333333p-2 稍微接近 0.3。
However, four times 0.1000000000000000055511151231257827021181583404541015625 or 0x1.999999999999ap−4 is 0.4000000000000000222044604925031308084726333618164062500 or 0x1.999999999999ap−2, which is also the closest floating-point number to 0.4 and hence is what you get when you write 0.4
in a program. 因此,當您編寫4*0.1
時,結果與您編寫0.4
時的浮點數完全相同。
現在,你沒有寫4*0.1
——而是你寫了.1 +.1 +.1 +.1
。 但事實證明,在二進制浮點算術中存在一個定理,即x + x + x + x
x——即 fl(fl(fl( + ) + ) + )——在不四舍五入的情況下總是准確地得出 4(除非它溢出),盡管x + x + x
或 fl(fl( + ) + ) = fl(3) 可能被四舍五入並且不完全等於 3。(請注意,fl( + ) = fl(2) 是總是等於 2,再次忽略溢出,因為這只是調整指數的問題。)
恰好通過添加第四項所犯的任何舍入錯誤抵消了添加第三項可能已提交的任何舍入錯誤!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.