While loop causing an infinite loop in MATLAB
Show older comments
Hi everyone,
I'm new to computer science and coding in general, so I apologize if this seems like a silly question.
I have a piece of code that involves a while loop which enters an infinite loop. I suspect it has something to do on line five, as when I change the value 0.1 to 1, the code is properly executed. I've attempted to rewrite the code using other loops, but to no avail.
Can I get an explanation as to why the code is entering this infinite loop? Thank you!
s=0
while s ~=5
s = s + 0.1;
end
Accepted Answer
More Answers (1)
Image Analyst
on 8 Oct 2018
See the FAQ: http://matlab.wikia.com/wiki/FAQ#Why_is_0.3_-_0.2_-_0.1_.28or_similar.29_not_equal_to_zero.3F
Another problem with your code is that you didn't use a failsafe - some way to bail out of the code automatically if you get into an infinite loop. While loops should ALWAYS use a failsafe. The failsafe will kick you out of the loop if you iterate more than some predetermined number of iterations - a number way more than you ever expect to iterate. For example:
s=0;
maxIterations = 100000; % Whatever is more than you expect to need.
loopCounter = 0;
while s ~=5 && loopCounter < maxIterations
s = s + 0.1;
loopCounter = loopCounter + 1;
end
if loopCounter >= maxIterations
warningMessage = sprintf('Loop exited after hitting max allowed iterations (%d).\n', maxIterations);
fprintf('%s\n', warningMessage);
uiwait(warndlg(warningMessage));
end
Also, in your specific situation you should really use s<=5 rather than s~=5 because of what you will learn after reading the FAQ - that 5 will never be hit exactly because 0.1 is not a power of 2.
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!