1、选取初始点x0,令k=0;
2、选取方向pk,使f(x)沿plk方向函数值下降(pk为搜索方向);
3、从xk出发以pk为方向作射线xk+lamdapk,在此射线上求f(x)的最小值;即:
min f(xk+lamdapk)=f(x[k+1]) 其中,lamda>=0;
4、判别x[k+1]是否为最优解x*,若|f’(x[k+1])|成功-失败法
%成功-失败法函数
function [xo,fo]=succeed_fail(x,f,h,e)
h = abs(h);
e = abs(e);
phi1=subs(f,x)
while 1
while 1
phi2=double(subs(f,x+h))
if phi1 > phi2
x=x+h
phi1=phi2
h=2*h
break;
end
if abs(h) > e
h=-h/4
break;
end
end
if abs(h) <= e
break;
end
end
xo = x;
fo = double(subs(f,x));
%成功-失败法函数测试
clear all;clc;
syms x
f = x^4 - 4*x^3 - 6*x^2 - 16*x + 4
[x0,f0] = succeed_fail(0,f,1,0.001)
0.618法(黄金分割法)
%0.618法函数
function [xo,fo]=zero_point_618(a,b,f,e)
if a>b
t=a;a=b;b=t;
end
e=abs(e)
x1=a+0.382*(b-a)
x2=a+b-x1
L=double(subs(f,x1))
R=double(subs(f,x2))
while 1
if L
%0.618法函数测试
clear all;clc;
syms x
f = x^4 - 4*x^3 - 6*x^2 - 16*x + 4
[x0,f0] = zero_point_618(0,5,f,0.01)
二分法
%二分法函数
function [xo,fo]=twohalf(a,b,f,df,e)
if a>b
t=a;a=b;b=t;
end
e=abs(e)
while 1
m = (a+b)/2;
if abs(subs(df,m))
%二分法函数测试
clear all;clc;
syms x
f = x^4 - 4*x^3 - 6*x^2 - 16*x + 4
df = diff(f)
[x0,f0] = twohalf(5,2,f,df,0.01)
牛顿法
%牛顿法函数
function [xo,fo]=Newton(x,f,df,ddf,e)
e=abs(e);
while 1
xo=x-double(subs(df,x)/subs(ddf,x))
if double(subs(df,xo))
%牛顿法函数测试
clear all;clc;
t1=clock;
syms x
f = x^4 - 4*x^3 - 6*x^2 - 16*x + 4
df = diff(f)
ddf =diff(df)
[x0,f0] = Newton(6,f,df,ddf,0.01)
t2=clock;
etime(t2,t1)
二次插值法
%二次插值法函数
function [xo,fo]=interpolation2(x1,x2,x3,f,e)
while 1
c1=(subs(f,x3)-subs(f,x1))/(x3-x1);
c2=((subs(f,x2)-subs(f,x1))/(x2-x1)-c1)/(x2-x3);
xo=double(0.5*(x1+x3-c1/c2));
if abs(xo-x2)
%二次插值法函数测试
clear all;clc;
t1=clock;
syms x
f = x^4 - 4*x^3 - 6*x^2 - 16*x + 4;
[x0,f0] = interpolation2(3,3.5,5,f,0.01)
t2=clock;
etime(t2,t1)
三次插值法
%三次插值法函数
function [xo,fo]=interpolation3(f,df,a,h,e)
e=abs(e);
v=subs(df,a);
u = v;
if abs(v) < e
xo = a
else
while abs(v) >= e
if v < 0
h = abs(h)
else
h = -abs(h)
end
while u * v >= 0
b = a + h
u = double(subs(df,b))
if abs(u) < e
xo = b;break;
else
if u * v <0
break;
else
h = 2 * h
v = u
a = b
end
end
end
if abs(u) < e
break;
end
s = double(3*(subs(f,a)-subs(f,b))/(b-a))
z = double(s-u-v)
w = double((z^2-u*v)^0.5)
a = double(a-(b-a)*v/(z-w*sign(v)-v))
v = double(subs(df,a))
if abs(v) < e
xo = a;break;
else
h = h/10
end
end
end
fo=double(subs(f,xo));
%三次插值法函数测试
clear all;clc;
t1=clock;
syms x
f = x^4 - 4*x^3 - 6*x^2 - 16*x + 4;
df = diff(f);
[x0,f0] = interpolation3(f,df,0,1,0.5)
t2=clock;
etime(t2,t1)