Python floating point precision sum

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.

Upvotes: 7

Views: 7899

Answers (2)

Andrej Kesely
Andrej Kesely

Reputation: 195438

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

Upvotes: 3

Ach113
Ach113

Reputation: 1825

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)

Upvotes: -1

Related Questions