模拟退火算法求最大值:
clear,close all;clc;
y=@(x)10*(x-2*(sin(x)).^2).^2 %目标函数
%……初始参数表……%
t1=100; %初始温度
t0=1; %终止温度
w=0.9 %衰减系数(经验在0.9-0.99之间,w越大搜索次数越多)
xmax=13,xmin=-13;%搜索范围在[-13,13]之间
xcurrent=0 %当前解
xnew=0 %新解
xbest=0%最优解
%……初始参数表……%
[hp,hn,hb]=show(y,xmax,xmin,xcurrent,xnew,xbest);%作图
while t1>t0
for i=1:100%降一次温搜索100次
step=0.3;%搜索步长
xnew=xcurrent+step*xmax*(rand-0.5);%扰动(rand-0.5)是(-0.5,0.5)之间的随机数
if xnew>xmax||xnew<xmin
continue %限制x坐标在规定范围内
end
%比较过程
if y(xnew)>y(xcurrent)
xcurrent=xnew;
%记忆化过程
if y(xnew)>y(xbest)
xbest=xnew;
end
%Metroplis准则
elseif exp(y(xnew)-y(xcurrent)./t1)>rand %(y(xnew)-y(xcurrent))<0
xcurrent=xnew;%以一定的概率接受新解
else
xcurrent=xcurrent;%否则不接受
end
%%更新图像
set(hn,'xdata',xnew,'ydata',y(xnew));
pause(0.1); %0.1秒暂停一下
set(hp,'xdata',xcurrent,'ydata',y(xcurrent));
set(hb,'xdata',xbest,'ydata',y(xbest));
end
t1=t1*w;%降温
xlabel(sprintf('最大值=%.1f',y(xbest)),'fontsize',13);%x轴显示动态的最大值,即从局部最优解变化到全局最优解的过程
title(sprintf('T=%.1f',t1),'fontsize',13);%标题显示温度的变化
end
function [hp,hn,hb]=show(y,xmax,xmin,xcurrent,xnew,xbest)
x=xmin:0.1:xmax;
plot(x,y(x),'-k');
hold on
hp=plot(xcurrent,y(xcurrent),'o','markersize',10,'markerfacecolor','r');
hn=plot(xnew,y(xnew),'o','markersize',10,'markerfacecolor','y');
hb=plot(xbest,y(xbest),'o','markersize',10,'markerfacecolor','b')
end