Effacer les filtres
Effacer les filtres

This simple code note working, HELP

3 vues (au cours des 30 derniers jours)
Poojitha Ariyathilaka
Poojitha Ariyathilaka le 13 Juin 2020
%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

Réponse acceptée

Ameer Hamza
Ameer Hamza le 13 Juin 2020
Modifié(e) : Ameer Hamza le 13 Juin 2020
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 commentaires
Ameer Hamza
Ameer Hamza le 13 Juin 2020
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 le 13 Juin 2020
Yes, tolerance method is much quicker.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by