While loop iterating further than expected?

5 views (last 30 days)
Hi. I am experiencing a strange behavior in this simple script:
% CASE 1 - COMPUTES CORRECTLY
m1=1;
while m1<4.80
m1=m1+0.1;
end
disp(m1);
% CASE 2 - DOES NOT COMPUTE CORRECTLY
m2=1;
while m2<4.90
m2=m2+0.1;
end
disp(m2);
I obtain m1 = 4.8, as expected. However, I obtain m2 = 5.0, which implies the loop in CASE 2 has gone on for one iteration too many. Any idea why this might be happening? Is it a precision-related issue? I'm afraid I must be missing something very silly. Thank you for your help.
  2 Comments
Guillermo
Guillermo on 29 Aug 2018
Thank you, Stephen. Very instructive. I will look at your references. I was somewhat aware that something like this might be happening but I frankly did not expect it to have such an impact with such simple numbers in two adjacent and very similar instances. Thanks again.

Sign in to comment.

Accepted Answer

OCDER
OCDER on 29 Aug 2018
Edited: OCDER on 29 Aug 2018
Rounding error. Try something like this:
m1=1;
while m1 < 4.80
m1=round(m1+0.1, 2); %To prevent m1 from drifting too far due to rounding error
end
disp(m1);
% CASE 2
m2=1;
while m2 < 4.90
m2=round(m2+0.1, 2);
end
disp(m2);
  3 Comments
OCDER
OCDER on 29 Aug 2018
See new answer. Use round(x, n) to round x to the nearest nth decimal place.

Sign in to comment.

More Answers (0)

Products


Release

R2018a

Community Treasure Hunt

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

Start Hunting!