Simulated Annealing(模拟退火算法)
生活随笔
收集整理的這篇文章主要介紹了
Simulated Annealing(模拟退火算法)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
?
/* Simulated Annealing(模擬退火算法) 求解旅行商問題(TSP) 網(wǎng)上給的數(shù)據(jù)是31個省會的坐標(biāo),蟻群算法得到的結(jié)果是:15378 我算的結(jié)果中,最好的一次是:15495 */ #include<iostream> #include<cstdio> #include<cstdlib> //#include<ctime> #include<cmath> #include<time.h> #define N 31 //城市個數(shù) #define Tmax 8000 //初始溫度 #define Tmin 1E-10 //終止溫度 #define RATE 0.95 //溫度衰減率 #define in_loop 13000 //內(nèi)層循環(huán)次數(shù) #define out_loop 2000 //外層循環(huán)次數(shù) #define p_limit 10000 //概率選擇次數(shù)using namespace std;//31個省會x和y的坐標(biāo) double x[N]={1304,3639,4177,3712,3488,3326,3238,4196,4312,4386,3007,2562,2788,2381,1332,3715,3918,4061,3780,3676,4029,4263,3429,3507,3394,3439,2935,3140,2545,2778,2370}; double y[N]={2312,1315,2244,1399,1535,1556,1229,1004,790,570,1970,1756,1491,1676,695,1678,2179,2370,2212,2578,2838,2931,1908,2367,2643,3201,3240,3550,2357,2826,2975};//兩個城市之間的距離 double d[N][N];void init(){//初始化任意兩個城市的距離for(int i=0;i<N;i++)for(int j=0;j<i;j++){d[i][j]=d[j][i]=sqrt((y[j]-y[i])*(y[j]-y[i])+(x[j]-x[i])*(x[j]-x[i]));}for(int i=0;i<N;i++)d[i][i]=0;srand((unsigned)time(0)); }//路徑 class path{ public:path(){}~path(){}int city[N]; //依次經(jīng)過的城市編號double dis; //總的距離void totalLen(){dis=0;for(int i=0;i<N-1;i++)dis+=d[city[i]][city[i+1]];dis+=d[city[0]][city[N-1]];} };//最優(yōu)解 path bestpath;//產(chǎn)生新路徑 path newpath(path prepath){path newp = prepath;int x,y,t;do{x=rand()%N;y=rand()%N;}while(x==y);t=newp.city[x];newp.city[x]=newp.city[y];newp.city[y]=t;newp.totalLen();return newp; }//Annealing void Anne() {init();//隨機選一個初始解for(int i=0;i<N;i++)bestpath.city[i]=i;bestpath.totalLen();int out_t=0,p_t=0;double T=Tmax,delta,prob, rnd;path np,cp; //新路徑,當(dāng)前路徑cp=bestpath;while(out_t<out_loop&&T>Tmin){for(int i=0;i<in_loop;i++){np=newpath(cp);if(np.dis<cp.dis){cp=np;out_t=0;p_t=0;}else{delta=np.dis-cp.dis;prob=exp(-delta/T);rnd=rand()%10000/10000.0;if(prob>rnd)cp=np;p_t++;}if(p_t>p_limit){out_t++;break;}}if(cp.dis<bestpath.dis)bestpath=cp;T*=RATE;printf("dis= %f\n",bestpath.dis);} }int main() {Anne();return 0; }?
轉(zhuǎn)載于:https://www.cnblogs.com/littlehoom/p/3612306.html
總結(jié)
以上是生活随笔為你收集整理的Simulated Annealing(模拟退火算法)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一个很好的机器学习普及网站
- 下一篇: NDK 获取android的imei和s