为什么 Python 将 3.15 舍入到 3.1

问题描述 投票:0回答:3

按照Python的Banker的四舍五入方式,如果是0.5应该四舍五入到偶数,所以会到3.2。 0.15、1.15、2.15 和 3.15 相同,但 4.15 与我预期的一样。为什么要这样做,因为银行家的四舍五入(四舍五入到偶数)应该意味着它四舍五入到 .2 而不是 .1.

发生了什么:

>>> print(round(3.15, 1))
3.1

我的期望:

>>> print(round(3.15, 1))
3.2
python rounding
3个回答
3
投票

这是由于浮点数的问题,那些浮点字面量表示的值都不能用二进制精确表示,所以它们总是略高于或低于你在源代码中写的值:

import decimal

floats = 0.15, 1.15, 2.15, 3.15, 4.15
for f in floats:
    print(decimal.Decimal(f))

你看:

0.1499999999999999944488848768742172978818416595458984375
1.149999999999999911182158029987476766109466552734375
2.149999999999999911182158029987476766109466552734375
3.149999999999999911182158029987476766109466552734375
4.1500000000000003552713678800500929355621337890625

注意,如果我们使用精确值:

decimals = list(map(decimal.Decimal, ['0.15', '1.15', '2.15', '3.15', '4.15']))
for d in decimals:
    print(d, round(d, 1))

我们得到你所期望的:

0.15 0.2
1.15 1.2
2.15 2.2
3.15 3.2
4.15 4.2

我们可以构造我们知道可以用二进制表示的浮点数(它们是2的幂):

exact = [(n, 2**(-n)) for n in range(1, 6)]
for exponent, f in exact:
    print(decimal.Decimal(f), round(f, exponent-1))

我们现在看到

float
对象“工作”:

0.5 0.0
0.25 0.2
0.125 0.12
0.0625 0.062
0.03125 0.0312

-1
投票

我使用了在 https://realpython.com/python-rounding/ 找到的这个函数 它返回我所期望的:

import math
def round_up(n, decimals=0):
    multiplier = 10 ** decimals
    return math.ceil(n * multiplier) / multiplier

现在:

floats = 0.15, 1.15, 2.15, 3.15, 4.15
for f in floats:
...round_up(f,1)

0.2
1.2
2.2
3.2
4.2

-1
投票

阅读函数的文档.

© www.soinside.com 2019 - 2024. All rights reserved.