今天用python中的round方法来四舍五入,结果发现预期跟实际差距太大,也摸不出规律所在,在一顿查找之下,终于算是彻底了解了。
先来看一波示例,结果是大跌眼镜。
# python 2.7.5
>>> round(1.55, 1)
1.6
>>> round(2.55, 1)
2.5
查阅python2.7官方文档,里面有这样一句话:
Note: The behavior of
round()
for floats can be surprising: for example,round(2.675, 2)
gives2.67
instead of the expected2.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()的行为可能令人惊讶,例如,round(2.675, 2)给出了2.67,而不是预期的2.68。这并不是一个bug,它是大多数小数部分不能精确表示为浮点数的结果。有关更多信息,请参阅浮点算法:问题和限制。
简而言之,就是大多数浮点数在存储为二进制的时候不能够精确存储,会有精度的损失,你看到的1.55并不是实际上的1.55,它实际的值通过decimal.Decimal模块可以看出来。
# python 2.7.5
>>> from decimal import Decimal
>>> Decimal(1.55)
Decimal('1.5500000000000000444089209850062616169452667236328125')
>>> Decimal(2.55)
Decimal('2.54999999999999982236431605997495353221893310546875')
可以看出1.55存储的实际值比1.55要大一点点,2.55存储的实际值比2.5小一点点,所以1.55保留一位小数的情况下它离1.6更近一些,而2.55保留一位小数的情况下则离2.5更近一些。
如果是精确存储的浮点数,并且最后一位为5的情况下,离两端距离一样,这个时候就要区分python版本了。
- 在python2下,直接进位。总结起来就是 “四舍五入”
# python 2.7.5
>>> round(0.5)
1.0
>>> round(-0.5)
-1.0
>>> round(1.5)
2.0
- 在python3下,前一位为奇数,则进位,前一位为偶数,则舍去。也就是 “四舍六入五成双”,又叫 “四舍六入五凑偶”。
# python 3.6.4
>>> round(0.5)
0
>>> round(-0.5)
0
>>> round(1.5)
2
参考: