Python浮点精度总和

And*_*lho 6 floating-point precision python-3.x

我在python中有以下数组

n = [565387674.45, 321772103.48,321772103.48, 214514735.66,214514735.65, 357524559.41]

如果我总结所有这些元素,我会得到这个:

sum(n)
1995485912.1300004
Run Code Online (Sandbox Code Playgroud)

但是,这个总和应该是:

1995485912.13

这样,我就知道了浮点“错误”。我已经使用isclose()numpy的函数来检查更正后的值,但是 这个限制是多少?有什么办法可以减少这种“错误”?

这里的主要问题是错误会传播到其他操作,例如,以下断言必须为真:

assert (sum(n) - 1995485911) ** 100 - (1995485912.13 - 1995485911) ** 100 == 0.

Ach*_*113 -1

您可以使用round(num, n)将数字四舍五入到所需小数位的函数。所以在你的例子中你会使用round(sum(n), 2)