方法一:二分法
function [x] =bisection(f,a,b,e)
if f(a)*f(b)>=0
x='there is no root in (a,b), please try another (a,b)';
else
while abs(a-b)>e
c=(a+b)/2;
if f(c)==0
x=c;
break
elseif f(c)*f(a)<0
b=c;
elseif f(c)*f(a)>0
a=c;
end
end
x=(a+b)/2;
end
end
方法二:不动点迭代
function [x] = fixpoint(g,dg,x0,e)
if abs(dg(x0))>=1
x='x0 cannot converge to x under this fixpoint function g';
else
x1=g(x0);
while abs(x1-x0)>=e
x0=x1;
x1=g(x0);
end
x=x1;
end
end
方法三:牛顿法
function [x] =newton(f,df,x0,e)
x1=x0-(f(x0)/df(x0));
if abs(f(x1))>=abs(f(x0))
disp('this x0 can not converge to x, please change');
else
while abs(x1-x0)>=e
x0=x1;x1=x0-(f(x0)/df(x0));
end
x=x1;
end
end
使用范例:
clear
clc
%set the problem
f=@(x)sin(x)-6*x-5; e=1e-3;
disp('solution for sinx=6*x+5')
%bisection method
a=-1;b=1;x=bisection(f,a,b,e);
disp('bisection method:x=');disp(x);
%fixpoint method
g=@(x)sin(x)/6-5/6; dg=@(x)cos(x)/6;
x0=0.5;x=fixpoint(g,dg,x0,e);
disp('fixpoint method:x=');disp(x);
%newton method
df=@(x)cos(x)-6;x0=0.5;x=newton(f,df,x0,e);
disp('newton method:x=');disp(x);
%set the problem
f=@(x)log(x)+x^2-3; e=1e-3;
disp('solution for lnx+x^2=3')
%bisection method
a=1;b=2;x=bisection(f,a,b,e);
disp('bisection method:x=');disp(x);
%fixpoint method
g=@(x)(3-log(x))^0.5;dg=@(x)-0.5*(x^(-1))*((3-log(x))^(-0.5));
x0=1;x=fixpoint(g,dg,x0,e);
disp('fixpoint method:x=');disp(x);
%newton method
df=@(x)2*x+x^(-1);
x0=1;x=newton(f,df,x0,e);
disp('newton method:x=');disp(x);
%set the problem
f=@(x)exp(x)+x-7; e=1e-3;
disp('solution for e^x+x=7')
%bisection method
a=1;b=2;x=bisection(f,a,b,e);
disp('bisection method:x=');disp(x);
%fixpoint method
g=@(x)log(7-x);dg=@(x) (x-7)^(-1);
x0=1;x=fixpoint(g,dg,x0,e);
disp('fixpoint method:x=');disp(x);
%newton method
df=@(x)exp(x)+1;
x0=1;x=newton(f,df,x0,e);
disp('newton method:x=');disp(x);