標籤:奇數 tco 精確 浮點數 div ima etc dig python2.7
由於 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進11.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需要設定float為decimal.Decimal, 然後修改decimal的上下文
import decimalfrom decimal import Decimalcontext=decimal.getcontext() # 擷取decimal現在的上下文context.rounding = decimal.ROUND_05UPround(Decimal(2.55), 1) # 2.6format(Decimal(2.55), ‘.1f‘) #‘2.6‘
ps, 這顯然是round策略問題, 不要扯浮點數在機器中的儲存方式, 且不說在python裡float, int 都是同decimal.Decimal一樣是對象, 就算是數字, 難道設計round的人就這麼無知以至於能拿浮點數直接當整數一樣比較?!
python 數位四捨五入的問題