while true vs. for i= 1:Inf
3 次查看(过去 30 天)
显示 更早的评论
So I was recently posed with the question, what is the difference between a while true loop and a for i = 1:Inf loop. I have done quite a bit of research, but I cannot seem to come up with an answer. Do you know?
0 个评论
回答(3 个)
James Tursa
2012-12-13
编辑:James Tursa
2012-12-13
In addition to what Per Isakson has written, I would add that the loop variable, after a certain point, will lose precision and become ill-defined. I think MATLAB will try to gracefully provide a value for ii, but after a point the successive ii's will be equal to each other until the background rounding scheme clocks it over into the next representable value. (As I recall, there was a previous similar thread some time ago that explored this topic)
Azzi Abdelmalek
2012-12-13
k=0;
while rand<0.8
k=k+1;
end
The while loop will run until a condition rand < 0.8 is false, we don't know when it occurs, because rand is a random number. In this case we can't use a for loop
2 个评论
michal.markun
2022-12-28
Why not? Even if slightly longer code...
for k=1:Inf,
if rand>=0.8,
break,
end;
end;
Walter Roberson
2022-12-28
Because it might take more than 281474976710655 iterations which is the limit for 1:inf loops.
另请参阅
类别
在 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!