Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Floating point addition in Python [duplicate]

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?

like image 446
cpx Avatar asked Jan 12 '23 02:01

cpx


1 Answers

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.

like image 191
Games Brainiac Avatar answered Jan 18 '23 01:01

Games Brainiac