2

The following output surprised me:

1.1 + 2.2
=> 3.3000000000000003

An unexpected small digit came up from the sum. The same does not happen for other addends, e.g.:

3.0 + 0.3
=> 3.3

I tried both in Python 2.7 and in 3.4, but the result is the same. What is the reason for this unexpected result of the sum?

Marco
  • 3,053
  • 5
  • 27
  • 29

3 Answers3

2

Mainly because binary doesn't play well with decimal (2 and 10 are coprime) and floats have limited precision.

franciscod
  • 992
  • 4
  • 17
1

Ultimately, when it comes down to it, computers are working with binary numbers. Some fractional numbers do not translate as neat as we would like to binary numbers. The resulting value includes some left-over digital garbage.

bhuxtable
  • 23
  • 4
1

For a more complete discussion, see: python floating number and Limiting floats to two decimal points but a reasonable solution might be to specify the desired precision like:

>>> a = 1.1 + 2.2
>>> a = round(a,1)
>>> a 
3.3
Community
  • 1
  • 1
Geoff Wright
  • 188
  • 10