C语言double里的deta,蚁群算法(C语言版)

蚁群算法的C语言实现

//段海滨教授主编的《蚁群算法原理及其应用》附录里的C程序代码. 并有几位网友修改。

//Basic Ant Colony Algorithm for TSP

#include

#include

#include

#include

#include

#include

#include

#define N 31 //city size

#define M 31 //ant number

double inittao=1;

double tao[N][N];

double detatao[N][N];

double distance[N][N];

double yita[N][N];

int tabu[M][N];

int route[M][N];

double solution[M];

int BestRoute[N];

double BestSolution=10000000000;

double alfa,beta,rou,Q;

int NcMax;

void initparameter(void); // initialize the parameters of basic ACA

double EvalueSolution(int *a); // evaluate the solution of TSP, and calculate the length of path

void InCityXY( double x[], double y[], char *infile ); // input the nodes' coordinates of TSP

void initparameter(void)

{

alfa=1; beta=5; rou=0.9; Q=100;

NcMax=200;

}

void main(void)

{

int NC=0;

initparameter();

double x[N];

double y[N];

InCityXY( x, y, "city31.tsp" );

for(int i=0;i

for(int j=i+1;j

{

distance[j][i]=sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]));

distance[i][j]=distance[j][i];

}

// calculate the heuristic parameters

for(i=0;i

for(int j=0;j

{

tao[i][j]=inittao;

if(j!=i)

yita[i][j]=100/distance[i][j];

}

for(int k=0;k

for(i=0;i

route[k][i]=-1;

srand(time(NULL));

for(k=0;k

{

route[k][0]=k%N;

tabu[k][route[k][0]]=1;

}

//each ant try to find the optiamal path

do {

int s=1;

double partsum;

double pper;

double drand;

//ant choose one whole path

while(s

{

for(k=0;k

{

int jrand=rand()%3000;

drand=jrand/3001.;

partsum=0;

pper=0;

for(int j=0;j

{

if(tabu[k][j]==0)

partsum+=pow(tao[route[k][s-1]][j],alfa)*pow(yita[route[k][s-1]][j],beta);

}

for(j=0;j

{

if(tabu[k][j]==0)

pper+=pow(tao[route[k][s-1]][j],alfa)*pow(yita[route[k][s-1]][j],beta)/partsum;

if(pper>drand)

break;

}

tabu[k][j]=1;

route[k][s]=j;

}

s++;

}

// the pheromone is updated

for(i=0;i

for(int j=0;j

detatao[i][j]=0;

for(k=0;k

{

solution[k]=EvalueSolution(route[k]);

if(solution[k]

{

BestSolution=solution[k];

for(s=0;s

BestRoute[s]=route[k][s];

}

}

for(k=0;k

{

for(s=0;s

detatao[route[k][s]][route[k][s+1]]+=Q/solution[k];

detatao[route[k][N-1]][route[k][0]]+=Q/solution[k];

}

for(i=0;i

for(int j=0;j

{

tao[i][j]=rou*tao[i][j]+detatao[i][j];

if(tao[i][j]<0.00001)

tao[i][j]=0.00001;

if(tao[i][j]>20)

tao[i][j]=20;

}

for(k=0;k

for(int j=1;j

{

tabu[k][route[k][j]]=0;

route[k][j]=-1;

}

NC++;

} while(NC

//ou

tput the calculating results

fstream result;

result.open("optimal_results.log", ios::app);

if(!result)

{

cout<

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值