Octave - Why $0.6-0.2-0.2-0.2 \neq 0$, but $0.4-0.2-0.2 = 0$?

200 Views Asked by At

I am newbie about this subject. I have no idea, why:

$$\text{octave}: 0.6 - 0.2 - 0.2 - 0.2$$ $$\text{ans}= -5.55111512312578\times 10^{-17}$$

It should be $0$. However in case:

$$\text{octave}: 0.4 - 0.2 - 0.2$$ $$\text{ans}= 0$$

We got correct result. I don't see a point. Can you explain me it, please ?

1

There are 1 best solutions below

1
On

None of those numbers can be represented exactly in double precision floating point.

Because of the nature of the representation, 0.4 has exactly the same fractional part as 0.2 - only the binary exponent is one larger. Therefore, 0.4-0.2 is computed to give 0.2.

However, 0.6 has a different fractional part which is such that when 0.6-0.4 is computed it differs by 1 in the last bit by the representation of 0.2.

Check the actual bits making up the numbers and you will see what happens.