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
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With