1

I understand that the number 0.3 cannot be exactly represented in binary, and thats why doing something like:

0.1+0.2==0.3

gives False as an answer.

However even if the number cannot be exactly represented, the result should still be True. Here's my reasoning:

Python will do the operation 0.1+0.2 and the result will not be exactly 0.3, it will be some number close to 0.3 that will be stored as the left operand of the comparison.

But then it has to take the right operand 0.3, convert it to a number, which will give again number not exactly equal to 0.3 and store it as the right operand of the comparison.

Finally compare both numbers.

So the result should actually give True, even if internally it will be comparing two numbers and none of them will actually be 0.3

What am I missing here? If the number cannot be exactly represented, then this must be true for both operands, so we will be comparing something like

0.1+0.2==0.3
0.30000000000000004 == 0.30000000000000004
True
  • 3
    I believe this is because you're ignoring the fact that also `0.1` and `0.2` can't be accurately represented too. So on the right side you have "inaccurate" 0.3 but on the left side the sum of "inaccurate" 0.1 and "inaccurate" 0.2. So they are not neccessariely the same – Tomerikoo Sep 23 '19 at 15:47
  • The only thing relevant is the ACTUAL floating point representation (bits), regardless of how the numbers “look” in source. Naturally, every X == X is true (except for very odd cases like NaN); so take that back to the premise. – user2864740 Sep 23 '19 at 15:47
  • The issue is explained in great depth at https://docs.python.org/3/tutorial/floatingpoint.html. Note also the use of ‘format’ / ‘hex’ eg to get the exact FP value representation for display. – user2864740 Sep 23 '19 at 15:51

1 Answers1

2

The error in representing 0.1 plus the error in representing 0.2 is not necessarily equal to the error in representing 0.3.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101