I need help with this false position script

3 次查看(过去 30 天)
I'm not sure where the issue is. Note the percent notes below the script has some commands that need to copy and pasted into the command box.
function root= fp(func,xl,xu,es,max)
if func(xl)*func(xu)>0
error('input error')
end
if nargin<5
max=50;
end
if nargin<4
es=0.001;
end
iter=0;
xr=xl;
while(1)
xrold=xr;
xr=xu-func(xu)*(xl-xu)/(func(xl)-func(xu));
iter=iter+1;
if xr~=0
ea=abs((xr-xrold)/xr)*100;
end
test=func(xl)*func(xr);
if test<0
xu=xr;
elseif test>0
xl=xr;
else
ea=0;
end
if ea<=es||iter>=max
break
end
end
root=xr;
%Type the following commands below
%format long
%fx=@(x)-12-(21*x)+(18*x^2)-(2.75*x^3)
%fp(fx,-1,0,0.001)

回答(1 个)

Stephan
Stephan 2019-10-19
编辑:Stephan 2019-10-19
No idea what your problem is, code runs for me:
format long
fx=@(x)-12-(21*x)+(18*x^2)-(2.75*x^3)
a =sprintf('%.8f', fp(fx,-1,0,0.001))
function root= fp(func,xl,xu,es,max)
if func(xl)*func(xu)>0
error('input error')
end
if nargin<5
max=50;
end
if nargin<4
es=0.001;
end
iter=0;
xr=xl;
while(1)
xrold=xr;
xr=xu-func(xu)*(xl-xu)/(func(xl)-func(xu));
iter=iter+1;
if xr~=0
ea=abs((xr-xrold)/xr)*100;
end
test=func(xl)*func(xr);
if test<0
xu=xr;
elseif test>0
xl=xr;
else
ea=0;
end
if ea<=es||iter>=max
break
end
end
root=xr;
end

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by