Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python sum of big float numbers

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!

like image 550
TheBestPessimist Avatar asked Dec 15 '22 01:12

TheBestPessimist


1 Answers

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.

like image 115
Nick Bastin Avatar answered Jan 03 '23 22:01

Nick Bastin