外点法
clc
m=zeros(1,50);
a=zeros(1,50);
b=zeros(1,50);%最优点坐标
f0=zeros(1,50);%最优点函数值
syms d x1 x2 e;
m(1)=1;c=10;a(1)=0;b(1)=0;
f=x1^2+x2^2+e*(1-x1)^2;
f0(1)=1;
fx1=diff(f,'x1');fx2=diff(f,'x2');
for k=1:100
x1=a(k);
x2=b(k);e=m(k);
for n=1:100%梯度法最优值收敛条件求点
f1=subs(fx1);
f2=subs(fx2);
if(double(sqrt(f1^2+f2^2))<=0.002)
a(k+1)=double(x1);
b(k+1)=double(x2);
f0(k+1)=double(subs(f));
break;
else
D=(x1-d*f1)^2+(x2-d*f2)^2+e*(1-(x1-d*f1))^2;
Dd=diff(D,'d');dd=solve(Dd);x1=x1-dd*f1;x2=x2-dd*f2;
end
end
if (double(sqrt((a(k+1)-a(k))^2+(b(k+1)-b(k))^2))<=0.001)&&(double(abs((f0(k+1)-f0(k))/f0(k)))<=0.001)
a(k+1)
b(k+1)
k
f0(k+1)
break;
else
m(k+1)=c*m(k);
end
end
f0(1:k)
t=1:1:50;
plot(t,f0);
ylim([0 1]);
xlabel('k值');
ylabel('f值')
ans =
0.9999
ans =
0
k =
5
ans =
0.9999
ans =
1.0000 0.5000 0.9091 0.9901 0.9990
分析总结:外点法可对违反约束的点在目标函数内加入相应的惩罚,而对可行点不予惩罚,此法的可行点一般在可行域外部移动。随着迭代次数增加,迭代点逐渐逼近最优点,惩罚函数值始终大于并逐渐接近原始目标函数值。惩罚项逐渐降低,迭代点在可行域外。
内点法
clc;
m=zeros(1,50);a=zeros(1,50);b=zeros(1,50);f0=zeros(1,50);P0=zeros(1,50);fi=zeros(1,50);
syms x1 x2 e d;
m(1)=1;a(1)=5;b(1)=3;c=0.5;
f=x1^2+x2^2+e*(-log(x1-1));
f_=x1^2+x2^2;
P=e*(-log(1-x1));
f0(1)=1;f1(1)=34-e*log(4);P0(1)=1;fi(1)=34;
fx1=diff(f,'x1');
fx2=diff(f,'x2');
for k=1:100
e=m(k);x1=a(k);x2=b(k);
for n=1:100
f1=subs(fx1);
f2=subs(fx2);
if double(sqrt(f1^2+f2^2))<=0.0001
a(k+1)=double(x1);b(k+1)=double(x2);f0(k+1)=double(subs(f));
P0(k+1)=double(subs(P));fi(k+1)=double(subs(f_));
break
else
D=(x1-d*f1)^2+(x2-d*f2)^2+e*(-log(1-x1+d*f1));
Dd=diff(D,d);dd=vpa(solve(Dd),5);
x1=x1-dd*f1;x2=x2-dd*f2;
x1=x1(x1>=1);
x2=x2(x1>=1);
end
end
if double(sqrt((a(k+1)-a(k))^2+(b(k+1)-b(k))^2))<0.0001 && double(abs((f0(k+1)-f0(k))/f0(k)))<=0.0001
disp('最优解 x1 = ')
disp(a(k+1))
disp('x2 = ')
disp(b(k+1))
disp('此时:f(x) =')
disp(f0(k+1))
disp('迭代次数:k= ')
disp(k)
stem(k,subs(f));hold on
break
else
m(k+1)=c*m(k);
stem(k,subs(f));hold on
end
end
最优解 x1 =
1.0000
x2 =
5.3392e-16
此时:f(x) =
1.0001
迭代次数:k=18
分析总结:内点法总是从可行域的内点出发,并保持在可行域内部搜索,这种方法只适合用于不等式约束问题。其对于企图从内部穿越可行域边界的点在目标函数上加入相应的障碍,距离边界越近,障碍越大,在边界上给予无穷大的障碍,从而保障迭代一直在可行域中进行。