Fzero for Colebrook Equation

조회 수: 6(최근 30일)
Tony Rankin
Tony Rankin 2021년 3월 14일
댓글: Rik 2021년 3월 16일
I am having no success in using fzero for
f = -1/sqrt(x)-2.*log10(((e./D)./3.7)+2.51/(Re*sqrt(x)))
[0 0.1]
Can someone please help with this? I want to know the iterations, root, time elapsed, and error.
I would ideally like to use the version that uses a function file, f.m.
  댓글 수: 2

댓글을 달려면 로그인하십시오.

채택된 답변

John D'Errico
John D'Errico 2021년 3월 14일
What you do not understand is that function have their own workspaces. If you create thse variables outside the function, then call it without passing in these variables, the function will fail, because it cannot "see" those variables. They don't exist in the function workspace. (Nested functions can see variables above them.)
If you insist on using an m-file function, then this should work:
p = 0.9*1000;
mu = 8*0.001;
e = 0.01;
D = 4*0.0254;
Q = (2000*42*3.785*10^-3)/(24*60*60);
A = (pi*(D.^2))/4;
Re = (p*D*Q)/(A*mu);
x0 = 0.01;
fplot(@(x) myfun(x,e,D,Re),[0,10])
I've plotted the function to see if a root does exist. Only now do I want to use fzero.
Also, note the use of fzero where I provide a bracket around the root. When you give it only ONE value, then it must do a search. And negative values for x will cause problems with your function.
options = optimset('Display','iter');
[xval,fval,exitflag] = fzero(@(x) myfun(x,e,D,Re),[eps,10],options)
Func-count x f(x) Procedure 2 10 2.82898 initial 3 10 2.82898 interpolation 4 5 2.69594 bisection 5 2.5 2.5078 bisection 6 1.25 2.24175 bisection 7 0.625 1.86552 bisection 8 0.3125 1.33353 bisection 9 0.15625 0.581296 bisection 10 0.078125 -0.482273 bisection 11 0.113551 0.136933 interpolation 12 0.105717 0.0273238 interpolation 13 0.103868 -0.000326184 interpolation 14 0.10389 4.29348e-06 interpolation 15 0.10389 6.66853e-10 interpolation 16 0.10389 -4.44089e-16 interpolation 17 0.10389 -4.44089e-16 interpolation Zero found in the interval [2.22045e-16, 10]
xval = 0.1039
fval = -4.4409e-16
exitflag = 1
Save this function as an m-file. Note my use of ./ operator. It seems you know about .* but the ./ operator has escaped your attention.
function y = myfun(x,e,D,Re)
y = -1./sqrt(x)-2.*log10(((e./D)./3.7)+2.51./(Re*sqrt(x)));
As far as being told the time elapsed, you can use tic and toc, I suppose. fzero does not return that. I have no clue what you mean by the "error".
  댓글 수: 4
John D'Errico
John D'Errico 2021년 3월 16일
I'd suggest you get used to the idea that functions are best kept separate from your scripts. This is far better programming practice. Now you can use a general function, to be used to solve many different problems, not just one. Don't encapsulate your code with your data. That is just poor programming practice.

댓글을 달려면 로그인하십시오.

추가 답변(0개)

Community Treasure Hunt

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

Start Hunting!

Translated by