#程序
function g=bisectfun(f,a,b,tol)
% bisectfun.m函数为编写的利用二分法求解非线性方程组的函数
% f为方程f(x)=0中的f(x)
% a为区间的左端点
% b为区间的右端点
% tol为根的精度
% g为求的根
if (nargin==3)
tol=1.0e-6;
end
g=compute_bisect(f,a,b,tol);
function r=compute_bisect(f,a,b,tol)
% 计算左端点函数值
fa=subs(f,a);
% 计算右端点函数值
fb=subs(f,b);
% 区间中点函数值
fab=subs(f,(a+b)/2);
if(fa*fab>0)
t=(a+b)/2;
%采用递归方法
r=compute_bisect(f,t,b,tol);
else
if(fa*fab==0)
r=(a+b)/2;
else
if(abs(b-a)<=tol)
r=(b+3*a)/4;
else
s=(a+b)/2;
r=compute_bisect(f,a,s,tol);
end
end
end
clear all;
tol=1e-6;
f=inline('x^3-3*x+1');a=-1;b=1;
g=bisectfun(f,a,b,tol)
错误使用 sym>tomupad (line 1229)
Unable to convert 'inline' to 'sym'.
出错 sym (line 211)
S.s = tomupad(x);
出错 subs (line 68)
r_unique_name = subs(sym(f_unique_name),varargin{:});
出错 bisectfun>compute_bisect (line 15)
fa=subs(f,a);
出错 bisectfun (line 11)
g=compute_bisect(f,a,b,tol);
clear all;
g=bisectfun('x^3-3*x+1',-1,1,1e-6)
错误使用 sym>convertChar (line 1448)
Character vectors and strings in the first argument can only specify a variable or number. To evaluate character
vectors and strings representing symbolic expressions, use 'str2sym'.
出错 sym>tomupad (line 1214)
S = convertChar(x);
出错 sym (line 211)
S.s = tomupad(x);
出错 subs (line 68)
r_unique_name = subs(sym(f_unique_name),varargin{:});
出错 bisectfun>compute_bisect (line 15)
fa=subs(f,a);
出错 bisectfun (line 11)
g=compute_bisect(f,a,b,tol);