123.4+2=125.40000000000001

Kalle Svensson karl-sve at dsv.su.se
Wed Jun 21 07:35:14 EDT 2000


On Wed, 21 Jun 2000, Peter Koppatz wrote:

> >>> 123.4+2
> 125.40000000000001   # is this OK?
> >>> print 123.4+2
> 125.4
> >>>

Short answer: This is the way it is.

Long answer:
It has to do with

1) Representation of floating point numbers internally
2) The difference between __repr__ and __str__

Point 1 ist that floating point numbers are not exact. Lots of people can
explain this better than me. Search deja, the answer is out there!

Point 2 is that print uses the __str__ method of an object to get the
printable string, but the interactive interpreter uses __repr__. __str__
does the rounding, __repr__ doesn't. Again, many others probably explain
this better than me. I could even be wrong, strange as it might seem!
Once again, search deja [1].

> On my calculator: 123.4+2 = 125.4 !?

In fact, this probably isn't true. It's just that your calculator rounds
the answer before handing it to you, just like print. Maybe. I should
probably change my name to Search Deja... :)

Also note that there has been a lot of discussion on this topic here, and
that the behavior might change in a later version of python.

HTH,
  Kalle Svensson

[1] You might answer "No, you get eye cancer from looking at Deja."
    To this I have no reply. Just get a good health insurance. :)




More information about the Python-list mailing list