1

I am trying to sum up a list of float number. There is not repeating decimals in the list but the result is a repeating decimals number. What is the cause and how to prevent? (Python version: 2.7.11)

For example,

a=[1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1]
sum(a)

results in

7.699999999999999

Thank you.

user19881219
  • 317
  • 2
  • 16

2 Answers2

1

You can use numpy for your calculation as in below code:

import numpy

a=[1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1]
print(numpy.sum(a))
Gahan
  • 4,075
  • 4
  • 24
  • 44
  • why I got downvote here? It's correct solution – Gahan May 25 '17 at 03:57
  • Yeah, why the downvote? – whackamadoodle3000 May 25 '17 at 03:58
  • 1
    This is at best hiding the problem; you were dealing with inaccurate numbers the moment you wrote `1.1` as a floating-point literal, adding them with numpy instead of the built-in `sum()` changes NOTHING. If you had used `print` instead of a raw expression in the first place (in other words, seeing the `__str__` of the value instead of its `__repr__`), you would have gotten `7.7`, but that's just being rounded for display - the actual result isn't actually 7.7. – jasonharper May 25 '17 at 12:33
0

This is nature of binary floating point. You can read more information here

Note: You can always use %.f for precision. i.e. %.1f in your case

Jay Parikh
  • 2,419
  • 17
  • 13