i am trying to add some float values in python 3 (never tested in 2) and i get some odd results, the only varying factor being the order of the elements in the summation.
a = [-1e30, 1e30, 1, 3]
print(sum(a)) # return 4.0
a = [-1e30, 1, 3, 1e30]
print(sum(a)) # return 0.0
Can anyone please tell me what did i miss here?
Thanks in advance!
When you're doing 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
Using the sum
builtin is not going to get you good answers for very large (or small) floating point numbers because of the inherent precision problems. You can get a pretty good view of the gory details at What Every Computer Scientist Should Know About Floating-Point Arithmetic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With