How do I avoid Infinite loop?

5 次查看(过去 30 天)
Shashanka
Shashanka 2014-7-13
I am facing an 'Infinite Loop' condition in the attached piece of code. The 'AxIF' is to be updated with each iteration with the latest value of 'AxIFN'. Finally giving a value of 'AxIFN' which is less than '0.4'. After which the loop is exited.

回答(2 个)

Image Analyst
Image Analyst 2014-7-13
AxIF will never equal 0.4 to the 15th decimal place. To find out why, 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. Try checking within a tolerance like the FAQ suggests:
if abs(AxIF-0.4) < 0.00001 % Or whatever tolerance you want.
  1 个评论
Image Analyst
Image Analyst 2014-7-13
Or maybe you wanted <= instead of ==.
if AxIF <= 0.4
break;
end
If it still doesn't exit the loop, step through it with the debugger to figure out why. http://blogs.mathworks.com/videos/2012/07/03/debugging-in-matlab/

请先登录,再进行评论。


Roger Stafford
Roger Stafford 2014-7-13
编辑:Roger Stafford 2014-7-13
Your use of the while loop is inappropriate for the problem you are dealing with. You stated, "The 'AxIF' is to be updated with each iteration with the latest value of 'AxIFN'. Finally giving a value of 'AxIFN' which is less than '0.4'. After which the loop is exited." This, along with the test "AxIF < 0.4", shows a misunderstanding of how the 'while' command functions. You are apparently waiting for the sequence of AxIFN values to converge to a limit which you hope will be less than 0.4 . It is not nearly that smart. As you have learned to your sorrow, the while loop will never stop the way you have written the code.
To test that convergence has been achieved you need to test that successive values of AxIF are sufficiently close to one another that the sequence has essentially converged. You can do that according to this outline:
AxIF = 0.3543;
AxIFN = inf; % Set this to ensure initial entry into the while loop
while abs(AxIF-AxIFH) >= tol (<-- Corrected))
AxIFN = AxIF;
Calculate the next value of AxIF from AxIFN
....
(Don't do AxIFN = AxIF down here)
end
where 'tol' is some positive quantity so small that it indicates essentially successful convergence - that is, near equality of two successive values.

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by