1)用0.618法求解min f(x) =,初始区间为[-1,1],区间精度为δ = 0.05.
function [ s,phis,k,G,E] = golds( phi,a,b,delta,epsilon )
t = (sqrt(5)-1)/2; h = b-a;
phia = feval(phi,a);phib = feval(phi,b);
p = a + (1-t)*h;q = a+t*h;
phip =feval(phi,p);phiq =feval(phi,q);
k = 1;G(k,:) = [a,p,q,b];
phi_values(k,:) = [phia, phib];
while(abs(phib-phia)>epsilon) |(h>delta)
if(phip<phiq)
b=q; phib = phiq; q=p;phiq = phip;
h=b-a;p=a +(1-t)*h;phip = feval(phi,p);
else
a=p; phia = phip; p=q;phip = phiq;
h=b-a;q=a +t*h;phiq = feval(phi,q);
end
k = k+1;G(k,:) = [a,p,q,b];
end
ds = abs(b-a);dphi = abs(phib -phia);
if(phip<=phiq)
s = p;phis = phip;
else
s = q;phis = phiq;
end
E = [ds,dphi];
2)用抛物线法求min f(x) = 的近似最优解,初始搜索区间为[0,3],初始插值点=1,终止条件为||<δ = 0.01.
function [ a,phis,ds,dphi,S ] = qmin( phi,a,b,delta,epsilon )
s0 = 1; maxj = 20;maxk = 30;big = 1e6;err = 1; k =1;
S(k) = s0;cond = 0;h = 1; ds = 0.00001;
if(abs(s0)>1e4),h = abs(s0)*(1e-4);end
%cond~=5?不等于的意思
while(k<maxk&err>epsilon&cond~=5)
%确定单峰区间
f1 = (feval(phi,s0+ds)-feval(phi,s0-ds))/(2*ds);
if(f1>0),h = -abs(h);end
s1 = s0+h ; s2 = s0+2*h; bars = s0;
phi0 =feval(phi,s0);phi1 =feval(phi,s1);
phi2 =feval(phi,s2); barphi = phi0; cond = 0;
j = 0;
while(j<maxj&abs(h)>delta&cond==0)
if(phi0<=phi1),
s2 = s1;phi2 = phi1;h = 0.5*h;
s1 = s0+h;phi1 = feval(phi,s1);
else if(phi2<phi1),
s1 = s2;phi1 = phi2;h = 2*h;
s2 = s0+h*2;phi2 = feval(phi,s2);
else
cond =- 1;
end
end
j = j+1;
if(abs(h)>big | abs(s0)>big),cond =5;end
end
if(cond==5)
bars =s1;barphi = feval(phi,s1);
else
d = 2*(2*phi1-phi0-phi2);
if(d<0),
barh = h*(4*phi1-3*phi0-phi2)/d;
else
barh = h/3;cond = 4;
end
bars = s0+barh; barphi = feval(phi,bars);
h= abs(h);h0 = abs(barh);
h1 = abs(barh - h);h2 = abs(barh - 2*h);
if(h0<h),h =h0;end
if(h1<h),h =h1;end
if(h2<h),h =h2;end
if(h==0),h = barh;end
if(h<delta),cond = 1;end
if(abs(h)>big |abs(bars)>big),cond = 5;end
err = abs(phi1-barphi);
s0 = bars;k=k+1;S(k) = s0;
end
if(cond == 2&h<delta),cond=3;end
end
s =s0;phis = feval(phi,s);
ds = h;dphi = err;
end
3)利用书中所给的Armijo搜索Matlab程序计算下面的问题:min φ(x) = f(),其中f(x) = .
function f = fun(x)
f = 100*(x(2)-x(1)^2)^2 + (1-x(1))^2;
end
function gf = gfun(x)
gf = [-400*x(1)*(x(2)-x(1)^2)-2*(1-x(1)),200*(x(2)-x(1)^2)]';
end
function mk = armijo(xk,dk)
beta = 0.5;sigma = 0.2;
m = 0;mmax = 20;
while(m <= mmax)
if(fun(xk+beta^m*dk)<=fun(xk)+sigma*beta^m*gfun(xk)'*dk)
mk = m;break;
end
m = m + 1;
end
alpha = beta^mk
newxk = xk +alpha*dk
fk = fun(xk)
newfk = fun(newxk)
end