这个一直都想写,可是由于这个点比较小,因此一直懒得动手。不过仍是补上吧,留着迟早是个祸害。python
round函数很简单,对浮点数进行近似取值,保留几位小数。好比linux
>>> round(10.0/3, 2) 3.33 >>> round(20/7) 3
第一个参数是一个浮点数,第二个参数是保留的小数位数,可选,若是不写的话默认保留到整数。git
这么简单的函数,能有什么坑呢?python2.7
一、round的结果跟python版本有关函数
咱们来看看python2和python3中有什么不一样:spa
$ 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
好玩吗?code
若是咱们阅读一下python的文档,里面是这么写的:orm
在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。blog
可是到了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。ip
因此若是有项目是从py2迁移到py3的,可要注意一下round的地方(固然,还要注意/和//,还有print,还有一些比较另类的库)。
二、特殊数字round出来的结果可能未必是想要的。
>>> round(2.675, 2)
2.67
python2和python3的doc中都举了个相同的栗子,原文是这么说的:
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。
以上。除非对精确度没什么要求,不然尽可能避开用round()函数。近似计算咱们还有其余的选择:
就酱。