MATLAB: This simple code note working, HELP

elsefloating pointfor loopif statementloopMATLAB

%this works well upto t==0.7, but not after 0.8
%give me an answer for this, not links
t=0;
for n=1:10
t=t+0.1;
disp(t)
if t==0.8
disp('if')
else
disp('else')
end
end

Best Answer

Direct comparison using == of floating-point number does not give the correct result. You need to allow some level of tolerance. Try this
t=0;
for n=1:10
t=t+0.1;
disp(t);
if abs(t-0.8) < 1e-6
disp('if')
else
disp('else')
end
end