Why won't my while loop terminate?

조회 수: 14 (최근 30일)
Riley Schmitt
Riley Schmitt 2020년 12월 8일
답변: Cris LaPierre 2020년 12월 8일
I'm basically trying to get the value of "F" be within 10% of the "W" value. When I run this code and watch the output, I can see the "forceErr" values drop below 10% but my while loop won't terminate for some reason. Can anyone figure out why?
format long
r = 0.1;
h = 0.5;
m = 6;
g = 9.81;
W = m*g;
rhoFluid = 1000;
forceErr = 1;
while forceErr > 0.1
for z = 0:0.01:0.5
pressure = rhoFluid*g*z;
for theta = 0:pi/50:2*pi
A = 1/2*r^2*theta;
F = A*pressure;
forceErr = abs((F - W)/W)
end
end
end

채택된 답변

Cris LaPierre
Cris LaPierre 2020년 12월 8일
Because forceErr is never <= 0.1.
Your while loop is actually unnecessary here. It doesn't add to the solution. It will just recompute the exact same results as before. Everything is actually happening inside your for loops.
What you might want to do is replace the outer for loop with a while loop. Before the while loop, define an initial value for z. Then, inside the while loop, increment that value of z by some amount each time. This will allow your value for pressure to continue changing until a result is found that meets your stopping criteria.

추가 답변 (1개)

James Tursa
James Tursa 2020년 12월 8일
편집: James Tursa 2020년 12월 8일
The forceErr you are calculating happens for every iteration of the for-loop. The forceErr that the while-loop sees is only for the last iteration of the for-loop. I'm guessing you need to change your logic to look at each iteration. E.g., something like this logic:
for z = 0:0.01:0.5
pressure = rhoFluid*g*z;
for theta = 0:pi/50:2*pi
A = 1/2*r^2*theta;
F = A*pressure;
forceErr = abs((F - W)/W)
if forceErr <= 0.1
break;
end
end
% this is where the break takes you
end
You will have to modify the above to code what needs to happen once you reach the desired forceErr condition. Maybe break out of the outer for-loop also? Are you trying to find the first place where z and theta give you the desired forceErr condition?

카테고리

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