遗传算法C语言代码
- 格式:docx
- 大小:20.26 KB
- 文档页数:11
遗传算法是一种模拟自然选择过程的优化算法,可以用于解决各种复杂的组合优化问题。
其中,旅行商问题是一个经典的组合优化问题,也是一个典型的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. 我们重复进行迭代操作,直到达到停止条件(例如达到最大迭代次数或者适应度达到阈值)。
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();}}}。
.专业整理 .C语言遗传算法代码以下为遗传算法的源代码,计算一元代函数的代码和二元函数的代码以+++++++++++++++++++++++++++++++++++++为分割线分割开来,请自行选择适合的代码,使用时请略看完代码的注释,在需要更改的地方更改为自己需要的代码。
+++++++++++++++++++++++++++++++一元函数代码++++++++++++++++++++++++++++#include <stdio.h>#include<stdlib.h>#include<time.h>#include<math.h>#define POPSIZE 1000#define maximization 1#define minimization 2#define cmax 100#define cmin 0#define length1 20#define chromlength length1// 染色体长度//注意,你是求最大值还是求最小值.专业整理 .//变量的上下限的修改开始float min_x1=-2;//变量的下界float max_x1=-1;//变量的上界//变量的上下限的修改结束int popsize;// 种群大小int maxgeneration;// 最大世代数double pc;// 交叉率double pm;// 变异率struct individual{char chrom[chromlength+1];double value;double fitness;// 适应度};int generation;// 世代数int best_index;int worst_index;struct individual bestindividual;// 最佳个体.专业整理 . struct individual worstindividual; //最差个体struct individual currentbest;struct individual population[POPSIZE];//函数声明void generateinitialpopulation();void generatenextpopulation();void evaluatepopulation();long decodechromosome(char *,int,int);void calculateobjectvalue();void calculatefitnessvalue();void findbestandworstindividual();void performevolution();void selectoperator();void crossoveroperator();void mutationoperator();void input();void outputtextreport();void generateinitialpopulation( )// 种群初始化{int i,j;.专业整理 .for (i=0;i<popsize; i++){for( j=0;j<chromlength;j++){population[i].chrom[j]=(rand()%20<10)?'0':'1';}population[i].chrom[chromlength]='\0';}}void generatenextpopulation()// 生成下一代{selectoperator();crossoveroperator();mutationoperator();}void evaluatepopulation()// 评价个体,求最佳个体{calculateobjectvalue();calculatefitnessvalue();findbestandworstindividual();}long decodechromosome(char *string ,int point,int length) //给染色体解码{int i;long decimal=0;char*pointer;for(i=0,pointer=string+point;i<length;i++,pointer++)if(*pointer-'0'){decimal +=(long)pow(2,i);}return (decimal);}void calculateobjectvalue()// 计算函数值{int i;long temp1,temp2;double x1;for (i=0; i<popsize; i++){temp1=decodechromosome(population[i].chrom,0,length1);x1=(max_x1-min_x1)*temp1/(1024*1024-1)+min_x1;//目标函数修改开始population[i].value=(pow(x1,5)-3*x1-1)*(pow(x1,5)-3*x1-1);//目标函数修改结束}}void calculatefitnessvalue()//计算适应度{int i;double temp;for(i=0;i<popsize;i++){if(functionmode==maximization){if((population[i].value+cmin)>0.0){temp=cmin+population[i].value;}else{temp=0.0;}}else if (functionmode==minimization){if(population[i].value<cmax){temp=cmax-population[i].value;}else{ temp=0.0;}}population[i].fitness=temp;}}void findbestandworstindividual( ) //求最佳个体和最差个体{int i;double sum=0.0;bestindividual=population[0];worstindividual=population[0];.专业整理 .for (i=1;i<popsize; i++){if (population[i].fitness>bestindividual.fitness){bestindividual=population[i];best_index=i;}else if (population[i].fitness<worstindividual.fitness) {worstindividual=population[i];worst_index=i;}sum+=population[i].fitness;}if (generation==0){currentbest=bestindividual;}else{if(bestindividual.fitness>=currentbest.fitness){currentbest=bestindividual;}}}void performevolution() //演示评价结果{if (bestindividual.fitness>currentbest.fitness){ currentbest=population[best_index];}else{population[worst_index]=currentbest;}}void selectoperator() //比例选择算法{int i,index;double p,sum=0.0;double cfitness[POPSIZE];struct individual newpopulation[POPSIZE];for(i=0;i<popsize;i++){sum+=population[i].fitness;}for(i=0;i<popsize; i++){cfitness[i]=population[i].fitness/sum;}for(i=1;i<popsize; i++){cfitness[i]=cfitness[i-1]+cfitness[i];}for (i=0;i<popsize;i++){p=rand()%1000/1000.0;index=0;while (p>cfitness[index]){index++;}newpopulation[i]=population[index];}for(i=0;i<popsize; i++){population[i]=newpopulation[i];}}void crossoveroperator() //交叉算法{int i,j;int index[POPSIZE];int point,temp;double p;char ch;for (i=0;i<popsize;i++){index[i]=i;}for (i=0;i<popsize;i++){point=rand()%(popsize-i);temp=index[i];index[i]=index[point+i];index[point+i]=temp;}for (i=0;i<popsize-1;i+=2){p=rand()%1000/1000.0;if (p<pc){point=rand()%(chromlength-1)+1;for ( j=point; j<chromlength;j++){ch=population[index[i]].chrom[j];population[index[i]].chrom[j]=population[index[i+1]].chrom[j];population[index[i+1]].chrom[j]=ch;}}}}void mutationoperator() //变异操作{int i,j;double p;for (i=0;i<popsize;i++){for( j=0;j<chromlength;j++){p=rand()%1000/1000.0;if (p<pm){population[i].chrom[j]=(population[i].chrom[j]=='0')?'1':'0';}}}}void input() //数据输入{ //printf(" 初始化全局变量 :\n");//printf("种群大小 (50-500) : ");//scanf("%d", &popsize);popsize=500;if((popsize%2) != 0){//printf( "种群大小已设置为偶数\n");popsize++;};//printf("最大世代数 (100-300) : ");//scanf("%d", &maxgeneration); maxgeneration=200;//printf("交叉率 (0.2-0.99) : ");//scanf("%f", &pc);pc=0.95;//printf("变异率 (0.001-0.1) :");//scanf("%f", &pm);pm=0.03;}void outputtextreport()//数据输出{int i;double sum;double average;sum=0.0;for(i=0;i<popsize;i++){sum+=population[i].value;}average=sum/popsize;printf("当前世代=%d\n当前世代平均函数值=%f\n当前世代最优函数值=%f\n",generation,average,population[best_index].value);}void main()// 主函数{ int i;long temp1,temp2;double x1,x2;generation=0;input();generateinitialpopulation();evaluatepopulation();while(generation<maxgeneration){generation++;generatenextpopulation();evaluatepopulation();performevolution();outputtextreport();}printf("\n");printf("统计结果 :");printf("\n");//printf("最大函数值等于:%f\n",currentbest.fitness);printf(" 其染色体编码为:");for (i=0;i<chromlength;i++){printf("%c",currentbest.chrom[i]);}printf("\n");temp1=decodechromosome(currentbest.chrom,0,length1);x1=(max_x1-min_x1)*temp1/(1024*1024-1)+min_x1;printf("x1=%lf\n",x1);.专业整理 .//这是需要修改的地方printf(" 最优值等于:%f\n",(pow(x1,5)-3*x1-1)*(pow(x1,5)-3*x1-1));}+++++++++++++++++++++++++二元函数代码+++++++++++++++++++++++++++++++++++++++++#include <stdio.h>#include<stdlib.h>#include<time.h>#include<math.h>#define POPSIZE 500#define maximization 1#define minimization 2#define cmax 100#define cmin 0#define length1 20#define length2 20#define chromlength length1+length2// 染色体长度//-----------求最大还是最小值int functionmode=maximization;//-----------//-----------变量上下界float min_x1=0;float max_x1=3;float min_x2=1;float max_x2=5;//-----------int popsize;// 种群大小int maxgeneration;// 最大世代数double pc;// 交叉率double pm;// 变异率struct individual{char chrom[chromlength+1];double value;double fitness;// 适应度};int generation;// 世代数int best_index;int worst_index;struct individual bestindividual;// 最佳个体struct individual worstindividual; //最差个体struct individual currentbest;struct individual population[POPSIZE];//函数声明void generateinitialpopulation();void generatenextpopulation();void evaluatepopulation();long decodechromosome(char *,int,int);void calculateobjectvalue();void calculatefitnessvalue();void findbestandworstindividual();void performevolution();void selectoperator();void crossoveroperator();void mutationoperator();void input();void outputtextreport();void generateinitialpopulation( )// 种群初始化{int i,j;for (i=0;i<popsize; i++){for( j=0;j<chromlength;j++){population[i].chrom[j]=(rand()%40<20)?'0':'1';}population[i].chrom[chromlength]='\0';}}void generatenextpopulation()// 生成下一代{selectoperator();crossoveroperator();mutationoperator();}void evaluatepopulation()// 评价个体,求最佳个体{calculateobjectvalue();calculatefitnessvalue();findbestandworstindividual();}long decodechromosome(char *string ,int point,int length) //给染色体解码{int i;long decimal=0;char*pointer;for(i=0,pointer=string+point;i<length;i++,pointer++)if(*pointer-'0'){decimal +=(long)pow(2,i);}return (decimal);}void calculateobjectvalue()// 计算函数值{int i;long temp1,temp2;double x1,x2;for (i=0; i<popsize; i++){temp1=decodechromosome(population[i].chrom,0,length1);temp2=decodechromosome(population[i].chrom,length1,length2);x1=(max_x1-min_x1)*temp1/(1024*1024-1)+min_x1;x2=(max_x2-min_x2)*temp2/(1024*1024-1)+min_x2;//-----------函数population[i].value=x1*x1+sin(x1*x2)-x2*x2;//-----------}}void calculatefitnessvalue()//计算适应度{int i;double temp;for(i=0;i<popsize;i++){if(functionmode==maximization){if((population[i].value+cmin)>0.0){temp=cmin+population[i].value;}else{temp=0.0;}}else if (functionmode==minimization){if(population[i].value<cmax){temp=cmax-population[i].value;}else{ temp=0.0;}}population[i].fitness=temp;}}void findbestandworstindividual( ) //求最佳个体和最差个体{int i;double sum=0.0;bestindividual=population[0];worstindividual=population[0];for (i=1;i<popsize; i++){if (population[i].fitness>bestindividual.fitness){bestindividual=population[i];best_index=i;}else if (population[i].fitness<worstindividual.fitness){worstindividual=population[i];worst_index=i;}sum+=population[i].fitness;}if (generation==0){currentbest=bestindividual;}else{if(bestindividual.fitness>=currentbest.fitness){currentbest=bestindividual;}}}void performevolution() //演示评价结果{if (bestindividual.fitness>currentbest.fitness){currentbest=population[best_index];}else{population[worst_index]=currentbest;}}void selectoperator() //比例选择算法{int i,index;double p,sum=0.0;double cfitness[POPSIZE];struct individual newpopulation[POPSIZE];for(i=0;i<popsize;i++){sum+=population[i].fitness;}for(i=0;i<popsize; i++){cfitness[i]=population[i].fitness/sum;}for(i=1;i<popsize; i++){cfitness[i]=cfitness[i-1]+cfitness[i];}for (i=0;i<popsize;i++){p=rand()%1000/1000.0;index=0;while (p>cfitness[index]){index++;}newpopulation[i]=population[index];}for(i=0;i<popsize; i++){population[i]=newpopulation[i];}}void crossoveroperator() //交叉算法{int i,j;int index[POPSIZE];int point,temp;double p;char ch;for (i=0;i<popsize;i++){index[i]=i;}for (i=0;i<popsize;i++){point=rand()%(popsize-i);temp=index[i];index[i]=index[point+i];index[point+i]=temp;}for (i=0;i<popsize-1;i+=2){p=rand()%1000/1000.0;if (p<pc){point=rand()%(chromlength-1)+1;for ( j=point; j<chromlength;j++){ch=population[index[i]].chrom[j];population[index[i]].chrom[j]=population[index[i+1]].chrom[j];population[index[i+1]].chrom[j]=ch;}}}}void mutationoperator() //变异操作{int i,j;double p;for (i=0;i<popsize;i++){for( j=0;j<chromlength;j++){p=rand()%1000/1000.0;if (p<pm){population[i].chrom[j]=(population[i].chrom[j]=='0')?'1':'0';}}}}void input() //数据输入{ //printf(" 初始化全局变量 :\n");//printf("种群大小 (50-500) : ");//scanf("%d", &popsize);popsize=200;if((popsize%2) != 0){//printf( "种群大小已设置为偶数\n");popsize++;};//printf("最大世代数 (100-300) : ");//scanf("%d", &maxgeneration);maxgeneration=200;//printf("交叉率 (0.2-0.99): ");//scanf("%f", &pc);pc=0.9;//printf("变异率 (0.001-0.1):");//scanf("%f", &pm);pm=0.003;}void outputtextreport()//数据输出{int i;double sum;double average;sum=0.0;for(i=0;i<popsize;i++){sum+=population[i].value;}average=sum/popsize;printf("当前世代=%d\n当前世代平均函数值=%f\n当前世代最优函数值=%f\n",generation,average,population[best_index].value);}void main()// 主函数{ int i;long temp1,temp2;double x1,x2;generation=0;input();generateinitialpopulation();evaluatepopulation();while(generation<maxgeneration){generation++;generatenextpopulation();evaluatepopulation();performevolution();outputtextreport();}printf("\n");printf("统计结果 :");printf("\n");//printf("最大函数值等于:%f\n",currentbest.fitness);printf(" 其染色体编码为:");for (i=0;i<chromlength;i++){printf("%c",currentbest.chrom[i]);}printf("\n");temp1=decodechromosome(currentbest.chrom,0,length1);temp2=decodechromosome(currentbest.chrom,length1,length2);x1=(max_x1-min_x1)*temp1/(1024*1024-1)+min_x1;x2=(max_x2-min_x2)*temp2/(1024*1024-1)+min_x2;printf("x=%lf,y=%lf\n",x1,x2);//-----------修改函数printf(" 最大值 =%f\n",x1*x1+sin(x1*x2)-x2*x2);//-----------}。
解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。
// 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++ 2009-07-28 23:09:03 阅读418 评论0 字号:大中小这是一个非常简单的遗传算法源代码,是由Denis Cormier (North Carolina State University)开发的,Sita S.Raghavan (University of North Carolina at Charlotte)修正。
代码保证尽可能少,实际上也不必查错。
对一特定的应用修正此代码,用户只需改变常数的定义并且定义“评价函数”即可。
注意代码的设计是求最大值,其中的目标函数只能取正值;且函数值和个体的适应值之间没有区别。
该系统使用比率选择、精华模型、单点杂交和均匀变异。
如果用Gaussian变异替换均匀变异,可能得到更好的效果。
代码没有任何图形,甚至也没有屏幕输出,主要是保证在平台之间的高可移植性。
读者可以从,目录coe/evol 中的文件prog.c中获得。
要求输入的文件应该命名为‘gadata.txt’;系统产生的输出文件为‘galog.txt’。
输入的文件由几行组成:数目对应于变量数。
且每一行提供次序——对应于变量的上下界。
如第一行为第一个变量提供上下界,第二行为第二个变量提供上下界,等等。
/**************************************************************************//* This is a simple genetic algorithm implementation where the *//* evaluation function takes positive values only and the *//* fitness of an individual is the same as the value of the *//* objective function *//**************************************************************************/#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 */#define 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 */ /****************************************************************/void elitist(){int i;double best, worst; /* best and worst fitness values */int best_mem, worst_mem; /* indexes of the best and worst member */ best = population[0].fitness;worst = population[0].fitness;for (i = 0; i < POPSIZE - 1; ++i){if(population[i].fitness > population[i+1].fitness){if (population[i].fitness >= best){best = population[i].fitness;best_mem = i;}if (population[i+1].fitness <= worst){worst = population[i+1].fitness;worst_mem = i + 1;}}else{if (population[i].fitness <= worst){worst = population[i].fitness;worst_mem = i;}if (population[i+1].fitness >= best){best = population[i+1].fitness;best_mem = i + 1;}}}/* if best individual from the new population is better than */ /* the best individual from the previous population, then *//* copy the best from the new population; else replace the *//* worst individual from the current population with the *//* best one from the previous generation */if (best >= population[POPSIZE].fitness){for (i = 0; i < NVARS; i++)population[POPSIZE].gene[i] = population[best_mem].gene[i];population[POPSIZE].fitness = population[best_mem].fitness;}else{for (i = 0; i < NVARS; i++)population[worst_mem].gene[i] = population[POPSIZE].gene[i];population[worst_mem].fitness = population[POPSIZE].fitness;}}/**************************************************************//* Selection function: Standard proportional selection for *//* maximization problems incorporating elitist model - makes *//* sure that the best member survives *//**************************************************************/void select(void){int mem, i, j, k;double sum = 0;double p;/* find total fitness of the population */for (mem = 0; mem < POPSIZE; mem++){sum += population[mem].fitness;}/* calculate relative fitness */for (mem = 0; mem < POPSIZE; mem++){population[mem].rfitness = population[mem].fitness/sum;}population[0].cfitness = population[0].rfitness;/* calculate cumulative fitness */for (mem = 1; mem < POPSIZE; mem++){population[mem].cfitness = population[mem-1].cfitness +population[mem].rfitness;}/* finally select survivors using cumulative fitness. */for (i = 0; i < POPSIZE; i++){p = rand()%1000/1000.0;if (p < population[0].cfitness)newpopulation[i] = population[0];else{for (j = 0; j < POPSIZE;j++)if (p >= population[j].cfitness &&p<population[j+1].cfitness)newpopulation[i] = population[j+1];}}/* once a new population is created, copy it back */for (i = 0; i < POPSIZE; i++)population[i] = newpopulation[i];}/***************************************************************//* Crossover selection: selects two parents that take part in *//* the crossover. Implements a single point crossover */ /***************************************************************/void crossover(void){int i, mem, one;int first = 0; /* count of the number of members chosen */ double x;for (mem = 0; mem < POPSIZE; ++mem){x = rand()%1000/1000.0;if (x < PXOVER){++first;if (first % 2 == 0)Xover(one, mem);elseone = mem;}}}/**************************************************************//* Crossover: performs crossover of the two selected parents. *//**************************************************************/void Xover(int one, int two){int i;int point; /* crossover point *//* select crossover point */if(NVARS > 1){if(NVARS == 2)point = 1;elsepoint = (rand() % (NVARS - 1)) + 1;for (i = 0; i < point; i++)swap(&population[one].gene[i], &population[two].gene[i]);}}/*************************************************************//* Swap: A swap procedure that helps in swapping 2 variables */ /*************************************************************/void swap(double *x, double *y){double temp;temp = *x;*x = *y;*y = temp;}/**************************************************************//* Mutation: Random uniform mutation. A variable selected for *//* mutation is replaced by a random value between lower and */ /* upper bounds of this variable */ /**************************************************************/void mutate(void){int i, j;double lbound, hbound;double x;for (i = 0; i < POPSIZE; i++)for (j = 0; j < NVARS; j++){x = rand()%1000/1000.0;if (x < PMUTATION){/* find the bounds on the variable to be mutated */lbound = population[i].lower[j];hbound = population[i].upper[j];population[i].gene[j] = randval(lbound, hbound);}}}/***************************************************************//* Report function: Reports progress of the simulation. Data *//* dumped into the output file are separated by commas */ /***************************************************************/void report(void){int i;double best_val; /* best population fitness */double avg; /* avg population fitness */double stddev; /* std. deviation of population fitness */ double sum_square; /* sum of square for std. calc */ double square_sum; /* square of sum for std. calc */ double sum; /* total population fitness */sum = 0.0;sum_square = 0.0;for (i = 0; i < POPSIZE; i++){sum += population[i].fitness;sum_square += population[i].fitness * population[i].fitness;}avg = sum/(double)POPSIZE;square_sum = avg * avg * POPSIZE;stddev = sqrt((sum_square - square_sum)/(POPSIZE - 1));best_val = population[POPSIZE].fitness;fprintf(galog, "\n%5d, %6.3f, %6.3f, %6.3f \n\n", generation,best_val, avg, stddev); }/**************************************************************//* Main function: Each generation involves selecting the best *//* members, performing crossover & mutation and then */ /* evaluating the resulting population, until the terminating *//* condition is satisfied */ /**************************************************************/void main(void){int i;if ((galog = fopen("galog.txt","w"))==NULL){exit(1);}generation = 0;fprintf(galog, "\n generation best average standard \n"); fprintf(galog, " number value fitness deviation \n"); initialize();evaluate();keep_the_best();while(generation<MAXGENS){generation++;select();crossover();mutate();report();evaluate();elitist();}fprintf(galog,"\n\n Simulation completed\n");fprintf(galog,"\n Best member: \n");for (i = 0; i < NVARS; i++){fprintf (galog,"\n var(%d) = %3.3f",i,population[POPSIZE].gene[i]);}fprintf(galog,"\n\n Best fitness = %3.3f",population[POPSIZE].fitness);fclose(galog);printf("Success\n");}/***************************************************************/链接库文件?这个简单一般的第三方库文件有2种提供方式1.lib静态库,这样必须在工程设置里面添加。
遗传算法的C语⾔实现(⼆)-----以求解TSP问题为例上⼀次我们使⽤遗传算法求解了⼀个较为复杂的多元⾮线性函数的极值问题,也基本了解了遗传算法的实现基本步骤。
这⼀次,我再以经典的TSP问题为例,更加深⼊地说明遗传算法中选择、交叉、变异等核⼼步骤的实现。
⽽且这⼀次解决的是离散型问题,上⼀次解决的是连续型问题,刚好形成对照。
⾸先介绍⼀下TSP问题。
TSP(traveling salesman problem,旅⾏商问题)是典型的NP完全问题,即其最坏情况下的时间复杂度随着问题规模的增⼤按指数⽅式增长,到⽬前为⽌还没有找到⼀个多项式时间的有效算法。
TSP问题可以描述为:已知n个城市之间的相互距离,某⼀旅⾏商从某⼀个城市出发,访问每个城市⼀次且仅⼀次,最后回到出发的城市,如何安排才能使其所⾛的路线最短。
换⾔之,就是寻找⼀条遍历n个城市的路径,或者说搜索⾃然⼦集X={1,2,...,n}(X的元素表⽰对n个城市的编号)的⼀个排列P(X)={V1,V2,....,Vn},使得Td=∑d(V i,V i+1)+d(V n,V1)取最⼩值,其中,d(V i,V i+1)表⽰城市V i到V i+1的距离。
TSP问题不仅仅是旅⾏商问题,其他许多NP完全问题也可以归结为TSP问题,如邮路问题,装配线上的螺母问题和产品的⽣产安排问题等等,也使得TSP问题的求解具有更加⼴泛的实际意义。
再来说针对TSP问题使⽤遗传算法的步骤。
(1)编码问题:由于这是⼀个离散型的问题,我们采⽤整数编码的⽅式,⽤1~n来表⽰n个城市,1~n的任意⼀个排列就构成了问题的⼀个解。
可以知道,对于n个城市的TSP问题,⼀共有n!种不同的路线。
(2)种群初始化:对于N个个体的种群,随机给出N个问题的解(相当于是染⾊体)作为初始种群。
这⾥具体采⽤的⽅法是:1,2,...,n作为第⼀个个体,然后2,3,..n分别与1交换位置得到n-1个解,从2开始,3,4,...,n分别与2交换位置得到n-2个解,依次类推。
计算智能作业三:遗传算法计算问题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位无符号二进制数就形成了个体的基因型,表示一个可行解。
C语言人工智能算法实现神经网络和遗传算法人工智能(Artificial Intelligence)是当今科技领域中备受关注的热门话题,而C语言作为一种广泛应用的编程语言,也可以用于实现人工智能算法。
本文将详细介绍如何用C语言来实现神经网络和遗传算法,以展示其在人工智能领域的应用。
1. 神经网络神经网络是一种模仿人脑的学习和决策过程的计算模型。
它由多个神经元组成的层级结构构成,每个神经元接收来自上一层神经元输出的信号,并根据一定的权重和激活函数来计算输出。
下图展示了一个简单的神经网络结构:[图1:神经网络结构图]为了实现一个神经网络,我们需要在C语言中定义神经网络的结构体,并实现前馈传播和反向传播算法。
首先,我们需要定义神经网络的层级结构,可以使用数组或链表来表达。
每个神经元需要存储权重、偏差和激活函数等信息。
我们可以使用结构体来表示神经元的属性,例如:```Ctypedef struct Neuron {double* weights; // 权重数组double bias; // 偏差double output; // 输出} Neuron;```然后,定义神经网络的结构体:```Ctypedef struct NeuralNetwork {int numLayers; // 层数int* layerSizes; // 每层神经元数量的数组Neuron** layers; // 神经元层级的数组} NeuralNetwork;```接下来,我们需要实现神经网络的前馈传播算法。
前馈传播算法用于将输入数据从输入层传递到输出层,并计算网络的输出。
算法的伪代码如下所示:```Cfor each layer in network {for each neuron in layer {calculate neuron's weighted sum of inputs;apply activation function to obtain neuron's output;}}```最后,需要实现神经网络的反向传播算法,用于根据期望输出来调整网络的权重和偏差。
一个简单实用的遗传算法c程序一个简单实用的遗传算法c程序(转载) 2009-07-28 23:09:03 阅读418 评论0 字号:大中小这是一个非常简单的遗传算法源代码,是由Denis Cormier (North Carolina State University)开发的,Sita S.Raghavan (University of North Carolina at Charlotte)修正。
代码保证尽可能少,实际上也不必查错。
对一特定的应用修正此代码,用户只需改变常数的定义并且定义“评价函数”即可。
注意代码的设计是求最大值,其中的目标函数只能取正值;且函数值和个体的适应值之间没有区别。
该系统使用比率选择、精华模型、单点杂交和均匀变异。
如果用文件编码(TTU-UITID-GGBKT-POIU-WUUI-0089)Gaussian变异替换均匀变异,可能得到更好的效果。
代码没有任何图形,甚至也没有屏幕输出,主要是保证在平台之间的高可移植性。
读者可以从,目录 coe/evol中的文件prog.c中获得。
要求输入的文件应该命名为‘gadata.txt’;系统产生的输出文件为‘galog.txt’。
输入的文件由几行组成:数目对应于变量数。
且每一行提供次序——对应于变量的上下界。
如第一行为第一个变量提供上下界,第二行为第二个变量提供上下界,等等。
一个简单实用的遗传算法c程序(转载) 2009-07-28 23:09:03 阅读418 评论0 字号:大中小这是一个非常简单的遗传算法源代码,是由Denis Cormier (North Carolina State University)开发的,Sita S.Raghavan (University of North Carolina at Charlotte)修正。
代码保证尽可能少,实际上也不必查错。
对一特定的应用修正此代码,用户只需改变常数的定义并且定义“评价函数”即可。
#include "stdio.h"#include "stdlib.h"#include "conio.h"#include "math.h"#include "time.h"#define num_C 12 //个体的个数,前6位表示x1,后6位表示x2 #define N 100 //群体规模为100#define pc 0.9 //交叉概率为0.9#define pm 0.1 //变异概率为10%#define ps 0.6 //进行选择时保留的比例#define genmax 2000 //最大代数200int RandomInteger(int low,int high);void Initial_gen(struct unit group[N]);void Sort(struct unit group[N]);void Copy_unit(struct unit *p1,struct unit *p2);void Cross(struct unit *p3,struct unit *p4);void Varation(struct unit group[N],int i);void Evolution(struct unit group[N]);float Calculate_cost(struct unit *p);void Print_optimum(struct unit group[N],int k);/* 定义个体信息*/typedef struct unit{int path[num_C]; //每个个体的信息double cost; //个体代价值};struct unit group[N]; //种群变量groupint num_gen=0; //记录当前达到第几代int main(){int i,j;srand((int)time(NULL)); //初始化随机数发生器Initial_gen(group); //初始化种群Evolution(group); //进化:选择、交叉、变异getch();return 0;}/* 初始化种群*/void Initial_gen(struct unit group[N]){int i,j;struct unit *p;for(i=0;i<=N-1;i++) //初始化种群里的100个个体{p=&group[i]; //p指向种群的第i个个体for(j=0;j<12;j++){p->path[j]=RandomInteger(0,9); //end }Calculate_cost(p); //计算该种群的函数值}//end 初始化种群}/* 种群进化,进化代数由genmax决定*/void Evolution(struct unit group[N]){int i,j;int temp1,temp2,temp3,temp4,temp5;temp1=N*pc/2;temp2=N*(1-pc);temp3=N*(1-pc/2);temp4=N*(1-ps);temp5=N*ps;for(i=1;i<=genmax;i++){//选择for(j=0;j<=temp4-1;j++){ Copy_unit(&group[j],&group[j+temp5]); }//交叉for(j=0;j<=temp1-1;){Cross(&group[temp2+j],&group[temp3+j]);j+=2;}//变异Varation(group,i);}Sort(group);Print_optimum(group,i-1); //输出当代(第i-1代)种群}/* 交叉*/void Cross(struct unit *p3,struct unit *p4){int i,j,cross_point;int son1[num_C],son2[num_C];for(i=0;i<=num_C-1;i++) //初始化son1、son2{son1[i]=-1;son2[i]=-1;}cross_point=RandomInteger(1,num_C-1); //交叉位随机生成//交叉,生成子代//子代1//子代1前半部分直接从父代复制for(i=0;i<=cross_point-1;i++) son1[i]=p3->path[i];for(i=cross_point;i<=num_C-1;i++)for(j=0;j<=num_C-1;j++) //补全p1{son1[i]=p4->path[j];}//end 子代1//子代2//子代1后半部分直接从父代复制for(i=cross_point;i<=num_C-1;i++) son2[i]=p4->path[i];for(i=0;i<=cross_point-1;i++){for(j=0;j<=num_C-1;j++) //补全p1{son2[i]=p3->path[j];}}//end 子代2//end 交叉for(i=0;i<=num_C-1;i++){p3->path[i]=son1[i];p4->path[i]=son2[i];}Calculate_cost(p3); //计算子代p1的函数值Calculate_cost(p4); //计算子代p2的函数值}/* 变异*/void Varation(struct unit group[N],int flag_v){int flag,i,j,k,temp;struct unit *p;flag=RandomInteger(1,100);//在进化后期,增大变异概率if((!flag>(flag_v>100))?(5*100*pm):(100*pm)){i=RandomInteger(0,N-1); //确定发生变异的个体j=RandomInteger(0,num_C-1); //确定发生变异的位k=RandomInteger(0,num_C-1);p=&group[i]; //变异temp=p->path[j];p->path[j]=p->path[k];p->path[k]=temp;Calculate_cost(p); //重新计算变异后的函数值}}/* 将种群中个体按函数值从小到大排序*/void Sort(struct unit group[N]){int i,j;struct unit temp,*p1,*p2;for(j=1;j<=N-1;j++) //排序总共需进行N-1轮{for(i=1;i<=N-1;i++){p1=&group[i-1];p2=&group[i];if(p1->cost>p2->cost) //值大的往后排{Copy_unit(p1,&temp);Copy_unit(p2,p1);Copy_unit(&temp,p2);}}//end 一轮排序}//end 排序}/* 计算某个个体的函数值*/float Calculate_cost(struct unit *p){double x1,x2;x1=0;if(p->path[0]>5){x1=p->path[1]+p->path[2]*0.1+p->path[3]*0.01+p->path[4]*0.001+p->path[5]*0.0001;}else if(p->path[0]<6){x1=0-(p->path[1]+p->path[2]*0.1+p->path[3]*0.01+p->path[4]*0.001+p->path[5]*0.0001);}x2=0;if(p->path[6]>5){}else if(p->path[6]<6){x2=0-(p->path[7]+p->path[8]*0.1+p->path[9]*0.01+p->path[10]*0.001+p->path[11]*0.0001);}p->cost=20+x1*x1+x2*x2-10*(cos(2*3.14*x1)+cos(2*3.14*x2));return(p->cost);}/* 复制种群中的p1到p2中*/void Copy_unit(struct unit *p1,struct unit *p2){int i;for(i=0;i<=num_C-1;i++)p2->path[i]=p1->path[i];p2->cost=p1->cost;}/* 生成一个介于两整型数之间的随机整数*/int RandomInteger(int low,int high){int k;double d;k=rand();k=(k!=RAND_MAX)?k:(k-1); //RAND_MAX是VC中可表示的最大整型数d=(double)k/((double)(RAND_MAX));k=(int)(d*(high-low+1));return (low+k);}/* 输出当代种群中的最优个体*/void Print_optimum(struct unit group[N],int k){struct unit *p;double x1,x2;x1=x2=0;p=&group[0];if(p->path[0]>5){x1=p->path[1]+p->path[2]*0.1+p->path[3]*0.01+p->path[4]*0.001+p->path[5]*0.0001;}else if(p->path[0]<6){}x2=0;if(p->path[6]>5){x2=p->path[7]+p->path[8]*0.1+p->path[9]*0.01+p->path[10]*0.001+p->path[11]*0.0001;}else if(p->path[6]<6){x2=0-(p->path[7]+p->path[8]*0.1+p->path[9]*0.01+p->path[10]*0.001+p->path[11]*0.0001);}printf(" 当x1=%f x2=%f\n",x1,x2);printf(" 函数最小值为:%f \n",p->cost);}。
以下是一个简单的遗传算法的C语言代码示例:c#include <stdio.h>#include <stdlib.h>#include <time.h>#include <math.h>#define POPULATION_SIZE 100#define GENE_LENGTH 10#define MAX_GENERATIONS 1000#define MUTATION_RATE 0.01#define CROSSOVER_RATE 0.8typedef struct Individual {char genes[GENE_LENGTH];double fitness;} Individual;double calculate_fitness(Individual* individual) {// 计算适应度函数,这里使用简单的二进制字符串中1的个数作为适应度 int count = 0;for (int i = 0; i < GENE_LENGTH; i++) {if (individual->genes[i] == '1') {count++;}}return count;}void initialize_population(Individual* population) {// 初始化种群for (int i = 0; i < POPULATION_SIZE; i++) {for (int j = 0; j < GENE_LENGTH; j++) {population[i].genes[j] = rand() % 2 ? '0' : '1';}population[i].fitness = calculate_fitness(&population[i]); }}void selection(Individual* population, Individual* parents) {// 选择操作,采用轮盘赌算法选择两个父代个体double total_fitness = 0;for (int i = 0; i < POPULATION_SIZE; i++) {total_fitness += population[i].fitness;}double rand1 = rand() / (double)RAND_MAX * total_fitness;double rand2 = rand() / (double)RAND_MAX * total_fitness;double cumulative_fitness = 0;int parent1_index = -1, parent2_index = -1;for (int i = 0; i < POPULATION_SIZE; i++) {cumulative_fitness += population[i].fitness;if (rand1 < cumulative_fitness && parent1_index == -1) {parent1_index = i;}if (rand2 < cumulative_fitness && parent2_index == -1) {parent2_index = i;}}parents[0] = population[parent1_index];parents[1] = population[parent2_index];}void crossover(Individual* parents, Individual* offspring) {// 交叉操作,采用单点交叉算法生成两个子代个体int crossover_point = rand() % GENE_LENGTH;for (int i = 0; i < crossover_point; i++) {offspring[0].genes[i] = parents[0].genes[i];offspring[1].genes[i] = parents[1].genes[i];}for (int i = crossover_point; i < GENE_LENGTH; i++) {offspring[0].genes[i] = parents[1].genes[i];offspring[1].genes[i] = parents[0].genes[i];}offspring[0].fitness = calculate_fitness(&offspring[0]);offspring[1].fitness = calculate_fitness(&offspring[1]);}void mutation(Individual* individual) {// 变异操作,以一定概率翻转基因位上的值for (int i = 0; i < GENE_LENGTH; i++) {if (rand() / (double)RAND_MAX < MUTATION_RATE) {individual->genes[i] = individual->genes[i] == '0' ? '1' : '0'; }}individual->fitness = calculate_fitness(individual);}void replace(Individual* population, Individual* offspring) {// 替换操作,将两个子代个体中适应度更高的一个替换掉种群中适应度最低的一个个体int worst_index = -1;double worst_fitness = INFINITY;for (int i = 0; i < POPULATION_SIZE; i++) {if (population[i].fitness < worst_fitness) {worst_index = i;worst_fitness = population[i].fitness;}}if (offspring[0].fitness > worst_fitness || offspring[1].fitness > worst_fitness) {if (offspring[0].fitness > offspring[1].fitness) {population[worst_index] = offspring[0];} else {population[worst_index] = offspring[1];}}}。
此例程总共包含3个文件:main.c(主函数);GA.c(包含3个所用函数);GA.h(头文件),3个文件截图如下:用visual c++或者visual stutio创建工程,然后将上述3个文件包含进工程,编译运行即可。
亲测可行!!!3个文件代码分别如下:1、main.c:#include<iostream>#include"GA.h"using namespace std;/*******************************************************************GA demo求函数y=x*sin(10*pai*x)+2.0的最大值编码:浮点数,1位初始群体数:50变异概率:0.8进化代数:100取值范围:[0,4]变异步长:0.004注:因为是单数浮点数编码,所以未使用基因重组函数**********************************************************************/int main(){GenEngine genEngine(50,0.8,0.8,1,100,0,4);genEngine.OnStartGenAlg();getchar();}2、GA.c:#include<vector>#include<stdio.h>#include <stdlib.h>#include <time.h>#include<iostream>#include"GA.h"using namespace std;//srand((unsigned) time(NULL));double random(){double randNum;randNum=rand()*1.0/RAND_MAX;return randNum;}GenAlg::GenAlg(){}void GenAlg::init(int popsize, double MutRate, double CrossRate, int GenLenght,double LeftPoint,double RightPoint){popSize = popsize;mutationRate = MutRate;crossoverRate = CrossRate;chromoLength = GenLenght;totalFitness = 0;generation = 0;//fittestGenome = 0;bestFitness = 0.0;worstFitness = 99999999;averageFitness = 0;maxPerturbation=0.004;leftPoint=LeftPoint;rightPoint=RightPoint;//清空种群容器,以初始化vecPop.clear();for (int i=0; i<popSize; i++){//类的构造函数已经把适应性评分初始化为0vecPop.push_back(Genome());//把所有的基因编码初始化为函数区间内的随机数。
代码://作者:鸡毛巾,2014年12月26日12:35:02//这是一个遗传算法的例子,关于此程序的详细介绍请参看《复杂》(美)米歇尔,第九章//网络上可以寻找到此书的PDF#include <stdio.h>#include <stdlib.h>#include <time.h>#include <conio.h>//网格大小#define GRID_SIZE 12//格子可选种类数量#define GRID_NUM 3//空白格子#define GRID_BLANK 0//有罐子的格子#define GRID_CANS 1//为墙的格子#define GRID_W ALL 2//行为可选种类数量#define GO_NUM 7//向上走步#define GO_UP 0//向下走步#define GO_DOWN 1//向左走步#define GO_LEFT 2//向右走步#define GO_RIGHT 3//四方向随机走步#define GO_RAND 4//停止不动#define GO_STOP 5//执行清扫工作#define GO_CLEAN 6//罗比DNA序列长度#define DNA_LEN ( GRID_NUM * GRID_NUM * GRID_NUM * GRID_NUM * GRID_NUM )//总步数#define STP_NUM 200//随机因子,决定繁殖权利的两极分化程度,这里2为两级分化最大,反比#define RAND_FACTOR 2//基因突变概率#define MUTATION_PBT 2//进化场内罗比个数#define ROBBIE_NUM 200//罗比每轮总清扫次数#define CLEAN_COUNT 100//罗比DNA序列类型,包含了243种情况下罗比应当采取的举动typedef unsigned char DNA[DNA_LEN];//网格类型typedef unsigned char grid[GRID_SIZE][GRID_SIZE];//进化场类型typedef DNA evo_space[ROBBIE_NUM];//向量结构typedef struct scoring scoring;struct scoring{int id;int score;};//计分板类型typedef scoring scoreboard[ROBBIE_NUM];//32位的随机数产生函数,标准库的rand()函数并不能满足大随机数生成需要int rand32(){unsigned int rv = 0;rv |= rand() % 256;rv <<= 8;rv |= rand() % 256;rv <<= 8;rv |= rand() % 256;rv <<= 8;rv |= rand() % 256;//范围为0 ~ 0x7fffffff,不允许出现负数rv &= 0x7fffffff;return ( int )rv;}//随机方式初始化一个DNA序列void rand_DNA( DNA aDNA ){int i;for( i = 0; i < sizeof( DNA ); i++ ){aDNA[i] = rand() % GO_NUM;}}//随机方式初始化进化场void rand_evo_space( evo_space asp ){int i;for( i = 0; i < ROBBIE_NUM; i++ ){rand_DNA( asp[i] );}}//随机方式初始化一个网格void rand_grid( grid agd ){int x, y;for( y = 0; y < GRID_SIZE; y++ ){for( x = 0; x < GRID_SIZE; x++ ){if( ( y == 0 || y == GRID_SIZE - 1 ) ||( x == 0 || x == GRID_SIZE - 1 ) ){agd[y][x] = GRID_W ALL;}else{agd[y][x] = ( rand() % 2 ) ? GRID_CANS : GRID_BLANK;}}}}//显示网格void display_grid( const grid agd ){int x, y;for( y = 0; y < GRID_SIZE; y++ ){for( x = 0; x < GRID_SIZE; x++ ){if( GRID_BLANK == agd[y][x] ){printf( " " );}else if( GRID_CANS == agd[y][x] ){printf( "◎" );}else{printf( "▇" );}}printf( "\n" );}}//清理测试int clean_test( const DNA robbie, grid agd ){//得分int score = 0;//步数int stp_num = STP_NUM;//行为IDint id;int x = 1;int y = 1;int x2;int y2;while( stp_num > 0 ){//根据当前场景计算行为IDid = agd[y - 1][x] +agd[y + 1][x] * GRID_NUM +agd[y][x - 1] * GRID_NUM * GRID_NUM +agd[y][x + 1] * GRID_NUM * GRID_NUM * GRID_NUM +agd[y][x] * GRID_NUM * GRID_NUM * GRID_NUM * GRID_NUM;//派生坐标x2 = x;y2 = y;switch( robbie[id] ){case GO_UP:{y2--;}break;case GO_DOWN:{y2++;}break;case GO_LEFT:{x2--;}break;case GO_RIGHT:{x2++;}break;case GO_RAND:{//随机化增量int p = ( rand() % 2 ) ? 1 : -1;//随机选择移动坐标轴if( rand() % 2 ){y2 += p;}else{x2 += p;}}break;case GO_STOP:{}break;case GO_CLEAN:{//如果当前网格有罐子,执行清扫,加10分if( GRID_CANS == agd[y2][x2] ){score += 10;agd[y2][x2] = GRID_BLANK;} //当前网格没有罐子,扣1分else{score -= 1;}}break;default:{puts( "clean_test: DNA序列存在错误信息." );}};//如果撞墙,新的坐标将不会被应用,并且扣5分if( GRID_W ALL == agd[y2][x2] ){score -= 5;} //如果没有撞墙,则应用新的坐标else{x = x2;y = y2;}stp_num--;}return score;}//分析罗比适应度int analyse_adaptive_value( const DNA robbie ){int score[CLEAN_COUNT];int i;int sum = 0;grid gd;for( i = 0; i < CLEAN_COUNT; i++ ){rand_grid( gd );score[i] = clean_test( robbie, gd );}for( i = 0; i < CLEAN_COUNT; i++ ){sum += score[i];}return sum / CLEAN_COUNT;}//罗比基因突变void mutation( DNA rb ){//一对基因发生变异rb[rand() % DNA_LEN] = rand() % GO_NUM;rb[rand() % DNA_LEN] = rand() % GO_NUM;rb[rand() % DNA_LEN] = rand() % GO_NUM;rb[rand() % DNA_LEN] = rand() % GO_NUM;rb[rand() % DNA_LEN] = rand() % GO_NUM;rb[rand() % DNA_LEN] = rand() % GO_NUM;rb[rand() % DNA_LEN] = rand() % GO_NUM;rb[rand() % DNA_LEN] = rand() % GO_NUM; }void show_dna( const DNA aDNA ){int i;for( i = 0; i < DNA_LEN; i++ ){printf( "%d", aDNA[i] );}printf( "\n" );}//罗比繁殖,一对罗比繁殖出两个后代void reproduce( const DNA frb, const DNA mrb, DNA crb1, DNA crb2 ){//切割点为1到DNA_LEN - 1int p = 1 + rand() % ( DNA_LEN - 1 );int i;//产生后代1for( i = 0; i < p; i++ ){crb1[i] = frb[i];}for( i = p; i < DNA_LEN; i++ ){crb1[i] = mrb[i];}//产生后代2for( i = 0; i < p; i++ ){crb2[i] = mrb[i];}for( i = p; i < DNA_LEN; i++ ){crb2[i] = frb[i];}//后代1基因突变if( rand() % MUTA TION_PBT == 0 ){mutation( crb1 );}//后代2基因突变if( rand() % MUTA TION_PBT == 0 ){mutation( crb2 );}}//根据随机因子选择罗比int rand_select(){int id = 0;while( 1 ){if( rand() % RAND_FACTOR == 0 ){break;}id++;if( ROBBIE_NUM == id ){id = 0;}}return id;}//对于计分板进行选择法降序排序void sort_scoreboard( scoreboard board ){int i, j;int max;scoring tmp;for( j = 0; j < ROBBIE_NUM - 1; j++ ){max = j;for( i = j + 1; i < ROBBIE_NUM; i++ ){if( board[i].score > board[max].score ){max = i;}}if( max != j ){tmp = board[j];board[j] = board[max];board[max] = tmp;}}}//罗比进化void evo( evo_space sp1, evo_space sp2 ){scoreboard board;int i;//父罗比IDint fid;//母罗比IDint mid;//统计每一个罗比对于环境的适应度,写入计分板,适应度区间为1 - 2001 for( i = 0; i < ROBBIE_NUM; i++ ){board[i].id = i;board[i].score = analyse_adaptive_value( sp1[i] ) + 1001;}//对计分板进行排序sort_scoreboard( board );printf( "min = %d max = %d\n", board[ROBBIE_NUM - 1].score, board[0].score );for( i = 0; i < ROBBIE_NUM / 2; i++ ){fid = rand_select();mid = rand_select();while( mid == fid ){mid = rand_select();}//让选中的两对罗比繁殖,繁殖得到的两个后代送入进化场2reproduce( sp1[board[fid].id], sp1[board[mid].id], sp2[i * 2], sp2[i * 2 + 1] );}}//主函数int main( int argc, char * argv[] ){evo_space robbie1;evo_space robbie2;int i = 1;system( "title 进化的罗比" );srand( ( unsigned int )time( NULL ) );//随机方式初始化进化场内罗比rand_evo_space( robbie1 );while( 1 ){printf( "%d:", i++ );evo( robbie1, robbie2 );//_getch();printf( "%d:", i++ );evo( robbie2, robbie1 );//_getch();}return 0;}运行效果:这里得出的数据是适应度+ 1001(统一为正整数),进化了大约1000代之后产生了接近最优的策略(满分1500分)。
遗传算法,解决y=x^2 x属于[0,31] 的最大值问题。
C言语#include<stdio.h>#include<time.h>#include<stdlib.h>typedef struct{int code; //染色体int degree;//适应度}Indi;Indi group[40];//种群规模为40void Judge(Indi &x){x.degree=x.code*x.code;}int happened(double p)//发生一个p=0~1间概率的事件{return rand()<(int)(p*RAND_MAX);}void Cross(Indi &x,Indi &y)//交叉操作{Indi z,z1;int temp,temp1;temp=x.code&0x3;temp1=y.code&0x3;z.code=x.code-temp+temp1;z1.code=y.code-temp1+temp;Judge(z);Judge(z1);if(x.degree<y.degree){if(z.degree>=x.degree) //如果新个体不如双亲,淘汰之x=z;}else{if(z.degree>=y.degree)y=z;}if(x.degree<y.degree){if(z1.degree>=x.degree) //如果新个体不如双亲,淘汰之x=z1;}else{if(z1.degree>=y.degree)y=z1;}}void main(){Indi indidest;int i,j,best,x,y,c;int sum,strick,SUM=0;static int n=0;srand(time(NULL));for(i=0;i<40;++i)//随机得到初始种群{group[i].code=rand()%32;Judge(group[i]);}for(i=1;i<=10;++i)//固定进化10代{for(sum=0,best=0,j=0;j<40;++j){sum+=group[j].degree;//求总的适应度sumif(group[j].degree>group[best].degree){best=j;//求当前最优个体}}printf("第%2d代中最优个体为 %d (%d) 平均适应度为 %10f\n",i,group[best].code,group[best].degree,sum/40.0);for(c=40;c;--c){strick=(int)((float)rand()/RAND_MAX*sum); //赌盘中的色子,选择个体x,y for(x=0;x<40&&strick>=group[x].degree;++x)strick-=group[x].degree;strick=(int)((float)rand()/RAND_MAX*sum);for(y=0;y<40&&strick>=group[y].degree;++y)strick-=group[y].degree;if(happened(0.9))Cross(group[x],group[y]);//交叉}}}。
遗传算法C语言代码遗传算法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 randomlygenerates 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 *//**************************************** ************************///搜寻杰出个体函数:找出最好和最坏的个体。
遗传算法代码# iiiclude<stdio.h>#mclude<stnng.h> #mclude<stdlib.h> #mclude<math.h> #mclude<tmie.h>^define cities 10 〃城市的个数 ^define MAXX ]00//迭代次数 #define pc 0.8 〃交配概率 #define pm 0.05 〃变异概率 ^define num 10〃种群的人小 int bestsolution;//最优染色体int distance[cities] [cities];// 城市之间的距离stmct group //染色体的结构{int city [cities];// 城市的顺序int adapt;// 适应度 double p 〃在种群中的幸存概率} group [num] ,grouptemp [num];〃随机产生10个城市之间的相互距离 voidinit(){intij ;meniset(distance.0.sizeof(distance)); srand((uiisigned)tuue(NULL)); fbr(i=O ;i<cities;i++){fbr(j=i+l ;j<cities J++){distance [i] [j]=rand()% 100; distance[j][i]=distance[i]Ij];} }fbr(i=O;i<cities;i++)printf( ”************ 城市的距离矩阵如下************\ii n );pruitf(M%4d H,distance[i][j]);}}〃随机产生初试群void groupproduceQ{mt i j 丄k,flag;fbi(i=O ;i<num; i++) //初始化for(j=OJ<citiesj++) group[i].city[j]=-l;srand((uiisigned)tuue(NULL));fbi(i=O ;i<num: i++)血(J=Oj<citi 亡s;){ t=rand()%cities;flag=l;for(k=0;k<j;k++){if(group[i] .city[k]=t){flag=O;break:}} if(flag){group[i].city|j]=t; J++;}}}pnntfC************ 初始种群如下^***************^);fbi(i=0;i<num: i++)血(J=0 J <citi 亡s;j++) pimtf(M%4d,\gioup[i].city[j]);〃评价函数,找岀最优染色体void pmgjiaQint ij;iiit nl,ii2;mt sumdistance5biggestsum=O; double biggestp=O;fdr(i=O;i<num; i++){sumdistance=O;{nl=group[i].city|j-l];n2=group[i].city[j]; sumdistance4-=distance[nl][n2];}group [1] .adapt=sumd istaiice; 〃每条染色体的路径总和biggestsum+=sumdistance; 〃种群的总路径}fbi(i=O ;i<num: i++){group [i].p= 1 -(double)gioup(i] .adapt/(double)biggestsum;biggestp+=group[i].p;}fbi(i=O ;i<num: i++)gioup[i] .p=gioup[i] .p./biggestp;〃求最佳路劲bestsolution=0;fbi(i=O ;i<num: i++) if(gioup[i].p>gioup[bestsolution].p) bestsolution=i; }〃选择void xuanzeQ{mt ij^temp;double gradient[num]^/梯度概率double xuaiize[num];//选择染色体的随机概率mt xuaii[num];//选择了的染色体〃初始化梯度概率fbi(i=O ;i<num: i++)gradient[i]=O.O; xuaiize[i]=O.O;}gradient[0]=gioup[0].p;fbr(i= 1 ;i<num:i++)gradient[i]=gradient[i-1 ]+group[i] .p; srand((uiisigned)tune(NULL));〃随机产生染色体的存活概率fdr(i=O;i<num: i++){xuanze[i]=(rand()% 100); xuaiize[i]/=100;}〃选择能生存的染色体fdr(i=0;i<num: i++){{if(xu aiize [i] <gradient [j ]){xuan[i]=j; //第i个位置存放第j个染色体break;}}}〃拷贝种群fdr(i=0;i<num: i++){grouptenip [i]. adapt=gioup [i].adapt;giouptemp[i] .p=group[i] .p;fbi(j=0 j <cities;j ++)grouptenip [i].citv|j]=group [i]. c ity[j ];}〃数据更新fdr(i=0;i<num: i++){temp=xuan[i];groupfi] .adapt=giouptemp[temp] .adapt;group [1] .p=giouptemp [temp] .p;fbi(j=0 j <cities;j ++)group[i].city[j]=grouptemp[tenip].city[j];〃变异void bianyiQ{intij;mt t;mt temp 1 ,temp2.point;double buinyip[num]; 〃染色体的变异概率mtbianyiflag[num];//染色体的变异情况fbi(i=O ;i<num: i++)〃初始化bianyiflag[i]=O;〃随机产生变异概率srand((uiisigned)tune(NULL));fbi(i=O ;i<num: i++){bianyip[i]=(rand()% 100); bianyip[i]/=100;}〃确定可以变异的染色体t=0;for(i=0 ;i<num; i++){if(biaiivip[i]<pm){ biaiiviflag[i]=l; t++;}}〃变异操作,即交换染色体的两个节点srand((iuisigned)tiine(NULL));for(i=0 ;i<num; i++){if(biaiiviflag[i]== 1){templ=rand()%10;temp2=rand()% 10;pomt=group[i]・ city[temp 1 ]; group [i]. city [temp1 ]=gioup [1]. city [temp2 ]; group[i] .city[temp2]=pomt;o e :a【n d(XXVINV£3n¥fo C T bB U T doQonpo】ddno・bb O -S Hg o q o ・Teqo「(£2】o o y )U S S A S()UTCU 二UTo lunp 」f (A R §o q o )2wl^20q o ^.・o %w uc o sXUTPsqsns^******** ***************^f l 】0 A)近士定—障尉QTry f ******************5-:************* **********⑧ 琛c>^建翠 唳********************=)七.s】d宀(dcl.mdno乩z'uxpt%-®^^・・)七宀「(曰目。
// 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 *//****************************************************************///搜寻杰出个体函数:找出最好和最坏的个体。