登录论坛

查看完整版本 : [讨论]用二分法求函数根的程序


chc33
2008-04-26, 13:21
各位好!我正练习用matlab做数值计算,我从书上抄了一个用二分法求函数根的程序,但不知老师提醒我输入函数无效请问该怎么弄?源程序如下:
function [c,err,yc]=bisect(f,a,b,delta)
%Input -f is the function input as a string 'f'
% -a and b are the left and right end points
% -delta is the tolerance
%-Output -c is the zero
% -yc=f(c)
% -err is the error estimate for c
ya=feval(f,a);
yb=feval(f,b);
if ya*yb>0,return,end
max1=1+round((log(b-a)-log(delta))/log(2));
for k=1:max1
c=(a+b)/2;
yc=feval(f,c);
if yc==0
a=c;
b=c;
elseif yb*yc>0
b=c;
yb=yc;
else
a=c;
ya=yc;
end
if b-a<delta,break,end
end
c=(a+b)/2;
err=abs(b-a);
yc=feval(f,c);
我在命令窗口输入:bisect('x^3-2*x+2',-10,10,0.001)
结果显示
??? Invalid function name 'x^3-2*x+2'.

Error in ==> bisect at 8
ya=feval(f,a);

sblyb444
2013-09-11, 15:21
改成这样
f = @(x)x^3-2*x^2+2;
>> bisect(f,-10,10,0.001)
即可