1. 程式人生 > >python中round函式小坑

python中round函式小坑

在python2.7的doc中。

真正的四捨五入,round(-1.5) = -2   round(1.5) = 2

在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

但是:

>>>

round(2.675,2)

>>>2.67

不論我們從python2還是3來看,結果都應該是2.68的,結果它偏偏是2.67,為什麼?這跟浮點數的精度有關。我們知道在機器中浮點數不一定能精確表達,因為換算成一串1和0後可能是無限位數的,機器已經做出了截斷處理。那麼在機器中儲存的2.675這個數字就比實際數字要小那麼一點點。這一點點就導致了它離2.67要更近一點點,所以保留兩位小數時就近似到了2.67。

如果對精度有要求的話,就不要用round()函數了,就得用其他ceil,floor , //等函式。

[decimal函式精度也有問題,from decimal import *   Decimal(2.67).quantize(Decimal('0.00')) 結果還是2.67]