MATLAB: “If function” can’t distinguish i ~= 1.6.

floating pointif statementMATLAB

I was trying to plot a series of figures and use "if elseif else" function to do this job. But I found out "if i ~= 1.6" cannot be distinguished. I wrote a simple code here. When "i=1.6","a=1.6". This weird thing only happens when i=1.6.
Could someone help me with it? Is it a bug or is there something wrong with my code.
Thank you very much!
a=0;
for i = 1.4:0.1:1.9
if i ~= 1.6
a = i;
end
end

Best Answer

"This weird thing only happens when i=1.6."
Nothing weird happens: you generate binary floating point numbers using two different methods and get slightly different output values for some input values. That is in the nature of binary floating point numbers.
"Is it a bug..."
No.
"...or is there something wrong with my code."
Yes. You assumed that numeric mathematics is the same as symbolic or algebraic mathematics. But it isn't.
In your example you did not take into account the acccumulated floating point error, which means that you should never test for exact equality of binary floating point numbers, but should always compare the absolute difference againsts a tolerance:
abs(A-B)<tol
Or change the algorithm to work with integer values only.
Read more about binary floating point numbers:
This is worth reading as well: