0

I am running this code on Python (both 2.7, 3.x):

>>> 1.1 + 2.2
3.3000000000000003
>>> 1.1 + 2.3
3.4

Could someone explain how does it work and what is happening?

Rudziankoŭ
  • 10,681
  • 20
  • 92
  • 192
  • 3
    see `Floating Point Arithmetic: Issues and Limitations` https://docs.python.org/2/tutorial/floatingpoint.html There is a good explanation. Sometimes there a just representation error, too. – Kordi Mar 10 '16 at 12:18
  • 2
    You could just use module `decimal` if it fits your needs. – Kordi Mar 10 '16 at 12:24
  • 1
    +1 on using the `Decimal()` module; it isn't as straightforward as floats, but it represents the numbers better. – Chuck Mar 10 '16 at 12:35

1 Answers1

1

float in Python implementing double point precision. Unless a number has power two denominator, it cannot be represented exactly by Python, but only "approximately" - up to the 16-th digit. Thus number like: 1, 0.5, 0.25 can be represented exactly, but number like your case (3.3) can only be represented "approximately". Its all correct, up to the 16 digit, and then you get the last 3 there, which is incorrect.

Ian
  • 30,182
  • 19
  • 69
  • 107