How do I avoid Infinite loop?
4 ビュー (過去 30 日間)
古いコメントを表示
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.
1 件のコメント
回答 (2 件)
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
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
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.
1 件のコメント
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!