7

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.

Guilherme
  • 1,980
  • 22
  • 23
  • 5
    Python has `math.fsum` to compute “an accurate floating point sum,” but [its documentation](https://docs.python.org/3/library/math.html#math.fsum) is vague. It generally returns a better result than simple serial addition, but it will not always return the best result possible in the floating-point format. – Eric Postpischil Jul 13 '18 at 02:29
  • Thanks, this method work for me. – André Davys Carvalho Jul 19 '18 at 17:34

2 Answers2

3

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

user2357112
  • 260,549
  • 28
  • 431
  • 505
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
-1

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)

Ach113
  • 1,775
  • 3
  • 18
  • 40