语法:round(number[, ndigits])
第二个ndigits参数表示舍入到第几位,需要对原数先计算再舍入,如果不写的话默认保留到整数
>>> round(3.4)
3
>>> round(4.6)
5
>>> round(3.5)
4
>>> round(2.5)
2
规律:四舍六入五成双
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)
如果两边一样远,则舍入到偶数的那一边。
>>> round(0.5)
0
>>> round(-0.5)
0
>>> round(1.5)
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(0.5)
1.0
>>> round(-0.5)
-1.0
浮点数的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.
>>> round(2.675, 2)
2.67
结果是2.67而不是2.68
这不是一个错误:这是一个事实,即大多数小数部分不能精确地表示为浮点数。
>>> print('{:.20f}'.format(2.675))
2.67499999999999982236
看咯,20位精度打印2.675,在机器中保存的2.675这个数字就比实际数字要小那么一点点。这一点点就导致了它离2.67要更近一点点,所以保留两位小数时就近似到了2.67。
小结:
- 误差主要来自输入时十进制转换为计算机内部二进制时。
- round 可以准确舍入,但它涉及的移位计算也可能带来其他误差。
- Python 的decimal 包可用于解决这一问题。