python 數位四捨五入的問題

來源:互聯網
上載者:User

標籤:奇數   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需要設定floatdecimal.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 數位四捨五入的問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.