Python sum of big float numbers

floating-point, python

Solution

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.

Problem

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!

Original source