Floating-Point Arithmetic: Issues and Limitations

Greetings,
I am self-learning from the python tutorial in the python docs. I am unable to wrap my head around this simple piece of code. Any kind of help is deeply appreciated.


Why is the first line output is True and the second one False ?
Thanks in advance.

For exactly the same reason at work here:

>>> 0.1 + 0.1 == 0.2
True
>>> 0.1 + 0.1 + 0.1 == 0.3
False

Rounding these values to one decimal digit has ne effect at all:

>>> round(0.1, 1) == 0.1
True
>>> round(0.3, 1) == 0.3
True

These decimal fractions are not exactly representable in binary floating point, and the binary approximations were already as close as it’s possible to get.

Adding the 3 copies of the closest binary approximation to 0.1 yields a sum that’s a little larger than the closest binary approximation to 0.3:

>>> import decimal
>>> decimal.Decimal(0.3)
Decimal('0.299999999999999988897769753748434595763683319091796875')
>>> decimal.Decimal(0.1 + 0.1 + 0.1)
Decimal('0.3000000000000000444089209850062616169452667236328125')
2 Likes

Hey Tim,
I am thankful for the knowledge shared here. This made my day. :innocent:

1 Like