is for loop or while loop better?
显示 更早的评论
I'm completing a homework question, and would like advice before I continue my code.
I will paste the problem below. I chose to use a while loop to solve the problem, but would a for loop me more applicable? If so, why is that?
Here is my code:
while (2500 <= Re) && (Re <= 1000000)
f = (1/((sqrt(f)*(4*log(Re*sqrt(f))-0.4))))^2; %von Karman equation
disp(f);
end
%user inputs values here
For fluid flow in pipes, friction is described by a dimensionless number, the Fanning friction factor f. The Fanning friction factor is dependent on a number of parameters related to the size of the pipe and the fluid, which can all be represented by another dimensionless quantitiy, the Reynolds number R e. A formula that predicts f given R e is the von Karman equation:
Typical values for the Reynolds number for turbulent flow are 10,000 to 500,000 and for the Fanning Friction factor are 0.001 to 0.01. Develop a function that uses FalsePosition (es=0.000001 and maxit=200) to solve for f given a user-supplied value of Re between 2,500 and 1,000,000.
1 个评论
dpb
2021-1-22
Well, in the code given, there's no purpose in the while at all; nothing inside the loop changes the Re number to terminate the loop if it once enters it.
There could be a reason for a while in the iteration loop to solve for the friction factor, but it would be more useful for it to be comparing the convergence condition; the Re number is presumed known and fixed to solve for f
A general consideration in choosing one over the other is that for loops are best for counting and limits whereas while is good as noted above when something calculated changes and that calculation is inside the loop (a convergence as here is a prime example).
In this case you have both kinds of tests because the iteration limit is counted so you could choose to wrap the iteration inside that kind of a structure; I'd probably go the other way and build the outer loop on the convergence and just count iterations internally and break/error if exceed the maximum.
In the end, it's user's choice but those are some guiding principles.
采纳的回答
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Programming 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!