python2与python3中的round

round不是简单的四舍五入。

在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。

但是到了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。

而且Python float类型采用二进制描述浮点数,实际上很多浮点数并不精确,就导致使用round()函数的时候会出现很多“不合理”的结果。 比如:

1
2
3
4
5
6
7
round(3.45, 1) = 3.5 

format(3.45, ".20f") = '3.45000000000000017764'

round(3.55, 1) = 3.5

format(3.55, ".20f") = '3.54999999999999982236'
1
2
3
4
5
6
7
8
9
10
11
12
13
python2中
>>> round(3.45, 1)
3.5
>>> format(3.45, ".20f")
'3.45000000000000017764'
>>> round(3.55, 1)
3.5
>>> format(3.55, ".20f")
'3.54999999999999982236'
>>> round(1.5)
2.0
>>> round(2.5)
3.0
1
2
3
4
5
6
7
8
9
10
11
python3中
>>> format(3.45, ".20f")
'3.45000000000000017764'
>>> round(3.55, 1)
3.5
>>> format(3.55, ".20f")
'3.54999999999999982236'
>>> round(1.5)
2
>>> round(2.5)
2
如果觉得写的还行,赞助瓶脉动~
0%