round函数

语法:round(number[, ndigits]) 
第二个ndigits参数表示舍入到第几位,需要对原数先计算再舍入,如果不写的话默认保留到整数

规律:四舍六入五成双

round函数在python 3和2中的表现并不一样

python 3的官网文档:https://docs.python.org/3/library/functions.html?highlight=round#round
if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2)
如果两边一样远,则舍入到偶数的那一边。

python 2的官网文档:https://docs.python.org/2/library/functions.html?highlight=round#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 (so, for example, round(0.5) is 1.0 and round(-0.5) is -1.0).
如果距离两端一样远,则保留到离0远的一边。所以round(0.5)会近似到1,而round(-0.5)会近似到-1。

浮点数的round的结果可能会使你惊讶,但不是错误
无论是python3还是2都举了相同的例子,
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.

结果是2.67而不是2.68

这不是一个错误:这是一个事实,即大多数小数部分不能精确地表示为浮点数。

看咯,20位精度打印2.675,在机器中保存的2.675这个数字就比实际数字要小那么一点点。这一点点就导致了它离2.67要更近一点点,所以保留两位小数时就近似到了2.67。
小结:

  1. 误差主要来自输入时十进制转化为计算机 内部二进制时
  2. round可以准确舍入,但它涉及的一位运算也可能带来其他的误差
  3. python的decimal包可用解决这一问题

 

posted @ 2019-02-11 17:36  团子emma  阅读(556)  评论(0)    收藏  举报