MATLAB: The instability in the very simple code.

#instability #indexingfloating pointMATLAB

I noticed the peculiar instability while executing this code in Matlab R2016b:
x = 0:0.01:1;
y=x(x==0.35);
The y variable gets all the values from x except for 0.35 and 0.65.
How is it possible?
I wonder if this instability reproduces in other Matlab versions.

Best Answer

MATLAB does not store fractions in base 10. Finite binary representation is used. 1/10, 0.1, does not have a finite representation in binary, exactly the same way that 1/3 and 1/7 do not have finite representation in decimal. 0.3333 decimal times 3 is not 1, it is 0.9999 decimal, and no matter how many finite digits you use, 1/3 expressed as a decimal, times 3, will not exactly equal 1.
1/10 expressed as binary has the same limitations of not being *exactly* 0.1 decimal. It happens that if you accumulate 35 copies of the approximation, then the result is not exactly the same as the approximation of 0.35 is.
Moral of the story is that you should never compare a computed decimal value for equality, because it is a bit-for-bit test that is done, not an algebraic test. (Exception: there are some situations where comparing for exact 0 is appropriate.)