4

I understand that floating number has their limitations so this can be expected:

>>> 0.1 + 0.2 == 0.3
False

But why is this valid? Computers can't store 0.45, 0.55 reliably either right?

>>> 0.45 + 0.55 == 1.00
True

I want to know how in the first case computer couldn't correct its inaccuracy and in the later one it could.

Abhinav Srivastava
  • 840
  • 10
  • 17
  • 2
    @cᴏʟᴅsᴘᴇᴇᴅ: This question does seem to differ from your linked question. The other asks why the inequality (sometimes) happens. This question asks why and under what conditions it sometimes happens and sometimes does not. – Rory Daulton Jul 08 '17 at 11:35
  • 1
    @RoryDaulton I see... Alright. Will retract. Also, OP, take a look at this: https://www.h-schmidt.net/FloatConverter/IEEE754.html – cs95 Jul 08 '17 at 11:39

1 Answers1

4

As you know most decimal numbers can't be stored exactly. That's true for all of your above numbers except 1.0.

But they get stored with a high accuracy. Instead of 0.3, some very close representable number gets used. It's not only very close, it's the closest such number.

When you compute 0.1 + 0.2, then another representable number gets computed, which is also very close to 0.3. You are "unlucky" and it differs from the closest possible representable number.

There's no real luck involved, both 0.1 and 0.2 get represented by a slightly larger number. When added, the two errors add as they're of the same sign and you get something like 0.30000000000000004.

With 0.45 + 0.55, the errors are of different signs and cancel out.

maaartinus
  • 44,714
  • 32
  • 161
  • 320