Python 中關於 round 函數的坑

 round函數很簡單(並且不須要引入math模塊),對浮點數進行近似取值,保留幾位小數。python

好比linux

# -*- coding: UTF-8 -*-
r1=round(12.12345,3) r2=round(12.12345) print r1,' ',r2

結果git

 

一、round的結果跟python版本有關

咱們來看看python2和python3中有什麼不一樣:python2.7

$ python Python 2.7.8 (default, Jun 18 2015, 18:54:19) [GCC 4.9.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> round(0.5) 1.0 $ python3 Python 3.4.3 (default, Oct 14 2015, 20:28:29) [GCC 4.8.4] on linux Type "help", "copyright", "credits" or "license" for more information. >>> round(0.5) 0

若是咱們閱讀一下python的文檔,裏面是這麼寫的:函數

在python2.7的doc中,round()的最後寫着,"Values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done away from 0." 保留值將保留到離上一位更近的一端(四捨六入),若是距離兩端同樣遠,則保留到離0遠的一邊。因此round(0.5)會近似到1,而round(-0.5)會近似到-1。spa

可是到了python3.5的doc中,文檔變成了"values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice." 若是距離兩邊同樣遠,會保留到偶數的一邊。好比round(0.5)和round(-0.5)都會保留到0,而round(1.5)會保留到2。code

因此若是有項目是從py2遷移到py3的,可要注意一下round的地方(固然,還要注意/和//,還有print,還有一些比較另類的庫)。orm



>>> round(2.675, 2) 2.67

python2和python3的doc中都舉了個相同的例子,原文是這麼說的:blog

Note The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.

簡單的說就是,round(2.675, 2) 的結果,不論咱們從python2仍是3來看,結果都應該是2.68的,結果它恰恰是2.67,爲何?這跟浮點數的精度有關。咱們知道在機器中浮點數不必定能精確表達,由於換算成一串1和0後多是無限位數的,機器已經作出了截斷處理。那麼在機器中保存的2.675這個數字就比實際數字要小那麼一點點。這一點點就致使了它離2.67要更近一點點,因此保留兩位小數時就近似到了2.67。ip

以上。除非對精確度沒什麼要求,不然儘可能避開用round()函數。近似計算咱們還有其餘的選擇:

  • 使用math模塊中的一些函數,好比math.ceiling(天花板除法)。
  • python自帶整除,python2中是/,3中是//,還有div函數。
  • 字符串格式化能夠作截斷使用,例如 "%.2f" % value(保留兩位小數並變成字符串……若是還想用浮點數請披上float()的外衣)。
  • 固然,對浮點數精度要求若是很高的話,請用嘚瑟饃,不對不對,請用decimal模塊。
相關文章
相關標籤/搜索