(完整版)遗传算法c语言代码

合集下载

遗传算法旅行商问题c语言代码

遗传算法旅行商问题c语言代码

遗传算法是一种模拟自然选择过程的优化算法,可以用于解决各种复杂的组合优化问题。

其中,旅行商问题是一个经典的组合优化问题,也是一个典型的NP难题,即寻找最优解的时间复杂度是指数级的。

在本文中,我们将讨论如何使用遗传算法来解决旅行商问题,并给出相应的C语言代码实现。

我们将介绍旅行商问题的数学模型,然后简要介绍遗传算法的原理,最后给出C语言代码实现。

旅行商问题是指一个旅行商要拜访n个城市,恰好拜访每个城市一次,并返回出发城市,要求总路程最短。

数学上可以用一个n*n的距离矩阵d[i][j]表示城市i到城市j的距离,问题可以形式化为求解一个排列p={p1,p2,...,pn},使得目标函数f(p)=Σd[p[i]][p[i+1]]+d[p[n]][p[1]]最小。

这个问题是一个组合优化问题,其搜索空间是一个n维的离散空间。

遗传算法是一种基于生物进化过程的优化算法,主要包括选择、交叉、变异等操作。

在使用遗传算法解决旅行商问题时,可以将每个排列p看作一个个体,目标函数f(p)看作个体的适应度,通过选择、交叉和变异等操作来搜索最优解。

以下是遗传算法解决旅行商问题的C语言代码实现:1. 我们需要定义城市的距离矩阵和其他相关参数,例如城市的数量n,种裙大小pop_size,交叉概率pc,变异概率pm等。

2. 我们初始化种裙,即随机生成pop_size个排列作为初始种裙。

3. 我们进入遗传算法的迭代过程。

在每一代中,我们首先计算种裙中每个个体的适应度,然后通过选择、交叉和变异操作来更新种裙。

4. 选择操作可以采用轮盘赌选择法,即根据个体的适应度来进行选择,适应度越高的个体被选中的概率越大。

5. 交叉操作可以采用部分映射交叉方法,即随机选择两个个体,然后随机选择一个交叉点,将交叉点之后的基因片段进行交换。

6. 变异操作可以采用变异率为pm的单点变异方法,即随机选择一个个体和一个位置,将该位置的基因值进行随机变异。

7. 我们重复进行迭代操作,直到达到停止条件(例如达到最大迭代次数或者适应度达到阈值)。

GA-遗传算法-C#代码【精品毕业设计】(完整版)

GA-遗传算法-C#代码【精品毕业设计】(完整版)

using System;using System.IO;using System.Collections;using System.Collections.Generic;using System.Text;using ponentModel;using System.Data;using System.Data.OleDb;namespace ConsoleApplication1{public class Genetic_Algorithm{Random rand=new Random();int MaxTime;//最大运行时间int popsize;//种群数量int ChromosomeLength;//染色体长度double CrossRate;//交叉率double MutateRate;//变异率double[] f;//适应度值int[] selected;//定义selected数组,用于表示需要进行交叉操作的染色体序号double[] wheel;//轮盘int[,] pregeneration;//上一代int[,] nextgeneration;//下一代int[] Best;//定义当前最优解int convergence;//定义当前最优解的已持续代数int[,] timeconstrait;public Genetic_Algorithm(int populationsize, int chromolength)//GA--构造函数,变量初始化{rand = new Random(lisecond);MaxTime = 50;popsize=populationsize;ChromosomeLength = chromolength;CrossRate = 0.8;MutateRate = 0.2;f = new double[2*popsize];selected = new int[popsize];wheel = new double[popsize + 1];pregeneration = new int[popsize, ChromosomeLength];//当前的染色体种群nextgeneration = new int[popsize, ChromosomeLength];//下一代(子代)染色体种群Best = new int[ChromosomeLength];convergence = 1;timeconstrait = new int[20, 2] { { 2, 6 }, { 1, 2 }, { 3, 4 }, { 1, 4 }, { 4, 7 }, { 3, 5 }, { 2, 6 }, { 3, 5 }, { 1, 4 }, { 3, 7 }, { 5, 7 }, { 2, 7 }, { 2, 4 }, { 4, 5 }, { 2, 5 }, { 4, 6 }, { 3, 5 }, { 1, 4 }, { 1, 5 }, { 3, 6 } };}public void RunGA()//运行{int i;CreateFirstPop();//产生初始种群i = 0;bool quit = true;while (quit){for (; i < MaxTime; i++){Console.WriteLine("The {0}th Generation..........", i + 1);CalFitness(ref pregeneration, popsize);//计算适应值PrintResult();//输出每步的结果WheelSelect();//此步确定了selected[i]的值CreateNextGeneration();//产生子代,包括被选择为selected[i]的染色体的交叉,还有变异ProduceNext();}Console.WriteLine("Press 'q' to quit, press Enter to continue.....");if (Console.Read() == 'q'){quit = false;}else{MaxTime += 50;}}}void CreateFirstPop()//产生初始种群{Console.WriteLine("Creating first generation..........\n");int i,j,r;for(i=0;i<popsize;i++){for(j=0;j<ChromosomeLength;j++){r=rand.Next(1,11);pregeneration[i, j] = r;}}}void CreateNextGeneration()//产生下一代种群(经交叉、变异){int i;for (i = 0; i < popsize; i+=2){Crossover(selected[i], selected[i + 1], i, i + 1);//将序号为selected[i]和selected[i + 1]的染色体进行交叉,产生的子代放在pregeneration中i和i+1的位置}Mutation(ref nextgeneration);//变异}void CalFitness(ref int[,] curgeneration,int number)//计算适应度值的函数{for (int i = 0; i < number; i++){double fitness = 0;for (int j = 0; j < ChromosomeLength; j++){fitness += Math.Abs(curgeneration[i, j]-j-1);}f[i] = fitness;}}void FindMax(ref double[] f, out int max)//寻找数组中最大值{int i;max = 0;for (i = 1; i < popsize; i++){if (f[i] > f[max]){max = i;}}}void FindMin(ref double[] f, out int min)//寻找数组中最小值{int i;min = 0;for (i = 1; i < popsize; i++){if (f[i] < f[min]){min = i;}}}void WheelSelect() //轮盘选择popsize个染色体(可重复),并将序号放入selected[]中,作为交叉的染色体{int i,j ,r;double sum;wheel[0] = 0; sum = 0;for (i = 0; i < popsize; i++){sum += f[i];wheel[i + 1] = wheel[i] + f[i];}for (i = 0; i < popsize; i++){r = rand.Next((int)sum);for (j = 0; j < popsize; j++){if (r > wheel[j] && r < wheel[j + 1]){selected[i] = j;break;}}}}void Crossover(int p1, int p2, int c1, int c2)//交叉==>将序号为selected[i]和selected[i + 1](这里形参是p1,p2)的染色体进行交叉,产生的子代放在pregeneration中i和i+1(这里形参是c1,c2)的位置{double dr = rand.NextDouble();if (dr < CrossRate){int[] covering_code = new int[ChromosomeLength];for (int i = 0; i < ChromosomeLength; i++)covering_code[i] = rand.Next(0, 2);for (int i = 0; i < ChromosomeLength; i++){if (covering_code[i] == 0){nextgeneration[c1, i] = pregeneration[p1, i];nextgeneration[c2, i] = pregeneration[p2, i];}else{nextgeneration[c1, i] = pregeneration[p2, i];nextgeneration[c2, i] = pregeneration[p1, i];}}}else{for (int i = 0; i < ChromosomeLength; i++){nextgeneration[c1, i] = pregeneration[p1, i];nextgeneration[c2, i] = pregeneration[p2, i];}}}void Mutation(ref int[,] curgeneration)//变异{int is_not_mutation;double dr;for (int i = 0; i < popsize; i++){dr = rand.NextDouble();if (dr < MutateRate){for (int j = 0; j < ChromosomeLength; j++){is_not_mutation = rand.Next(0, 2);if (is_not_mutation == 1)curgeneration[i, j] = rand.Next(1, 11);}}}}void PrintResult()//计算每次迭代后种群中最优解及其适应度值,平均适应值 {int i,j;int min;double average;average = 0;for (i = 0; i < popsize; i++){average += f[i];}average = (double) average / popsize;Console.Write("Average profit is {0}\n", average);FindMin(ref f, out min);//计算稳定的次数for (j = 0; j < ChromosomeLength; j++){if (pregeneration[min, j] != Best[j]){convergence = 1;goto G2;}}convergence++;G2:for (j = 0; j < ChromosomeLength; j++){Best[j] = pregeneration[min, j];}//打印相关的数据Console.Write("染色体 ");for (j = 0; j < ChromosomeLength; j++){Console.Write(pregeneration[min, j] + ",");}Console.WriteLine("");Console.WriteLine("综合目标 {0} of individual ", f[min]);Console.WriteLine("已经稳定的代数 {0} of individual ",convergence);Console.WriteLine("");}void ProduceNext()//选择==>父代和子代中popsize个最优的解进入下一代{int[,] temgeneration=new int [2*popsize,ChromosomeLength];//定义临时种群,用来将父代和子代放在一起,进行选优//将父代放入临时种群for (int i = 0; i <= popsize - 1; i++){for (int j = 0; j <= ChromosomeLength - 1; j++){temgeneration[i, j] = pregeneration[i, j];}}//将子代放入临时种群for (int i = 0; i <= popsize - 1; i++){for (int j = 0; j <= ChromosomeLength - 1; j++){temgeneration[i + popsize, j] = nextgeneration[i, j];}}CalFitness(ref temgeneration, popsize * 2);//计算临时种群(父代和子代)的各染色体适应值int []tem=new int [ChromosomeLength];//定义临时染色体,用来染色体排序时的交换...//根据临时种群(父代和子代)的各染色体适应值,进行排序for (int i = 0; i < 2*popsize - 1; i++){for (int j = i + 1; j <= 2 * popsize - 1; j++){if (f[i] > f[j]){double tem_f = f[i];f[i] = f[j];f[j] = tem_f;for (int k = 0; k < ChromosomeLength; k++){tem[k] = temgeneration[i, k];temgeneration[i, k] = temgeneration[j, k];temgeneration[j, k] = tem[k];}}}}//取临时种群中前popsize个好的染色体作为下一代种群,并将子代变为父代for (int i = 0; i <= popsize - 1; i++){for (int j = 0; j <= ChromosomeLength - 1; j++){pregeneration[i, j] = temgeneration[i, j];}}}}class Program{static void Main(string[] args){int chromosomelength = 10;int populationsize = 300;int cycle = 5;Console.WriteLine("Press Enter to start running Genetic Algorithm");Console.ReadKey();Genetic_Algorithm GA = new Genetic_Algorithm(populationsize, chromosomelength); GA.RunGA();}}}。

解TSP问题的遗传算法C语言程序

解TSP问题的遗传算法C语言程序

解TSP问题的遗传算法C语言程序#include<stdio.h>#include<stdlib.h>#include<math.h>#include<alloc.h>#include<conio.h>#include<float.h>#include<time.h>#include<graphics.h>#include<bios.h>#define maxpop 100#define maxstring 100struct pp{unsigned char chrom[maxstring];float x,fitness;unsigned int parent1,parent2,xsite;};struct pp *oldpop,*newpop,*p1;unsigned int popsize,lchrom,gem,maxgen,co_min,jrand;unsigned int nmutation,ncross,jcross,maxpp,minpp,maxxy;floatpcross,pmutation,sumfitness,avg,max,min,seed,maxold,oldrand[maxstring];unsigned char x[maxstring],y[maxstring]; float*dd,ff,maxdd,refpd,fm[201]; FILE *fp,*fp1;float objfunc(float);void statistics();int select();int flip(float);int crossover();void generation();void initialize();void report();float decode();void crtinit();void inversion();float random1();void randomize1();main(){unsigned int gen,k,j,tt;char fname[10];float ttt;clrscr();co_min=0;if((oldpop=(struct pp *)farmalloc(maxpop*sizeof(struct pp)))==NULL) {printf("memory requst fail!\n");exit(0);} if((dd=(float*)farmalloc(maxstring*maxstring*sizeof(float)))==NULL){printf("memory requst fail!\n");exit(0);} if((newpop=(struct pp *)farmalloc(maxpop*sizeof(struct pp)))==NULL){printf("memory requst fail!\n");exit(0);} if((p1=(struct pp*)farmalloc(sizeof(struct pp)))==NULL){printf("memory requst fail!\n");exit(0);} for(k=0;k<maxpop;k++) oldpop[k].chrom[0]='\0'; for(k=0;k<maxpop;k++) newpop[k].chrom[0]='\0'; printf("Enter Result Data Filename:"); gets(fname);if((fp=fopen(fname,"w+"))==NULL){printf("cannot open file\n");exit(0);}gen=0;randomize();initialize();fputs("this is result of the TSP problem:",fp);fprintf(fp,"city: %2d psize: %3d Ref.TSP_path:%f\n",lchrom,popsize,refpd);fprintf(fp,"Pc: %f Pm: %f Seed: %f\n",pcross,pmutation,seed);fprintf(fp,"X site:\n");for(k=0;k<lchrom;k++){if((k%16)==0) fprintf(fp,"\n"); fprintf(fp,"%5d",x[k]);}fprintf(fp,"\n Y site:\n"); for(k=0;k<lchrom;k++){if((k%16)==0) fprintf(fp,"\n"); fprintf(fp,"%5d",y[k]);}fprintf(fp,"\n");crtinit();statistics(oldpop);report(gen,oldpop);getch();maxold=min;fm[0]=100.0*oldpop[maxpp].x/ff; do {gen=gen+1;generation();statistics(oldpop);if(max>maxold){maxold=max;co_min=0;}fm[gen%200]=100.0*oldpop[maxpp].x/ff; report(gen,oldpop);gotoxy(30,25);ttt=clock()/18.2;tt=ttt/60;printf("Run Clock: %2d: %2d: %4.2f",tt/60,tt%60,ttt-tt*60.0);printf("Min=%6.4fNm:%d\n",min,co_min); }while((gen<100)&&!bioskey(1)); printf("\n gen= %d",gen);do{gen=gen+1;generation();statistics(oldpop);if(max>maxold){maxold=max;co_min=0;}fm[gen%200]=100.0*oldpop[maxpp].x/ff; report(gen,oldpop);if((gen%100)==0)report(gen,oldpop); gotoxy(30,25);ttt=clock()/18.2;tt=ttt/60;printf("Run Clock: %2d: %2d: %4.2f",tt/60,tt%60,ttt-tt*60.0);printf("Min=%6.4fNm:%d\n",min,co_min); }while((gen<maxgen)&&!bioskey(1));getch();for(k=0;k<lchrom;k++) {if((k%16)==0)fprintf(fp,"\n");fprintf(fp,"%5d",oldpop[maxpp].chrom[k]);}fprintf(fp,"\n");fclose(fp);farfree(dd);farfree(p1);farfree(oldpop);farfree(newpop);restorecrtmode();exit(0);}/*%%%%%%%%%%%%%%%%*/float objfunc(float x1) {float y;y=100.0*ff/x1;return y;}/*&&&&&&&&&&&&&&&&&&&*/void statistics(pop) struct pp *pop;{int j;sumfitness=pop[0].fitness; min=pop[0].fitness; max=pop[0].fitness; maxpp=0;minpp=0;for(j=1;j<popsize;j++) {sumfitness=sumfitness+pop[j].fitness;if(pop[j].fitness>max){max=pop[j].fitness;maxpp=j;}if(pop[j].fitness<min){min=pop[j].fitness;minpp=j;}}avg=sumfitness/(float)popsize;}/*%%%%%%%%%%%%%%%%%%%%*/void generation(){unsigned int k,j,j1,j2,i1,i2,mate1,mate2;float f1,f2;j=0;do{mate1=select();pp:mate2=select();if(mate1==mate2)goto pp;crossover(oldpop[mate1].chrom,oldpop[mate2].chrom,j);newpop[j].x=(float)decode(newpop[j].chrom);newpop[j].fitness=objfunc(newpop[j].x); newpop[j].parent1=mate1;newpop[j].parent2=mate2;newpop[j].xsite=jcross;newpop[j+1].x=(float)decode(newpop[j+1].chrom);newpop[j+1].fitness=objfunc(newpop[j+1].x); newpop[j+1].parent1=mate1;newpop[j+1].parent2=mate2;newpop[j+1].xsite=jcross;if(newpop[j].fitness>min){for(k=0;k<lchrom;k++)oldpop[minpp].chrom[k]=newpop[j].chrom[k];oldpop[minpp].x=newpop[j].x;oldpop[minpp].fitness=newpop[j].fitness;co_min++;return;}if(newpop[j+1].fitness>min){for(k=0;k<lchrom;k++)oldpop[minpp].chrom[k]=newpop[j+1].chrom[k];oldpop[minpp].x=newpop[j+1].x;oldpop[minpp].fitness=newpop[j+1].fitness;co_min++;return;}j=j+2;}while(j<popsize);}/*%%%%%%%%%%%%%%%%%*/void initdata(){unsigned int ch,j;clrscr();printf("-----------------------\n");printf("A SGA\n");printf("------------------------\n");/*pause();*/clrscr();printf("*******SGA DATA ENTRY AND INITILIZATION *******\n");printf("\n");printf("input pop size");scanf("%d",&popsize); printf("input chrom length");scanf("%d",&lchrom); printf("input maxgenerations");scanf("%d",&maxgen); printf("input crossoverprobability");scanf("%f",&pcross); printf("input mutationprob");scanf("%f",&pmutation); randomize1();clrscr();nmutation=0;ncross=0;}/*%%%%%%%%%%%%%%%%%%%%*/void initreport(){int j,k;printf("pop size=%d\n",popsize);printf("chromosome length=%d\n",lchrom);printf("maxgen=%d\n",maxgen);printf("pmutation=%f\n",pmutation); printf("pcross=%f\n",pcross);printf("initial generation statistics\n"); printf("ini pop maxfitness=%f\n",max); printf("ini pop avr fitness=%f\n",avg); printf("ini pop min fitness=%f\n",min); printf("ini pop sum fit=%f\n",sumfitness); } void initpop(){unsigned char j1;unsigned int k5,i1,i2,j,i,k,j2,j3,j4,p5[maxstring];float f1,f2;j=0;for(k=0;k<lchrom;k++)oldpop[j].chrom[k]=k;for(k=0;k<lchrom;k++)p5[k]=oldpop[j].chrom[k];randomize();for(;j<popsize;j++){j2=random(lchrom);for(k=0;k<j2+20;k++){j3=random(lchrom);j4=random(lchrom);j1=p5[j3];p5[j3]=p5[j4];p5[j4]=j1;}for(k=0;k<lchrom;k++)oldpop[j].chrom[k]=p5[k]; }for(k=0;k<lchrom;k++)for(j=0;j<lchrom;j++)dd[k*lchrom+j]=hypot(x[k]-x[j],y[k]-y[j]);for(j=0;j<popsize;j++) {oldpop[j].x=(float)decode(oldpop[j].chrom); oldpop[j].fitness=objfunc(oldpop[j].x);oldpop[j].parent1=0;oldpop[j].parent2=0;oldpop[j].xsite=0;}}/*&&&&&&&&&&&&&&&&&*/void initialize(){int k,j,minx,miny,maxx,maxy; initdata();minx=0;miny=0;maxx=0;maxy=0;for(k=0;k<lchrom;k++){x[k]=rand();if(x[k]>maxx)maxx=x[k]; if(x[k]<minx)minx=x[k]; y[k]=rand();if(y[k]>maxy)maxy=y[k]; if(y[k]<miny)miny=y[k]; }if((maxx-minx)>(maxy-miny)){maxxy=maxx-minx;}else {maxxy=maxy-miny;}maxdd=0.0;for(k=0;k<lchrom;k++)for(j=0;j<lchrom;j++){dd[k*lchrom+j]=hypot(x[k]-x[j],y[k]-y[j]);if(maxdd<dd[k*lchrom+j])maxdd=dd[k*lchrom+j];}refpd=dd[lchrom-1];for(k=0;k<lchrom;k++)refpd=refpd+dd[k*lchrom+k+2]; for(j=0;j<lchrom;j++)dd[j*lchrom+j]=4.0*maxdd; ff=(0.765*maxxy*pow(lchrom,0.5)); minpp=0; min=dd[lchrom-1];for(j=0;j<lchrom-1;j++){if(dd[lchrom*j+lchrom-1]<min){min=dd[lchrom*j+lchrom-1];minpp=j;}}initpop();statistics(oldpop);initreport();}/*&&&&&&&&&&&&&&&&&&*/void report(int l,struct pp *pop){int k,ix,iy,jx,jy;unsigned int tt;float ttt;cleardevice();gotoxy(1,1);printf("city:%4d para_size:%4d maxgen:%4d ref_tour:%f\n",lchrom,popsize,maxgen,refpd);printf("ncross:%4d Nmutation:%4d Rungen:%4d AVG=%8.4f MIN=%8.4f\n\n",ncross,nmutation,l,avg,min);printf("inpath:%6.4f Minpath length:%10.4f Ref_co_tour:%f\n",pop[maxpp].x/maxxy,pop[maxpp].x,ff); printf("Co_minpath:%6.4f Maxfit:%10.8f",100.0*pop[maxpp].x/ff,pop[maxpp].fitness); ttt=clock()/18.2;tt=ttt/60;printf("Run clock:%2d:%2d:%4d.2f\n",tt/60,tt%60,ttt-tt*60.0); setcolor(1%15+1);for(k=0;k<lchrom-1;k++){ix=x[pop[maxpp].chrom[k]];iy=y[pop[maxpp].chrom[k]]+110;jx=x[pop[maxpp].chrom[k+1]];jy=y[pop[maxpp].chrom[k+1]]+110;line(ix,iy,jx,jy);putpixel(ix,iy,RED);}ix=x[pop[maxpp].chrom[0]];iy=y[pop[maxpp].chrom[0]]+110;jx=x[pop[maxpp].chrom[lchrom-1]];jy=y[pop[maxpp].chrom[lchrom-1]]+110; line(ix,iy,jx,jy); putpixel(jx,jy,RED);setcolor(11);outtextxy(ix,iy,"*");setcolor(12);for(k=0;k<1%200;k++){ix=k+280;iy=366-fm[k]/3;jx=ix+1;jy=366-fm[k+1]/3;line(ix,iy,jx,jy);putpixel(ix,iy,RED);}printf("GEN:%3d",l);printf("Minpath:%f Maxfit:%f",pop[maxpp].x,pop[maxpp].fitness); printf("Clock:%2d:%2d:%4.2f\n",tt/60,tt%60,ttt-tt*60.0);}/*###############*/float decode(unsigned char *pp) {int j,k,l;float tt;tt=dd[pp[0]*lchrom+pp[lchrom-1]]; for(j=0;j<lchrom-1;j++){tt=tt+dd[pp[j]*lchrom+pp[j+1]];} l=0;for(k=0;k<lchrom-1;k++)for(j=k+1;j<lchrom;j++){if(pp[j]==pp[k])l++;}return tt+4*l*maxdd;}/*%%%%%%%%%%%%%%%%%%*/ void crtinit(){int driver,mode;struct palettetype p;driver=DETECT;mode=0;initgraph(&driver,&mode,""); cleardevice();}/*$$$$$$$$$$$$$$$$$$$$*/ int select(){double rand1,partsum; float r1;int j;partsum=0.0;j=0;rand1=random1()*sumfitness; do{partsum=partsum+oldpop[j].fitness;j=j+1;}while((partsum<rand1)&&(j<popsize));return j-1;}/*$$$$$$$$$$$$$$$*/int crossover(unsigned char *parent1,unsigned char *parent2,int k5) {int k,j,mutate,i1,i2,j5;int j1,j2,j3,s0,s1,s2; unsigned charjj,ts1[maxstring],ts2[maxstring];float f1,f2;s0=0;s1=0;s2=0;if(flip(pcross)){jcross=random(lchrom-1); j5=random(lchrom-1); ncross=ncross+1;if(jcross>j5){k=jcross;jcross=j5;j5=k;}}else jcross=lchrom; if(jcross!=lchrom) {s0=1;k=0;for(j=jcross;j<j5;j++) {ts1[k]=parent1[j]; ts2[k]=parent2[j]; k++; }j3=k;for(j=0;j<lchrom;j++) {j2=0;while((parent2[j]!=ts1[j2])&&(j2<k)){j2++;}if(j2==k){ts1[j3]=parent2[j];j3++;}}j3=k;for(j=0;j<lchrom;j++){j2=0;while((parent1[j]!=ts2[j2])&&(j2<k)){j2++;}if(j2==k){ts2[j3]=parent1[j];j3++;}}for(j=0;j<lchrom;j++){newpop[k5].chrom[j]=ts1[j];newpop[k5+1].chrom[j]=ts2[j]; }}else{for(j=0;j<lchrom;j++){newpop[k5].chrom[j]=parent1[j]; newpop[k5+1].chrom[j]=parent2[j]; } mutate=flip(pmutation);if(mutate){s1=1;nmutation=nmutation+1;for(j3=0;j3<200;j3++){j1=random(lchrom);j=random(lchrom);jj=newpop[k5].chrom[j];newpop[k5].chrom[j]=newpop[k5].chrom[j1];newpop[k5].chrom[j1]=jj;}}mutate=flip(pmutation);if(mutate){s2=1;nmutation=nmutation+1;for(j3=0;j3<100;j3++){j1=random(lchrom);j=random(lchrom);jj=newpop[k5+1].chrom[j];newpop[k5+1].chrom[j]=newpop[k5+1].chrom[j1];newpop[k5+1].chrom[j1]=jj;}}}j2=random(2*lchrom/3);for(j=j2;j<j2+lchrom/3-1;j++)for(k=0;k<lchrom;k++){if(k==j)continue;if(k>j){i2=k;i1=j;}else{i1=k;i2=j;}f1=dd[lchrom*newpop[k5].chrom[i1]+newpop[k5].chrom[i2]]; f1=f1+dd[lchrom*newpop[k5].chrom[(i1+1)%lchrom]+newpop[k5].chrom[(i2+1)%lchrom]];f2=dd[lchrom*newpop[k5].chrom[i1]+newpop[k5].chrom[(i1+1)%lchrom]];f2=f2+dd[lchrom*newpop[k5].chrom[i2]+newpop[k5].chrom[(i2+1)%lchrom]];if(f1<f2){inversion(i1,i2,newpop[k5].chrom);}}j2=random(2*lchrom/3);for(j=j2;j<j2+lchrom/3-1;j++)for(k=0;k<lchrom;k++){if(k==j)continue;if(k>j){i2=k;i1=j;}else{i1=k;i2=j;}f1=dd[lchrom*newpop[k5+1].chrom[i1]+newpop[k5+1].chrom[i2]];f1=f1+dd[lchrom*newpop[k5+1].chrom[(i1+1)%lchrom]+newpop[k5+1].chrom[(i2+1)%lchrom]];f2=dd[lchrom*newpop[k5+1].chrom[i1]+newpop[k5+1].chrom[(i1+1)%lchrom]];f2=f2+dd[lchrom*newpop[k5+1].chrom[i2]+newpop[k5+1].chrom[(i2+1)%lchrom]];if(f1<f2){inversion(i1,i2,newpop[k5+1].chrom);} }return 1;}/*$$$$$$$$$$$$$$$*/void inversion(unsigned int k,unsigned int j,unsigned char *ss) {unsigned int l1,i;unsigned char tt;l1=(j-k)/2;for(i=0;i<l1;i++){tt=ss[k+i+1];ss[k+i+1]=ss[j-i];ss[j-i]=tt;}}/*%%%%%%%%%%%%%%%*/void randomize1(){int i;randomize();for(i=0;i<lchrom;i++) oldrand[i]=random(30001)/30000.0;jrand=0;}/*%%%%%%%%%%%*/float random1(){jrand=jrand+1;if(jrand>=lchrom){jrand=0;randomize1();}return oldrand[jrand]; }/*%%%%%%%%%%*/int flip(float probability) {float ppp;ppp=random(20001)/20000.0; if(ppp<=probability)return 1; return 0;}%TSP问题(又名:旅行商问题,货郎担问题)遗传算法通用matlab程序 %D是距离矩阵,n为种群个数,建议取为城市个数的1~2倍, %C为停止代数,遗传到第 C 代时程序停止,C的具体取值视问题的规模和耗费的时间而定%m为适应值归一化淘汰加速指数 ,最好取为1,2,3,4 ,不宜太大 %alpha为淘汰保护指数,可取为0~1之间任意小数,取1时关闭保护功能,最好取为0.8~1.0 %R为最短路径,Rlength为路径长度function [R,Rlength]=geneticTSP(D,n,C,m,alpha)[N,NN]=size(D);farm=zeros(n,N);%用于存储种群for i=1:nfarm(i,:)=randperm(N);%随机生成初始种群endR=farm(1,:);%存储最优种群len=zeros(n,1);%存储路径长度fitness=zeros(n,1);%存储归一化适应值counter=0;while counter<Cfor i=1:nlen(i,1)=myLength(D,farm(i,:));%计算路径长度endmaxlen=max(len);minlen=min(len);fitness=fit(len,m,maxlen,minlen);%计算归一化适应值rr=find(len==minlen);R=farm(rr(1,1),:);%更新最短路径FARM=farm;%优胜劣汰,nn记录了复制的个数nn=0;for i=1:nif fitness(i,1)>=alpha*rand nn=nn+1;FARM(nn,:)=farm(i,:);endendFARM=FARM(1:nn,:);[aa,bb]=size(FARM);%交叉和变异while aa<nif nn<=2nnper=randperm(2);elsennper=randperm(nn);endA=FARM(nnper(1),:);B=FARM(nnper(2),:);[A,B]=intercross(A,B); FARM=[FARM;A;B]; [aa,bb]=size(FARM);endif aa>nFARM=FARM(1:n,:);%保持种群规模为nendfarm=FARM;clear FARMcounter=counter+1endRlength=myLength(D,R);function [a,b]=intercross(a,b) L=length(a); if L<=10%确定交叉宽度W=1;elseif ((L/10)-floor(L/10))>=rand&&L>10W=ceil(L/10);elseW=floor(L/10);endp=unidrnd(L-W+1);%随机选择交叉范围,从p到p+W for i=1:W%交叉x=find(a==b(1,p+i-1)); y=find(b==a(1,p+i-1)); [a(1,p+i-1),b(1,p+i-1)]=exchange(a(1,p+i-1),b(1,p+i-1));[a(1,x),b(1,y)]=exchange(a(1,x),b(1,y));endfunction [x,y]=exchange(x,y) temp=x;x=y;y=temp;% 计算路径的子程序function len=myLength(D,p) [N,NN]=size(D);len=D(p(1,N),p(1,1)); for i=1:(N-1)len=len+D(p(1,i),p(1,i+1));end%计算归一化适应值子程序function fitness=fit(len,m,maxlen,minlen) fitness=len;for i=1:length(len)fitness(i,1)=(1-((len(i,1)-minlen)/(maxlen-minlen+0.000001))).^m;end。

(完整版)遗传算法c语言代码

(完整版)遗传算法c语言代码
break;
}
}
}
//拷贝种群
for(i=0;i<num;i++)
{
grouptemp[i].adapt=group[i].adapt;
grouptemp[i].p=group[i].p;
for(j=0;j<cities;j++)
grouptemp[i].city[j]=group[i].city[j];
{
group[i].p=1-(double)group[i].adapt/(double)biggestsum;
biggestp+=group[i].p;
}
for(i=0;i<num;i++)
group[i].p=group[i].p/biggestp;
//求最佳路劲
bestsolution=0;
for(i=0;i<num;i++)
printf("\n******************是否想再一次计算(y or n)***********************\n");
fflush(stdin);
scanf("%c",&choice);
}while(choice=='y');
return 0;
}
遗传算法代码
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<time.h>
#define cities 10 //城市的个数

遗传算法C语言代码

遗传算法C语言代码

// GA.cpp : Defines the entry point for the console application.///*这是一个非常简单的遗传算法源代码,是由Denis Cormier (North Carolina State University)开发的,Sita S.Raghavan (University of North Carolina at Charlotte)修正。

代码保证尽可能少,实际上也不必查错。

对一特定的应用修正此代码,用户只需改变常数的定义并且定义“评价函数”即可。

注意代码的设计是求最大值,其中的目标函数只能取正值;且函数值和个体的适应值之间没有区别。

该系统使用比率选择、精华模型、单点杂交和均匀变异。

如果用Gaussian变异替换均匀变异,可能得到更好的效果。

代码没有任何图形,甚至也没有屏幕输出,主要是保证在平台之间的高可移植性。

读者可以从, 目录coe/evol中的文件prog.c中获得。

要求输入的文件应该命名为‘gadata.txt’;系统产生的输出文件为‘galog.txt’。

输入的文件由几行组成:数目对应于变量数。

且每一行提供次序——对应于变量的上下界。

如第一行为第一个变量提供上下界,第二行为第二个变量提供上下界,等等。

*/#include <stdio.h>#include <stdlib.h>#include <math.h>/* Change any of these parameters to match your needs *///请根据你的需要来修改以下参数#define POPSIZE 50 /* population size 种群大小*/#define MAXGENS 1000 /* max. number of generations 最大基因个数*/const int NVARS = 3; /* no. of problem variables 问题变量的个数*/#define PXOVER 0.8 /* probability of crossover 杂交概率*/#define PMUTATION 0.15 /* probability of mutation 变异概率*/#define TRUE 1#define FALSE 0int generation; /* current generation no. 当前基因个数*/int cur_best; /* best individual 最优个体*/FILE *galog; /* an output file 输出文件指针*/struct genotype /* genotype (GT), a member of the population 种群的一个基因的结构体类型*/{double gene[NVARS]; /* a string of variables 变量*/double fitness; /* GT's fitness 基因的适应度*/double upper[NVARS]; /* GT's variables upper bound 基因变量的上界*/ double lower[NVARS]; /* GT's variables lower bound 基因变量的下界*/ double rfitness; /* relative fitness 比较适应度*/double cfitness; /* cumulative fitness 积累适应度*/};struct genotype population[POPSIZE+1]; /* population 种群*/struct genotype newpopulation[POPSIZE+1]; /* new population; 新种群*//* replaces the old generation *///取代旧的基因/* Declaration of procedures used by this genetic algorithm *///以下是一些函数声明void initialize(void);double randval(double, double);void evaluate(void);void keep_the_best(void);void elitist(void);void select(void);void crossover(void);void Xover(int,int);void swap(double *, double *);void mutate(void);void report(void);/***************************************************************/ /* Initialization function: Initializes the values of genes *//* within the variables bounds. It also initializes (to zero) *//* all fitness values for each member of the population. It *//* reads upper and lower bounds of each variable from the *//* input file `gadata.txt'. It randomly generates values *//* between these bounds for each gene of each genotype in the *//* population. The format of the input file `gadata.txt' is *//* var1_lower_bound var1_upper bound *//* var2_lower_bound var2_upper bound ... *//***************************************************************/void initialize(void){FILE *infile;int i, j;double lbound, ubound;if ((infile = fopen("gadata.txt","r"))==NULL){fprintf(galog,"\nCannot open input file!\n");exit(1);}/* initialize variables within the bounds *///把输入文件的变量界限输入到基因结构体中for (i = 0; i < NVARS; i++){fscanf(infile, "%lf",&lbound);fscanf(infile, "%lf",&ubound);for (j = 0; j < POPSIZE; j++){population[j].fitness = 0;population[j].rfitness = 0;population[j].cfitness = 0;population[j].lower[i] = lbound;population[j].upper[i]= ubound;population[j].gene[i] = randval(population[j].lower[i],population[j].upper[i]);}}fclose(infile);}/***********************************************************/ /* Random value generator: Generates a value within bounds *//***********************************************************/ //随机数产生函数double randval(double low, double high){double val;val = ((double)(rand()%1000)/1000.0)*(high - low) + low;return(val);}/*************************************************************/ /* Evaluation function: This takes a user defined function. *//* Each time this is changed, the code has to be recompiled. *//* The current function is: x[1]^2-x[1]*x[2]+x[3] *//*************************************************************/ //评价函数,可以由用户自定义,该函数取得每个基因的适应度void evaluate(void){int mem;int i;double x[NVARS+1];for (mem = 0; mem < POPSIZE; mem++){for (i = 0; i < NVARS; i++)x[i+1] = population[mem].gene[i];population[mem].fitness = (x[1]*x[1]) - (x[1]*x[2]) + x[3];}}/***************************************************************/ /* Keep_the_best function: This function keeps track of the *//* best member of the population. Note that the last entry in *//* the array Population holds a copy of the best individual *//***************************************************************/ //保存每次遗传后的最佳基因void keep_the_best(){int mem;int i;cur_best = 0;/* stores the index of the best individual *///保存最佳个体的索引for (mem = 0; mem < POPSIZE; mem++){if (population[mem].fitness > population[POPSIZE].fitness){cur_best = mem;population[POPSIZE].fitness = population[mem].fitness;}}/* once the best member in the population is found, copy the genes *///一旦找到种群的最佳个体,就拷贝他的基因for (i = 0; i < NVARS; i++)population[POPSIZE].gene[i] = population[cur_best].gene[i];}/****************************************************************/ /* Elitist function: The best member of the previous generation *//* is stored as the last in the array. If the best member of *//* the current generation is worse then the best member of the *//* previous generation, the latter one would replace the worst *//* member of the current population *//****************************************************************///搜寻杰出个体函数:找出最好和最坏的个体。

用C 实现遗传算法

用C  实现遗传算法

/*本程序试用遗传算法来解决Rosenbrock函数的全局最大值计算问题:max f(x1,x2)=100(x1^2-x2^2)^2+(1-x1)^2s.t.-2.048≤xi≤2.048(i=1,2)*/#include<iostream>#include<time.h>#include<stdlib.h>#include<cmath>using namespace std;const int M=8,T=2;//M群体大小,pc交叉概率,pm变异概率,T终止代数const double pc=0.6,pm=0.01;struct population//定义群体结构{int x[20];double x1,x2;double fit;double sumfit;}p[M];void initial(population*);//初始化函数void evaluefitness(population*);//计算适应度void select(population*);//选择复制函数void crossover(population*);//交叉函数void mutation(population*);//变异函数void decoding(population*);//解码函数void print(population*);//显示函数int main()//遗传算法主函数{int gen=0;initial(&p[0]);//随机获得初始解cout<<"initialed!"<<endl;print(&p[0]);decoding(&p[0]);//先解码cout<<"decoded!"<<endl;print(&p[0]);evaluefitness(&p[0]);//计算适应值与累计适值cout<<"evalued!"<<endl;print(&p[0]);while(gen<=T){cout<<"gen="<<gen+1<<endl;select(&p[0]);decoding(&p[0]);evaluefitness(&p[0]);cout<<"selected!"<<endl;print(&p[0]);crossover(&p[0]);decoding(&p[0]);evaluefitness(&p[0]);cout<<"crossovered!"<<endl;print(&p[0]);mutation(&p[0]);decoding(&p[0]);evaluefitness(&p[0]);cout<<"mutated!"<<endl;print(&p[0]);gen++;}decoding(&p[0]);evaluefitness(&p[0]);cout<<"最后得出的满意解为:"<<endl;for(int i=0;i<M;i++)cout<<"x1:"<<p[i].x1<<"x2:"<<p[i].x2<<"值:"<<p[i].fit<<endl;return0;}/*****************************初始化函数*****************************/int rand01()//用于随机取0或1的函数{int r;float q;q=rand()/(RAND_MAX+0.0);if(q<0.5)r=0;else r=1;return r;}void initial(population*t)//群体初始化函数{int j;population*po;srand(time(0));for(po=t;po<t+M;po++)for(j=0;j<20;j++)(*po).x[j]=rand01();}/*************************计算适应值函数*********************************/ void evaluefitness(population*t)//计算适应值函数{double f,x1,x2,temp=0.0;population*po,*po2;for(po=t;po<t+M;po++){x1=(*po).x1;x2=(*po).x2;f=100.0*(x1*x1-x2*x2)*(x1*x1-x2*x2)+(1.0-x1)*(1.0-x1);(*po).fit=f;}for(po=t;po<t+M;po++)//计算累计适应值{for(po2=t;po2<=po;po2++)temp=temp+(*po2).fit;(*po).sumfit=temp;temp=0.0;}}/**************************选择复制函数********************************/ double randab(double a,double b)//在区间(a,b)内生成一个随机数{double c,r;c=b-a;r=a+c*rand()/(RAND_MAX+1.0);return r;}void select(population*t)//选择算子函数{int i=0;population pt[M],*po;double s;srand(time(0));while(i<M){s=randab((*t).sumfit,(*(t+M-1)).sumfit);for(po=t;po<t+M;po++){if((*po).sumfit>=s){pt[i]=(*po);break;}else continue;}i++;}for(i=0;i<M;i++)//将复制后数据pt[M]转入p[M] for(int j=0;j<20;j++)p[i].x[j]=pt[i].x[j];}/***************************交叉函数*******************************/ void crossover(population*t)//交叉算子函数{population*po;double q;//用于存一个0到1的随机数int d,e,tem[20];//d存放从1到19的一个随机整数,用来确定交叉的位置//e存放从0到M的一个随机且与当前P[i]中i不同的整数,用来确定交叉的对象srand(time(0));for(po=t;po<t+M/2;po++){q=rand()/(RAND_MAX+0.0);if(q<pc){for(int j=0;j<M;j++)//运算M次,避免产生群体中某个体与自己交叉的情况{e=rand()%M;//随机确定交叉对象if(t+e!=po)break;}//不能重复d=1+rand()%19;//随机确定交叉位置for(int i=d;i<20;i++){tem[i]=(*po).x[i];(*po).x[i]=(*(t+e)).x[i];(*(t+e)).x[i]=tem[i];}}else continue;}}/***************************变异函数*******************************/void mutation(population*t)//变异算子函数{double q;//q用来存放针对每一个基因座产生的[0,1]的随机数population*po;srand(time(0));for(po=t;po<t+M;po++){int i=0;while(i<20){q=rand()/(RAND_MAX+0.0);if(q<pm)(*po).x[i]=1-(*po).x[i];i++;}}}/***************************解码函数*******************************/void decoding(population*t)//解码函数{population*po;int temp,s1=0,s2=0;float m,n,dit;n=ldexp(1,10);//n=2^10dit=4.096/(n-1);//dit=(U(max)-U(min))/n-1for(po=t;po<t+M;po++){for(int i=0;i<10;i++){temp=ldexp((*po).x[i],i);s1=s1+temp;}m=-2.048+s1*dit;(*po).x1=m;s1=0;for(int j=10;j<20;j++){temp=ldexp((*po).x[j],j-10);s2=s2+temp;}m=-2.048+s2*dit;(*po).x2=m;s2=0;}}/*******************************显示函数**************************************/ void print(population*t){population*po;for(po=t;po<t+M;po++){for(int j=0;j<20;j++){cout<<(*po).x[j];if((j+1)%5==0)cout<<"";}cout<<endl;cout<<(*po).x1<<""<<(*po).x2<<""<<(*po).fit<<""<<(*po).sumfit<<endl;}}。

遗传算法案例及源代码

遗传算法案例及源代码

计算智能作业三:遗传算法计算问题1.问题描述:求下述二元函数的最大值:222121),(m ax x x x x f +=S.t. }7,6,5,4,3,2,1{1∈x }7,6,5,4,3,2,1{2∈x2.程序结构:(1)变量:C :是一个1*6数组,每个数组里面是一个6位二进制数,它是遗传算法中的染色体。

new_c:每一轮的新变量c 。

first_c:初始群体矩阵。

sur_value :个体适应值的概率值,为0-1之间的数,所有概率值和为1。

survived :经过选择运算后产生的个体基因型组合。

intersect_c :经过交叉运算后产生的个体基因型组合。

mutation_c :经过变异运算后产生的个体基因型组合。

f :最后计算得到的最大值 (2)程序里面的方程function out = value_function( ci ):价值函数(自适应度函数),即222121),(x x x x f +=。

function [ sur_value ] = calc_value( c ):计算群体中每一个个体的适应度的值function survived = surviver( sur_value ):利用概率选择函数 function [ intersect_c ] = intersect( new_c ):交叉运算function [ mutation_c ,mutation_value] = mutation( intersect_c ):变异运算3.源程序(1)遗传算法的主程序主程序包括初始群体产生,最终结果展示,即各函数之间的调用关系。

个体编码遗传算法的运算对象是表示个体的符号串,所以必须把变量 x1, x2 编码为无符号二进制整数。

这个二进制整数位个体的基因型。

因为x1, x2 为 0 ~ 7之间的整数,所以分别用3位无符号二进制整数来表示,将它们连接在一起所组成的6位无符号二进制数就形成了个体的基因型,表示一个可行解。

遗传算法程序实现

遗传算法程序实现

遗传算法程序实现#include <stdlib.h>#include <stdio.h>#include <time.h>#include <math.h>#include "GA.h"unsigned seed=1;//产生一个不大于x的随机数double crandom(int x){seed++;srand((unsigned)(seed*time(NULL)));return(rand()%x);}//产生一个0~1的随机数double random(){seed++;srand((unsigned)(seed*time(NULL)));return (double)rand()/(double)RAND_MAX;}//产生(0.1,0.2,...,1)之间的一个随机数double crandom(void){double t;t=random();if((10*t-floor(10*t))>=0.5) return (floor(10*t)+1)/10;elsereturn(floor(10*t)/10);}//初始化种群void Initial_group(double group[M][N_para], double up_limit[N_para],double low_limit[N_para]){ double beta;int i,j;for (i=0;i<M;i++)for (j=0;j<N_para;j++){beta=crandom();group[i][j]=low_limit[j]+beta*(up_limit[j]-low_limit[j]);}}}//加载实时测试数据void Load_data(double realvalue[][4]){FILE *fp;float x;//changedif((fp=fopen("realtime\\Realdata.txt","r"))==NULL){printf("cannot open the file Realvalue.txt\n");exit(0);}for(int i=0;i<N_hit+N_Begin;i++){for(int j=0;j<4;j++)//修改了{fscanf(fp,"%f ",&x);if(i>=N_Begin)realvalue[i-N_Begin][j]=(double)x;//修改了}}fclose(fp);}//计算适应度值void Fit_calculate(double group[][N_para],double realvalue[][4],double fit_degree[],int n){int i;//double Mcar,m1,r1,r2,L,J1,J2,c1,c2,b;double mcar,m1,l1,J1,b,g,f1,eks,eksd,theta1,theta1d,h;double x[4],x_temp[4],k[4][4],lefA[4];double err,A11,A12,A21,A22,B1,B2,B3,B4,C11,C12,C21,C22,D2;g=9.8;h=0.005;for (i=0;i<n;i++){mcar=group[i][0];m1=group[i][1];l1=group[i][2];J1=group[i][3];b=group[i][4];f1=group[i][5];//printf("mcar=%6.3f,m1=%6.3f,l1=%6.3f,J1=%6.3f,b=%6.3,f1=%6.3\n,",mcar,m1, l1,J1,b,f1);err=0;for (int j=0;j<4;j++) //新加的{x[j]=realvalue[0][j];x_temp[j]=realvalue[0][j];}/*for (int j=0;j<4;j++)//修改了{x[j]=Initivalue[j];x_temp[j]=Initivalue[j];}*/for (int q=0;q<N_hit;q++){eks=x[0];eksd=x[1];theta1=x[2];theta1d=x[3];while(fabs(x[2])>(2*Pi)){printf("Error");printf(" q=%d",q);getchar();}A11=mcar+m1;A12=-m1*l1*cos(theta1);A22=m1*l1*l1+J1;A21=A12;C11=b;C12=m1*l1*sin(theta1)*theta1d;C21=0;C22=f1;D2=-m1*g*l1*sin(theta1);B1=eksd;B2=-C11*eksd-C12*theta1d;B3=theta1d;B4=-C22*theta1d-D2;/*%A=[1 0 0 0;% 0 A11 0 A12 ;% 0 0 1 0 ;% 0 A21 0 A22];%lefA = inv(A)*B;%A11x+A12y=B(2)%A21x+A22y=B(4)*/lefA[0]=B1;lefA[1]=(B2*A22-B4*A12)/(A22*A11-A21*A12);lefA[2]=B3;lefA[3]=(B2*A21-B4*A11)/(A12*A21-A22*A11);for (j=0;j<4;j++) //龙格-库塔法{k[j][0]=lefA[0];k[j][1]=lefA[1];k[j][2]=lefA[2];k[j][3]=lefA[3];for (int p=0;p<4;p++){if(j==0) x[p]=x_temp[p]+h/2*k[j][p];if(j==1) x[p]=x_temp[p]+h/2*k[j][p];if(j==2) x[p]=x_temp[p]+h*k[j][p];}}for(j=0;j<4;j++){x[j]=x_temp[j]+(k[0][j]+2*k[1][j]+2*k[2][j]+k[3][j])*h/6;x_temp[j]=x[j];}//getchar();//test uerr=err+pow((x[2]-realvalue[q][2]),2);//err=err+80*pow(x[1],2)+80*pow(x[3],2)+pow(u,2);}//end of for qfit_degree[i]=2+log(2/err)/log(200);///log(2);//9改成200了}}//种群排序void sort(double order_fit[],int index_fit[],int n){int i,j;int t;double temp;for (i=0;i<n;i++)index_fit[i]=i;for (j=1;j<=n-1;j++)for(i=1;i<=n-j;i++){if(order_fit[i]<order_fit[i-1]){temp=order_fit[i];order_fit[i]=order_fit[i-1];order_fit[i-1]=temp;t=index_fit[i];index_fit[i]=index_fit[i-1];index_fit[i-1]=t;}}}//反馈式突变void Feedback_mut(double group[][N_para],double up_limit[],double low_limit[],int index_fit[],double fit_opitimal,int nb){// printf("\nFeedback1 ok\n");double beta;int i,j,best,worse;int n=M;best=index_fit[M-1];for (i=0;i<n*0.9;i++){beta=crandom();worse=index_fit[i];if(nb>50||fit_opitimal<Sigma){if(nb>50) nb=0;for(j=0;j<N_para;j++)group[worse][j]=low_limit[j]+beta*(up_limit[j]-low_limit[j]);}elsefor(j=0;j<N_para;j++){group[worse][j]=(Nu+beta*Vi)*group[best][j];if (group[worse][j]<low_limit[j]||group[worse][j]>up_limit[j])group[worse][j]=group[best][j];}}//printf("\nFeedback 2 ok\n");}//选择操作void Slected(double cross[],double group[][N_para],double fit_degree[],double fit_sum){int j,i=0;double beta,slectvalue[M];beta=crandom();slectvalue[0]=fit_degree[0]/fit_sum;for(i=1;i<M;i++)slectvalue[i]=slectvalue[i-1]+fit_degree[i]/fit_sum;for(i=1;i<M;i++){if(slectvalue[i-1]<beta&&slectvalue[i]>beta)break;}for(j=0;j<N_para;j++)cross[j]=group[i][j];}//计算两个染色体的海明距离int haiming(double crossa[],double crossb[],int n){int num=0;int i;for (i=0;i<n;i++)if(crossa[i]!=crossb[i]) num++;return num;}//交叉操作void Cro_operation(double crossa[],double crossb[],double up_limit[],double low_limit[],int D_hm){int i,j,cro_point,d,zeta=0,sum=0;double cro_temp,beta;double x_temp[N_para];double y_temp[N_para];int rec[6]={0,0,0,0,0,0};if(D_hm==1){for(i=0;i<N_para;i++){if(crossa[i]!=crossb[i])break;}//cro_temp=crossa[i];//crossa[i]=crossb[i];//crossb[i]=cro_tempcro_point=i;}else{//zeta=(int)(crandom(4)+1);for(int ii=0;ii<N_para;ii++){for (int k=0;k<N_para;k++){x_temp[k]=0;y_temp[k]=0;}for(i=0;i<=ii;i++){x_temp[i]=crossa[i];y_temp[i]=crossb[i];}d=haiming(x_temp,y_temp,N_para);if(d>0&&d<D_hm){zeta++;rec[ii]=1;}//break;//>=改成<???}ii=(int)(crandom(zeta)+1);sum=0;for(i=0;sum<ii;i++){sum=sum+rec[i];cro_point=i;;}}//End of elsefor (j=0;j<cro_point;j++){cro_temp=crossa[j];crossa[j]=crossb[j];crossb[j]=cro_temp;}//cro_point--;//改了beta=crandom();cro_temp=(crossa[cro_point]<=crossb[cro_point])?crossa[cro_point]:crossb[cro_point];crossa[cro_point]=cro_temp+beta*fabs(crossa[cro_point]-crossb[cro_point]);beta=crandom();crossb[cro_point]=low_limit[cro_point]+beta*(up_limit[cro_point]-low_limit[cro_poi nt]);}//正交实验产生一个较优染色体void Cro_opiti(double crossa[N_para],double crossb[N_para],double cro_result[N_para],double realvalue[][4])//改了{double matrix[8][6]={//四因素两水平正交试验表1,1,1,1,1,1,1,1,1,2,2,2,1,2,2,1,1,2,1,2,2,2,2,1,2,1,2,1,2,1,2,1,2,2,1,2,2,2,1,1,2,2,2,2,1,2,1,1};int i,j;double fit_temp[8];double kx[N_para]={0,0,0,0,0,0};//changedouble ky[N_para]={0,0,0,0,0,0};//changefor(i=0;i<8;i++)for(j=0;j<N_para;j++){if(matrix[i][j]==1)matrix[i][j]=crossa[j];elsematrix[i][j]=crossb[j];}Fit_calculate(matrix,realvalue,fit_temp,8);for(i=0;i<8;i++)// 改了{for(j=0;j<N_para;j++){if(matrix[i][j]==crossa[j])kx[j]=kx[j]+fit_temp[i];if(matrix[i][j]==crossb[j])ky[j]=ky[j]+fit_temp[i];}}for(j=0;j<N_para;j++){if(kx[j]>ky[j])cro_result[j]=crossa[j];elsecro_result[j]=crossb[j];}}//变异操作void mut_operation(double cro_result[N_para],double up_limit[], double low_limit[]) {int mut_point1,mut_point2;double beta,x1,x2;do{mut_point1=(int)crandom(6);//改了13mut_point2=(int)crandom(6);//改了13}while(mut_point1==mut_point2);x1=(cro_result[mut_point1]-low_limit[mut_point1])/(up_limit[mut_point1]-low_limit [mut_point1]);x2=(cro_result[mut_point2]-low_limit[mut_point2])/(up_limit[mut_point2]-low_limit [mut_point2]);beta=crandom();if(beta<Pm){beta=crandom();cro_result[mut_point1]=(1-beta)*cro_result[mut_point1]+beta*low_limit[mut_point 1]+x2*(up_limit[mut_point1]-cro_result[mut_point1]);cro_result[mut_point2]=(1-beta)*cro_result[mut_point2]+beta*low_limit[mut_point 2]+x1*(up_limit[mut_point2]-cro_result[mut_point2]);}}//产生新一代种群void New_group(double group_temp[][N_para],double group[][N_para],double newfit_degree[],double fit_degree[]){int i,j;int temp;int index[M+Ncross];sort(newfit_degree,index,M+Ncross);for(i=0;i<M;i++){temp=index[Ncross+i];for(j=0;j<N_para;j++){group[i][j]=group_temp[temp][j];}fit_degree[i]=newfit_degree[Ncross+i];}}//种群最优个体,适应度值数据存盘void Data_record(double group[][N_para],double fit_degree[],double fit_population,int index_fit[]){FILE *fp;if((fp=fopen("Result\\Result.txt","a"))==NULL){printf("cannot open the fiel Result.txt\n");exit(0);}int nbest=index_fit[M-1];for(int i=0;i<N_para;i++)fprintf(fp,"%6.5f ",group[nbest][i]);printf("\npara=%6.5f %6.5f %6.5f %6.5f %6.5f %6.5f\n",group[nbest][0],group[n best][1],group[nbest][2],group[nbest][3],group[nbest][4],group[nbest][5]);//家的fprintf(fp,"%6.5f %6.5f\n",fit_degree[M-1],fit_population);fclose(fp);。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
{
n1=group[i].city[j-1];
n2=group[i].city[j];
sumdistance+=distance[n1][n2];
}
group[i].adapt=sumdistance; //每条染色体的路径总和
biggestsum+=sumdistance; //种群的总路径
}
for(i=0;i<num;i++)
//初始化梯度概率
for(i=0;i<num;i++)
{
gradient[i]=0.0;
xuanze[i]=0.0;
}
gradient[0]=group[0].p;
for(i=1;i<num;i++)
gradient[i]=gradient[i-1]+group[i].p;
srand((unsigned)time(NULL));
}
//数据更新
for(i=0;i<num;i++)
{
temp=xuan[i];
group[i].adapt=grouptemp[temp].adapt;
group[i].p=grouptemp[temp].p;
for(j=0;j<cities;j++)
group[i].city[j]=grouptemp[temp].city[j];
遗传算法代码
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<time.h>
#define cities 10 //城市的个数
#define MAXX 100//迭代次数
#define pc 0.8 //交配概率
{
group[i].p=1-(double)group[i].adapt/(double)biggestsum;
biggestp+=group[i].p;
}
for(i=0;i<num;i++)
group[i].p=group[i].p/biggestp;
//求最佳路劲
bestsolution=0;
for(i=0;i<num;i++)
break;
}
}
}
//拷贝种群
for(i=0;i<num;i++)
{
groupemp[i].p=group[i].p;
for(j=0;j<cities;j++)
grouptemp[i].city[j]=group[i].city[j];
int adapt;//适应度
double p;//在种群中的幸存概率
}group[num],grouptemp[num];
//随机产生10个城市之间的相互距离
void init()
{
int i,j;
memset(distance,0,sizeof(distance));
srand((unsigned)time(NULL));
for(j=0;j<cities;j++)
group[i].city[j]=-1;
srand((unsigned)time(NULL));
for(i=0;i<num;i++)
{
for(j=0;j<cities;)
{
t=rand()%cities;
flag=1;
for(k=0;k<j;k++)
{
if(group[i].city[k]==t)
printf("\n");
}
}
//评价函数,找出最优染色体
void pingjia()
{
int i,j;
int n1,n2;
int sumdistance,biggestsum=0;
double biggestp=0;
for(i=0;i<num;i++)
{
sumdistance=0;
for(j=1;j<cities;j++)
for(i=0;i<cities;i++)
{
for(j=i+1;j<cities;j++)
{
distance[i][j]=rand()%100;
distance[j][i]=distance[i][j];
}
}
printf("************城市的距离矩阵如下************\n");
{
flag=0;
break;
}
}
if(flag)
{
group[i].city[j]=t;
j++;
}
}
}
printf("************初始种群如下****************\n");
for(i=0;i<num;i++)
{
for(j=0;j<cities;j++)
printf("%4d",group[i].city[j]);
}
}
//变异
void bianyi()
{
int i,j;
int t;
int temp1,temp2,point;
double bianyip[num]; //染色体的变异概率
//随机产生染色体的存活概率
for(i=0;i<num;i++)
{
xuanze[i]=(rand()%100);
xuanze[i]/=100;
}
//选择能生存的染色体
for(i=0;i<num;i++)
{
for(j=0;j<num;j++)
{
if(xuanze[i]<gradient[j])
{
xuan[i]=j; //第i个位置存放第j个染色体
if(group[i].p>group[bestsolution].p)
bestsolution=i;
}
//选择
void xuanze()
{
int i,j,temp;
double gradient[num];//梯度概率
double xuanze[num];//选择染色体的随机概率
int xuan[num];//选择了的染色体
for(i=0;i<cities;i++)
{
for(j=0;j<cities;j++)
printf("%4d",distance[i][j]);
printf("\n");
}
}
//随机产生初试群
void groupproduce()
{
int i,j,t,k,flag;
for(i=0;i<num;i++) //初始化
#define pm 0.05 //变异概率
#define num 10//种群的大小
int bestsolution;//最优染色体
int distance[cities][cities];//城市之间的距离
struct group //染色体的结构
{
int city[cities];//城市的顺序
相关文档
最新文档