Friday, 15 February 2019

Floating point addition in Python




Why exactly does the latter case in Python doesn't yield the result 3.3?



>>> 1.0 + 2.3
3.3
>>> 1.1 + 2.2
3.3000000000000003



It doesn't seem to make any sense to me what is going on here. What are the limitations here for the representation of the same result that you are getting through 1.0 + 2.3 but not through 1.1 + 2.2?


Answer



To quote the documentation:




Unfortunately, most decimal fractions cannot be represented exactly as binary fractions. A consequence is that, in general, the decimal floating-point numbers you enter are only approximated by the binary floating-point numbers actually stored in the machine.




And what you have stumbled upon is one of many idiosyncrasies:




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


In fact, its a rare one, I've had a hard time finding other occurrences. Here's another weird one:




>>> 0.1 + 0.1 + 0.1 - 0.3
5.551115123125783e-17


Using Python's decimal class would give you better results.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...