Python floating point precision sum

谁都会走 提交于 2020-01-14 19:34:26

问题


I have the following array in python

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

if I sum all these elements, I get this:

sum(n)
1995485912.1300004

But, this sum should be:

1995485912.13

In this way, I know about floating point "error". I already used the isclose() function from numpy to check the corrected value, but how much is this limit? Is there any way to reduce this "error"?

The main issue here is that the error propagates to other operations, for example, the below assertion must be true:

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


回答1:


This is problem with floating point numbers. One solution is having them represented in string form and using decimal module:

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

from decimal import Decimal

s = sum(Decimal(i) for i in n)

print(s)

Prints:

1995485912.13




回答2:


You could use round(num, n) function which rounds the number to the desired decimal places. So in your example you would use round(sum(n), 2)



来源:https://stackoverflow.com/questions/51312279/python-floating-point-precision-sum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!