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!
When you make sums of sequences of floating point numbers, you want to use math.fsum:
math.fsum
>>> a = [-1e30, 1e30, 1, 3] >>> math.fsum(a) 4.0 >>> a = [-1e30, 1, 3, 1e30] >>> math.fsum(a) 4.0
sum ( ) - . gory .
sum
53- ( " e" ).
e
10**30 , 2**53, 4 .
10**30
2**53
>>> 2**53 9007199254740992 >>> 10**30 1000000000000000000000000000000 >>> float(2**53) 9007199254740992.0 >>> float(2**53) + 1 9007199254740992.0