0

When I add numbers from a list, I get an extra .00000000003. Where does that come from?

Here's my list of numbers

list = [210.0, 140.0, 171.0, 70.0, 625.0, 187.5, 70.0, 1496.89]

When I get a total sum of all the numbers, I get 2970.3900000000003

>>> sum(list)
2970.3900000000003

>>> total = 0
>>> for x in list:
...     total += x
... 
>>> total
2970.3900000000003

But say I print, the total comes out as regular

>>> total = 0
>>> for x in list:
...     total += x
...     print total
... 
210.0
350.0
521.0
591.0
1216.0
1403.5
1473.5
2970.39

Where do those extra sig figs come from and how can I avoid it when using it elsewhere?

Freigheist
  • 31
  • 1
  • 2
  • 8

1 Answers1

1

It comes from floating point rounding. If you need exact decimal math you'll have to use Decimal.

> sum([decimal.Decimal(f) for f in '210.0 140.0 171.0 70.0 625.0 187.5 70.0 1496.89'.split()])
Decimal('2970.39')

The short version is that your fractional numbers like 1496.89 are being stored in binary, and .89 definitely can't be represented as k/2^n. Here's a longer document that says the same thing.

Sometimes you can get away with this by printing the final value with python's %g formatter, e.g.

> print '%g' % sum([210.0, 140.0, 171.0, 70.0, 625.0, 187.5, 70.0, 1496.89])
2970.39

Which tries very hard to find a short representation of the number you actually have (which is in binary)

U2EF1
  • 12,907
  • 3
  • 35
  • 37