python 數字的四捨五入的問題

python3 以及python2.7 使用 round或者format進行浮點數的四捨五入問題

由於 python3 包括python2.7 以後的round策略使用的是decimal.ROUND_HALF_EVEN
即Round to nearest with ties going to nearest even integer. 也就是隻有在整數部分是奇數的時候, 小數部分才逢5進1; 偶數時逢5捨去。 這有利於更好地保證數據的精確性, 並在實驗數據處理中廣爲使用。

>>> round(2.55, 1) # 2是偶數,逢5捨去
2.5
>>> format(2.55, '.1f')
'2.5'

>>> round(1.55, 1) # 1是奇數,逢5進1
1.6
>>> format(1.55, '.1f')
'1.6'

但如果一定要decimal.ROUND_05UP 即Round away from zero if last digit after rounding towards zero would have been 0 or 5; otherwise round towards zero. 也就是逢5必進1需要設置floatdecimal.Decimal, 然後修改decimal的上下文

import decimal
from decimal import Decimal
context=decimal.getcontext() # 獲取decimal現在的上下文
context.rounding = decimal.ROUND_05UP

round(Decimal(2.55), 1) # 2.6
format(Decimal(2.55), '.1f') #'2.6'

ps, 這顯然是round策略問題, 不要扯浮點數在機器中的存儲方式, 且不說在python裏float, int 都是同decimal.Decimal一樣是對象, 就算是數字, 難道設計round的人就這麼無知以至於能拿浮點數直接當整數一樣比較?!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章