Sum of large Python floating point numbers

I try to add some float values ​​in python 3 (never tested in 2) and I get some odd results, the only variable factor is the order of the elements in the sum.

a = [-1e30, 1e30, 1, 3]
print(sum(a))   # return 4.0

a = [-1e30, 1, 3, 1e30]
print(sum(a))   # return 0.0

Can anyone tell me what I missed here?

Thanks in advance!

+3
source share
2 answers

When you make sums of sequences of floating point numbers, you want to use math.fsum:

>>> a = [-1e30, 1e30, 1, 3]
>>> math.fsum(a)
4.0
>>> a = [-1e30, 1, 3, 1e30]
>>> math.fsum(a)
4.0

sum ( ) - . gory .

+6

53- ( " e" ).

10**30 , 2**53, 4 .

>>> 2**53
9007199254740992
>>> 10**30
1000000000000000000000000000000
>>> float(2**53)
9007199254740992.0
>>> float(2**53) + 1
9007199254740992.0
+4

All Articles