python 數字的四舍五入的問題


由於 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的人就這么無知以至於能拿浮點數直接當整數一樣比較?!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM