%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

 채택된 답변

Ameer Hamza
Ameer Hamza 2020년 6월 13일
편집: Ameer Hamza 2020년 6월 13일

1 개 추천

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

댓글 수: 3

Thank you very much, that worked!
If the case comprises with the floating point, can't we do it by rounding?
t=0;
for n=1:10
t=round(t+0.1,1);
disp(t)
if t==0.8
disp('if')
else
disp('else')
end
end
Ameer Hamza
Ameer Hamza 2020년 6월 13일
yes, that will work as well, but it is good to use the tolerance method. Otherwise, you will need to do rounding every time you do some mathematical operation on the variable.
Poojitha Ariyathilaka
Poojitha Ariyathilaka 2020년 6월 13일
Yes, tolerance method is much quicker.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

제품

릴리스

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by