clear
clc%生成初始解
sol_new2=1;%(1)解空间(初始解)sol_new1=2-sol_new2^2;sol_current1 = sol_new1; sol_best1 = sol_new1;sol_current2 = sol_new2; sol_best2 = sol_new2;E_current = inf;E_best = inf;rand('state',sum(clock)); %初始化随机数发生器
t=90; %初始温度tf=89.9; %结束温度a = 0.99; %温度下降比例while t>=tf%(7)结束条件
for r=1:1000 %退火次数 %产生随机扰动(3)新解的产生 sol_new2=sol_new2+rand*0.2; sol_new1=2-sol_new2^2; %检查是否满足约束 if sol_new1^2-sol_new2>=0 && -sol_new1-sol_new2^2+2==0 && sol_new1>=0 &&sol_new2>=0 else sol_new2=rand*2; sol_new1=2-sol_new2^2; continue; end %退火过程 E_new=sol_new1^2+sol_new2^2+8;%(2)目标函数 if E_new<E_current%(5)接受准则 E_current=E_new; sol_current1=sol_new1; sol_current2=sol_new2; if E_new<E_best %把冷却过程中最好的解保存下来 E_best=E_new; sol_best1=sol_new1; sol_best2=sol_new2; end else if rand<exp(-(E_new-E_current)/t)%(4)代价函数差 E_current=E_new; sol_current1=sol_new1; sol_current2=sol_new2; else sol_new1=sol_current1; sol_new2=sol_current2; end end plot(r,E_best,'*') hold on end t=t*a;%(6)降温enddisp('最优解为:')
disp(sol_best1)disp(sol_best2)disp('目标表达式的最小值等于:')disp(E_best)
---------------------------------
function len=computer_tour(city,n) %计算路线总长度,每个城市只计算和下家城市之间的距离。
len=0; for i=1:n-1 len=len+sqrt((city(i).x-city(i+1).x)^2+(city(i).y-city(i+1).y)^2); end len=len+sqrt((city(n).x-city(1).x)^2+(city(n).y-city(1).y)^2);end------------------------------------
function city=perturb_tour(city,n)
%随机置换两个不同的城市的坐标 %产生随机扰动 p1=floor(1+n*rand()); p2=floor(1+n*rand());while p1==p2
p1=floor(1+n*rand()); p2=floor(1+n*rand()); end %exchange the random two cities tmp=city(p1); city(p1)=city(p2); city(p2)=tmp;end
------------------------
function netplot(city,n) %连线各城市,将路线画出来
hold on; for i=1:n-1 plot(city(i).x,city(i).y,'r*'); line([city(i).x city(i+1).x],[city(i).y city(i+1).y]); %只连线当前城市和下家城市 endplot(city(n).x,city(n).y,'r*');
line([city(n).x city(1).x],[city(n).y city(1).y]); %最后一家城市连线第一家城市 hold off;end