旅行商问题,即TSP问题(Travelling Salesman Problem)又译为旅行推销员问题、货郎担问题,是数学领域中著名问题之一。假设有一个旅行商人要拜访n个城市,他必须选择所要走的路径,路径的限制是每个城市只能拜访一次,而且最后要回到原来出发的城市。路径的选择目标是要求得的路径路程为所有路径之中的最小值。来自百度百科解释这里写链接内容
先写上模拟退火算法主干:
function [SA,mincity]=TPS_SA(T,delta,city0,eps)
% 退火算法,T为初始温度,delta为衰减因子,x0为初始值,eps为精度对应于温度下限,
i=1;
while (T>eps)
for j=1:100
city1=Exchange(city0);
dE=Distance(city1)-Distance(city0);
if (dE<0)
city0=city1;%移动后得到优解
else
if(exp(dE/T)<rand(1))%以一定概率移动。
city0=city1;
end
end
end
T=T*delta;
i=i+1;
end
SA=Distance(city0);
mincity=city0;
line(mincity(1,:),mincity(2,:),'color','red');
计算城市距离的函数
function distance=Distance(city)
%city=[x1 x2 x3;y1 y2 y3]的对应的城市坐标
NumberCity=length(city);
city1=city';
distance=0;
for i=1:NumberCity-1
distance=distance+pdist(city1(i:i+1,:));
end
if NumberCity>=3
distance=distance+pdist([city1(1,:);city1(NumberCity,:)]);
end
交换路线0的代码:
function city1=Exchange(city0)
NumberCity=length(city0);
n=round((NumberCity-2)*rand(1)+2);%产生(2-NumberCity之间的数)
m=round((NumberCity-2)*rand(1)+2);%产生(2-NumberCity之间的数)
city2=city0(:,m);
city0(:,m)=city0(:,n);
city0(:,n)=city2;
city1=city0;
function main()
T=100;
city0=[0.6606,0.9695,0.5906,0.2124,0.0398,0.1367,0.9536,0.6091,0.8767,0.8148,0.3876,0.7041,0.0213,0.3429,0.7471,0.4606,0.7695,0.5006,0.3124,0.0098,0.3637,0.5336,0.2091,0.4767,0.4148,0.5876,0.6041,0.3213,0.6429,0.7471; 0.9500,0.6740,0.5029,0.8274,0.9697,0.5979,0.2184,0.7148,0.2395,0.2867,0.8200,0.3296,0.1649,0.3025,0.8192,0.6500,0.7420,0.0229,0.7274,0.4697,0.0979,0.2684,0.7948,0.4395,0.8867,0.3200,0.5296,0.3649,0.7025,0.9192];
delta=0.99;
eps=1e-6;
[d,city1]=TPS_SA(T,delta,city0,eps);
d
plot(city1(1,:),city1(2,:),'*');
hold on;
line(city1(1,:),city1(2,:),'color','red');
当然模拟退火算法不是一定就可以找到最优解,只是近似最优解。计算多次会出现多次值,
如distance=5.8600
此时的
改变参数也可以改进distance的值,如detal,eps等等。或者利用遗传算法与模拟退火算法结合,求得最优解。