Python 中的隐式舍入?

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

我有一个这样的代码:

trait= traits[25] #0.5243
value =values[25] #0.8594
amount = trait*value #0.4508979999999997 
dispatch = round(amount,8) #0.4509

为什么

round(amount,8)
只给出四位数?如果我只是将
amount
分配给一个新变量,它将正确返回 0.450898。 但在运行代码中,这种行为会发生变化。是否存在某种隐式舍入?比如,位数不能超过原始变量的位数?

我也尝试过

format 

dispatch_str = format(amount, '.8f') #'0.4509'

有什么解释为什么会发生这种情况吗?

python rounding implicit
1个回答
0
投票

很可能之前的某些值已更改,无法重现此

您给出的金额

0.4508979999999997
与相乘的结果不同
0.5243*0.8594=0.45058342

和四舍五入

amount = 0.4508979999999997
会按预期工作

>>> round(amount, 5)
0.4509
>>> round(amount, 6)
0.450898
>>> round(amount, 8)
0.450898
© www.soinside.com 2019 - 2024. All rights reserved.