遗传算法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();}}}。

遗传算法C语言源代码(一元函数和二元函数)

遗传算法C语言源代码(一元函数和二元函数)

.专业整理 .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);//-----------}。

遗传算法解释及代码一看就懂

遗传算法解释及代码一看就懂

遗传算法( GA , Genetic Algorithm ) ,也称进化算法。

遗传算法是受达尔文的进化论的启发,借鉴生物进化过程而提出的一种启发式搜索算法。

因此在介绍遗传算法前有必要简单的介绍生物进化知识。

一.进化论知识作为遗传算法生物背景的介绍,下面内容了解即可:种群(Population):生物的进化以群体的形式进行,这样的一个群体称为种群。

个体:组成种群的单个生物。

基因 ( Gene ) :一个遗传因子。

染色体 ( Chromosome ):包含一组的基因。

生存竞争,适者生存:对环境适应度高的、牛B的个体参与繁殖的机会比较多,后代就会越来越多。

适应度低的个体参与繁殖的机会比较少,后代就会越来越少。

遗传与变异:新个体会遗传父母双方各一部分的基因,同时有一定的概率发生基因变异。

简单说来就是:繁殖过程,会发生基因交叉( Crossover ) ,基因突变( Mutation ) ,适应度( Fitness )低的个体会被逐步淘汰,而适应度高的个体会越来越多。

那么经过N代的自然选择后,保存下来的个体都是适应度很高的,其中很可能包含史上产生的适应度最高的那个个体。

二.遗传算法思想借鉴生物进化论,遗传算法将要解决的问题模拟成一个生物进化的过程,通过复制、交叉、突变等操作产生下一代的解,并逐步淘汰掉适应度函数值低的解,增加适应度函数值高的解。

这样进化N代后就很有可能会进化出适应度函数值很高的个体。

举个例子,使用遗传算法解决“0-1背包问题”的思路:0-1背包的解可以编码为一串0-1字符串(0:不取,1:取);首先,随机产生M个0-1字符串,然后评价这些0-1字符串作为0-1背包问题的解的优劣;然后,随机选择一些字符串通过交叉、突变等操作产生下一代的M个字符串,而且较优的解被选中的概率要比较高。

这样经过G代的进化后就可能会产生出0-1背包问题的一个“近似最优解”。

编码:需要将问题的解编码成字符串的形式才能使用遗传算法。

用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;}}。

(完整版)遗传算法简介及代码详解

(完整版)遗传算法简介及代码详解

遗传算法简述及代码详解声明:本文内容整理自网络,认为原作者同意转载,如有冒犯请联系我。

遗传算法基本内容遗传算法为群体优化算法,也就是从多个初始解开始进行优化,每个解称为一个染色体,各染色体之间通过竞争、合作、单独变异,不断进化。

遗传学与遗传算法中的基础术语比较染色体:又可以叫做基因型个体(individuals)群体/种群(population):一定数量的个体组成,及一定数量的染色体组成,群体中个体的数量叫做群体大小。

初始群体:若干染色体的集合,即解的规模,如30,50等,认为是随机选取的数据集合。

适应度(fitness):各个个体对环境的适应程度优化时先要将实际问题转换到遗传空间,就是把实际问题的解用染色体表示,称为编码,反过程为解码/译码,因为优化后要进行评价(此时得到的解是否较之前解优越),所以要返回问题空间,故要进行解码。

SGA采用二进制编码,染色体就是二进制位串,每一位可称为一个基因;如果直接生成二进制初始种群,则不必有编码过程,但要求解码时将染色体解码到问题可行域内。

遗传算法的准备工作:1) 数据转换操作,包括表现型到基因型的转换和基因型到表现型的转换。

前者是把求解空间中的参数转化成遗传空间中的染色体或者个体(encoding),后者是它的逆操作(decoding)2) 确定适应度计算函数,可以将个体值经过该函数转换为该个体的适应度,该适应度的高低要能充分反映该个体对于解得优秀程度。

非常重要的过程。

遗传算法基本过程为:1) 编码,创建初始群体2) 群体中个体适应度计算3) 评估适应度4) 根据适应度选择个体5) 被选择个体进行交叉繁殖6) 在繁殖的过程中引入变异机制7) 繁殖出新的群体,回到第二步实例一:(建议先看实例二)求 []30,0∈x 范围内的()210-=x y 的最小值1) 编码算法选择为"将x 转化为2进制的串",串的长度为5位(串的长度根据解的精度设 定,串长度越长解得精度越高)。

遗传算法案例及源代码

遗传算法案例及源代码

计算智能作业三:遗传算法计算问题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语言代码

(完整版)遗传算法c语言代码
//随机产生变异概率
srand((unsigned)time(NULL));
for(i=0;i<num;i++)
{
bianyip[i]=(rand()%100);
bianyip[i]/=100;
}
//确定可以变异的染色体
t=0;
for(i=0;i<num;i++)
{
if(bianyip[i]<pm)
printf("\n******************是否想再一次计算(y or n)***********************\n");
fflush(stdin);
scanf("%c",&choice);
}while(choice=='y');
return 0;
}
{
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]);
{
group[i].p=1-(double)group[i].adapt/(double)biggestsum;
biggestp+=group[i].p;

C语言版遗传算法

C语言版遗传算法
}; //城市间的距离矩阵
//distance[i][j]代表i城市与j城市的距离
/*
const static DISTANCE distance[][_CITY_AMOUNT]
={
0, 1, 4, 6, 8, 1, 3, 7, 2, 9, 7, 3, 4, 5, 8, 9, 2, 8, 2, 8,
{
cout << "第" << i+1 << "代" << std::endl;
CUnit.fnDispProbability();
CUnit.fnDispHistoryMin();
}
}
CUnit.fnDispHistoryMin();
int fnEvalOne(T &Gene); //测试某一个基因的适应度
void fnDispProbability(); //显示每个个体的权值
void fnDispHistoryMin();
private:
bool fnGeneAberranceOne(const int &i, const int &j);//变异某个基因
//#define _XCHG_GENE_AMOUNT_WHEN_MIX 2 //每次杂交所交换的碱基数量
#define _TIMES 50 //定义进化次数
#define _DISP_INTERVAL 5 //每隔多少次显示基因中的最高适应度
#define _CONTAINER std::vector<int> //定义个体基因容器类型
#define _CONTAINER_P std::vector<int> //定义适应度容器类型

遗传算法 c语言代码

遗传算法 c语言代码

以下是一个简单的遗传算法的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];}}}。

遗传算法的C++代码实现教程

遗传算法的C++代码实现教程

此例程总共包含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());//把所有的基因编码初始化为函数区间内的随机数。

基本遗传算法源程序

基本遗传算法源程序
CSCCADlg::CSCCADlg(CWnd* pParent /*=NULL*/) : CDialog(CSCCADlg::IDD, pParent)
{ //{{AFX_DATA_INIT(CSCCADlg) m_N = 0; m_c = 0; m_ge = 0; m_zz = 0.0; m_x2 = 0.0; m_x3 = 0.0; m_x4 = 0.0; m_x5 = 0.0; m_y1 = 0.0; m_y2 = 0.0; m_y3 = 0.0; m_y4 = 0.0; m_y5 = 0.0;
// DDX/DDV support
// Implementation protected:
1
//{{AFX_MSG(CAboutDlg) //}}AFX_MSG DECLARE_MESSAGE_MAP() };
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) {
//{{AFX_DATA_INIT(CAboutDlg) //}}AFX_DATA_INIT }
void CAboutDlg::DoDataExchange(CDataExchange* pDX) {
CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CAboutDlg) //}}AFX_DATA_MAP }
class CAboutDlg : public CDialog { public:
CAboutDlg();
// Dialog Data //{{AFX_DATA(CAboutDlg) enum { IDD = IDD_ABOUTBOX }; //}}AFX_DATA
// ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAboutDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); //}}AFX_VIRTUAL

遗传算法代码

遗传算法代码

%%GA求有约束下函数最小值,可求一般线性规划和非线性规划模型%%以下是主程序,完整代码可加qq七七零一二四零四久clcclear all;close all;%warning off%% 参数初始化popsize=100;%种群规模lenchrom=3;%染色体长度pc=0.7;%交叉概率pm=0.3;%变异概率maxgen=100;%最大迭代代数popmax=50;popmin=0;bound=[popmin popmax;popmin popmax;popmin popmax];%变量范围%%生成初始解for i=1:popsizeGApop(i,:)=Code(lenchrom,bound);%产生初始种群fitness(i)=fun(GApop(i,:));%计算适应度end[bestfitness bestindex]=min(fitness);zbest=GApop(bestindex,:);gbest=GApop;fitnessgbest=fitness;fitnesszbest=bestfitness;%%迭代寻优for i=1:maxgenGApop=Select(GApop,fitness,popsize);GApop=Cross(pc,lenchrom,GApop,popsize,bound);%交叉操作GApop=Mutation(pm,lenchrom,GApop,popsize,[i,maxgen],bound);%变异操作 pop=GApop;for j=1:popsizeif 1.0*pop(j,1)-1.0*pop(j,2)+1.0*pop(j,3)<=20if 3*pop(j,1)+2*pop(j,2)+4*pop(j,3)<=42if 3*pop(j,1)+2*pop(j,2)<=30fitness(j)=fun(pop(j,:));%适应度值endendendif fitness(j)<fitnessgbest%个体最优更新gbest(j,:)=pop(j,:);fitnessgbest=fitness(j);endif fitness(j)<fitnesszbest%种群最优更新zbest=pop(j,:);fitnesszbest=fitness(j);endendyy(i)=fitnesszbest;end%% 结果disp '***************best particle number******************'zbest%%plot(yy,'linewidth',2);title(['适应度曲线' '终止代数=' num2str(maxgen)]); xlabel('进化代数');ylabel('适应度');grid on%%输出结果子程序如下。

遗传算法源码

遗传算法源码

function [result,individual]=GA_OPT(popsize,stringlength,pc,pm,fun,a,b)%popsize初始种群数量%stringlength染色体长度%fun需要优化的函数%a,b是区间上下界%pc交叉概率0.9%pm变异概率0.08popsize=200;fun=@(x)x.* sin(10*pi*x)+2.0;stringlength=22;pc=0.9;pm=0.08;a=-1;b=2;pop=initial(popsize,stringlength,fun,a,b);%产生初始种群for i=1:200[bestindividual,bestvalue]=best(pop,stringlength);%计算个体适应度值newpop=selection(pop,popsize,stringlength);%比例选择运算newpop=crossover(newpop,stringlength,fun,a,b,pc);%单点交叉运算newpop=mutation(newpop,stringlength,fun,a,b,pm);%基本位变异运算pop=newpop;%产生新一代种群end[bestindividual,bestvalue]=best(pop,stringlength);result=bestvalue;individual=bestindividual;%得到最优函数值%--------种群初始化,随机生成二进制与解码-------------%function pop=initial(popsize,stringlength,fun,a,b)pop=round(rand(popsize,stringlength+2));%随机生成二进制数for i=1:popsize %在种群内pop(i,stringlength+1)=sum(2.^(stringlength-1:-1:0).*pop(i,1:stringlength))*(b-a)/(2^stringlength-1)+a; %把二进制数转化为对应的十进制数pop(i,stringlength+2)=fun(pop(i,stringlength+1));%求出二进制转化为十进制数后对应的函数值,为下面的计算个体适应值做准备%生成的pop矩阵为popsize*(stringlength+2)的矩阵,前面的stringlength列位二进制数%第stringlength+1列为二进制数转化为对应的十进制数,第stringlength+2列为二进制对应的函数值end%------------选择算子,按转轮赌方式方式选择-------------%function newpop=selection(pop,popsize,stringlength)totalfit=sum(pop(:,stringlength+2));%求种群中所有适应度函数之和prob=pop(:,stringlength+2)/totalfit;%计算每个个体占种群之和的比例prob=cumsum(prob);%计算比例的累积总和newin=1;while newin<=popsize %转轮赌方式生成新的个体rns=rand; %模拟赌盘操作,随机产生一个概率i=find(prob>rns);%找出个体的概率满足转轮赌方式的个体,即找出可以遗传到下一代的个体i=i(1);newpop(newin,:)=pop(i, :);%生成新的种群newin=newin+1;%继续循环end%----------------交叉算子,实现交叉运算-------------------%function newpop=crossover(newpop,stringlength,fun,a,b,pc)[px,py]=size(newpop);%求出新种群矩阵的大小(行和列)for i=1:2:px-1if rand<=pc%如果产生的随机数小于交叉概率,则进行交叉cpoint=unidrnd(stringlength-1);%随机生成一个1到stringlength-1的数,作为交叉点newpop(i,1:stringlength)=[newpop(i,1:cpoint),newpop(i+1,(cpoint+1):stringlength)];newpop(i+1,1:stringlength)=[newpop(i+1,1:cpoint),newpop(i,(cpoint+1):stringlength)];%在交叉点处实现第i与i+1二进制数的交叉newpop(i,stringlength+1)=sum(2.^(stringlength-1:-1:0).*newpop(i,1:stringlength))*(b-a)/(2^stringlen gth-1)+a;newpop(i+1,stringlength+1)=sum(2.^(stringlength-1:-1:0).*newpop(i+1,1:stringlength))*(b-a)/(2^stri nglength-1)+a;%算出交叉后的二进制数对应的十进制数newpop(i,stringlength+2)=fun(newpop(i,stringlength+1));newpop(i+1,stringlength+1)=fun(newpop(i+1,stringlength+1));%算出交叉后的二进制数对应的函数值elsenewpop(i, :)=newpop(i, :);newpop(i+1, :)=newpop(i+1, :);%形成新的种群矩阵endend%-----------------变异算子,实现变异运算-------------------%function newpop=mutation(newpop,stringlength,fun,a,b,pm)[px,py]=size(newpop);%求出新种群矩阵的大小(行和列)for i=1:pxif(rand<=pm)%随机生成一个概率小于变异概率后,实现变异运算mpoint=unidrnd(stringlength);%随机生成一个1到stringlength的数,作为变异点newpop(i,mpoint)=abs(newpop(i,mpoint)-1);%在变异点实现变异,使0变为1,1变为0 newpop(i,stringlength+1)=sum(2.^(stringlength-1:-1:0).*newpop(i,1:stringlength))*(b-a)/(2^stringlen gth-1)+a;%算出变异后的二进制数对应的十进制数newpop(i,stringlength+2)=fun(newpop(i,stringlength+1));%算出变异后的二进制数对应的函数值elsenewpop(i, :)=newpop(i, :);%形成新的种群矩阵endend%----------------求最大适应值-----------------%function [bestindividual,bestfit]=best(pop,stringlength)[px,py]=size(pop);%求出新种群矩阵的大小(行和列)bestindividual=pop(1,stringlength+1);bestfit=pop(1,stringlength+2);%把种群的第一个数作为初始值for i=2:px%在种群中从第二项开始if bestfit<pop(i,stringlength+2)%种群中如果哪一项比哪一项大,则代替之bestfit=pop(i,stringlength+2);bestindividual=pop(i,stringlength+1);%选出种群中最大的适应值,自变量的值和函数值endend。

遗传算法C语言代码

遗传算法C语言代码

遗传算法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 *//**************************************** ************************///搜寻杰出个体函数:找出最好和最坏的个体。

遗传算法解释及代码(一看就懂)

遗传算法解释及代码(一看就懂)

遗传算法( GA , Genetic Algorithm ) ,也称进化算法。

遗传算法是受达尔文的进化论的启发,借鉴生物进化过程而提出的一种启发式搜索算法。

因此在介绍遗传算法前有必要简单的介绍生物进化知识。

一.进化论知识作为遗传算法生物背景的介绍,下面内容了解即可:种群(Population):生物的进化以群体的形式进行,这样的一个群体称为种群。

个体:组成种群的单个生物。

基因 ( Gene ) :一个遗传因子。

染色体 ( Chromosome ):包含一组的基因。

生存竞争,适者生存:对环境适应度高的、牛B的个体参与繁殖的机会比较多,后代就会越来越多。

适应度低的个体参与繁殖的机会比较少,后代就会越来越少。

遗传与变异:新个体会遗传父母双方各一部分的基因,同时有一定的概率发生基因变异。

简单说来就是:繁殖过程,会发生基因交叉( Crossover ) ,基因突变( Mutation ) ,适应度( Fitness )低的个体会被逐步淘汰,而适应度高的个体会越来越多。

那么经过N代的自然选择后,保存下来的个体都是适应度很高的,其中很可能包含史上产生的适应度最高的那个个体。

二.遗传算法思想借鉴生物进化论,遗传算法将要解决的问题模拟成一个生物进化的过程,通过复制、交叉、突变等操作产生下一代的解,并逐步淘汰掉适应度函数值低的解,增加适应度函数值高的解。

这样进化N代后就很有可能会进化出适应度函数值很高的个体。

举个例子,使用遗传算法解决“0-1背包问题”的思路:0-1背包的解可以编码为一串0-1字符串(0:不取,1:取);首先,随机产生M个0-1字符串,然后评价这些0-1字符串作为0-1背包问题的解的优劣;然后,随机选择一些字符串通过交叉、突变等操作产生下一代的M个字符串,而且较优的解被选中的概率要比较高。

这样经过G代的进化后就可能会产生出0-1背包问题的一个“近似最优解”。

编码:需要将问题的解编码成字符串的形式才能使用遗传算法。

使用遗传算法求二元函数的最小值

使用遗传算法求二元函数的最小值

使⽤遗传算法求⼆元函数的最⼩值⼆元函数为y=x1^2+x2^2,x∈[-5,5]NIND=121; %初始种群的个数(Number of individuals)NVAR=2; %⼀个染⾊体(个体)有多少基因PRECI=20; %变量的⼆进制位数(Precision of variables)MAXGEN=200; %最⼤遗传代数(Maximum number of generations)GGAP=0.8; %代沟(Generation gap),以⼀定概率选择⽗代遗传到下⼀代trace=zeros(MAXGEN,2); %寻优结果的初始值Chrom=crtbp(NIND,PRECI*NVAR); %初始种群%区域描述器(Build field descriptor)%确定每个变量的⼆进制位数,取值范围,及取值范围是否包括边界等。

FieldD=[rep([PRECI],[1,NVAR]);rep([-5;5],[1,NVAR]);rep([1;0;1;1],[1,NVAR])];Objv=objfun(bs2rv(Chrom,FieldD))gen=1; %代计数器while gen<=MAXGENFitv=ranking(Objv); %分配适应度值(Assign fitness values)SelCh=select('sus',Chrom,Fitv,GGAP); %选择SelCh=recombin('xovsp',SelCh,1); %重组SelCh=mut(SelCh); %变异ObjVSel=objfun(bs2rv(SelCh,FieldD));%⼦代个体的⼗进制转换%重插⼊⼦代的新种群[Chrom,Objv]=reins(Chrom,SelCh,1,1,Objv,ObjVSel);trace(gen,1)=min(Objv); %遗传算法性能跟踪trace(gen,2)=sum(Objv)/length(Objv);gen=gen+1; %代计数器增加endplot(trace(:,1));hold onplot(trace(:,2),'.')gridlegend('最优解的变化','解的平均值的变化')根据上⾯的求解模型,可以写出模型的.M⽂件如下,即适应度函数% OBJFUN.M% Syntax: ObjVal = objfun1(Chrom,rtn_type)%% Input parameters:% Chrom - Matrix containing the chromosomes of the current% population. Each row corresponds to one individual's% string representation.% if Chrom == [], then special values will be returned% rtn_type - if Chrom == [] and% rtn_type == 1 (or []) return boundaries% rtn_type == 2 return title% rtn_type == 3 return value of global minimum%% Output parameters:% ObjVal - Column vector containing the objective values of the% individuals in the current population.% if called with Chrom == [], then ObjVal contains% rtn_type == 1, matrix with the boundaries of the function% rtn_type == 2, text for the title of the graphic output% rtn_type == 3, value of global minimum% Author: YQ_youngerfunction ObjVal = objfun(Chrom,rtn_type);% Dimension of objective functionDim = 2;% Compute population parameters[Nind,Nvar] = size(Chrom);% Check size of Chrom and do the appropriate thing% if Chrom is [], then define size of boundary-matrix and valuesif Nind == 0% return text of title for graphic outputif rtn_type == 2ObjVal = ['DE JONG function 1-' int2str(Dim)];% return value of global minimumelseif rtn_type == 3ObjVal = 0;% define size of boundary-matrix and valueselse% lower and upper bound, identical for all n variablesObjVal = 1*[-5; 5];ObjVal = ObjVal(1:2,ones(Dim,1));end% if Dim variables, compute values of functionelseif Nvar == Dim% function 1, sum of xi^2 for i = 1:Dim (Dim=30)% n = Dim, -5 <= xi <= 5% global minimum at (xi)=(0) ; fmin=0ObjVal = sum((Chrom .* Chrom)')';% ObjVal = diag(Chrom * Chrom'); % both lines produce the same% otherwise error, wrong format of Chromelseerror('size of matrix Chrom is not correct for function evaluation');end% End of function注释:种群表⽰和初始化函数 bs2rv:⼆进制串到实值的转换Phen=bs2rv(Chrom,FieldD) FieldD=[len, lb, ub, code, scale, lbin, ubin] code(i)=1为标准的⼆进制编码,code(i)=0为格雷编码scale(i)=0为算术刻度,scale(i)=1为对数刻度函数 crtbp:创建初始种群[Chrom,Lind,BaseV]=crtbp(Nind,Lind)[Chrom,Lind,BaseV]=crtbp(Nind,BaseV)[Chrom,Lind,BaseV]=crtbp(Nind,Lind,BaseV)Nind指定种群中个体的数量,Lind指定个体的长度函数 crtrp:创建实值原始种群Chrom=crtrp(Nind,FieldDR)适应度计算函数 ranking:基于排序的适应度分配(此函数是从最⼩化⽅向对个体进⾏排序的)FitV=ranking(ObjV)FitV=ranking(ObjV, RFun)FitV=ranking(ObjV, RFun, SUBPOP)Rfun(1)线性排序标量在[1 2]间为,⾮线性排序在[1 length(ObjV)-2] Rfun(2)指定排序⽅法,0为线性排序,1为⾮线性排序SUBPOP指明ObjV中⼦种群的数量,默认为1选择⾼级函数 select:从种群中选择个体SelCh=select(SEL_F, Chrom, FitnV)SelCh=select(SEL_F, Chrom, FitnV, GGAP)SelCh=select(SEL_F, Chrom, FitnV, GGAP, SUBPOP)SEL_F是⼀字符串,为⼀低级选择函数名,如rws或susGGAP指出了代沟,默认为1;也可⼤于1,允许⼦代数多于⽗代的数量rws: 轮盘赌选择NewChrIx=rws(FitnV, Nsel) 使⽤轮盘赌选择从⼀个种群中选择Nsel个个体NewChrIx 是为育种选择的个体的索引值sus:随机遍历抽样NewChrIx=sus(FitnV, Nsel)交叉⾼级函数 recombin:重组个体NewChrom=recombin(REC_F, Chrom)NewChrom=recombin(REC_F, Chrom, RecOpt)NewChrom=recombin(REC_F, Chrom, RecOpt, SUBPOP)REC_F是包含低级重组函数名的字符串,例如recdis,recint,reclin,xovdp, xovdprs, xovmp, xovsh, xovshrs, xovsp, xovsprs recdis:离散重组NewChrom=recdis(OldChorm)recint:中间重组NewChrom=recint(OldChorm)reclin:线性重组NewChrom=reclin(OldChorm)xovdp:两点交叉NewChrom=xovdp(OldChrom, XOVR)XOVR为交叉概率,默认为0.7Xovdprs:减少代理的两点交叉NewChrom=xovdprs(OldChrom, XOVR)Xovmp:多点交叉NewChrom=xovmp(OldChrom, XOVR, Npt, Rs)Npt指明交叉点数, 0 洗牌交叉;1 单点交叉;2 两点交叉;默认为0Rs指明使⽤减少代理, 0 不减少代理;1 减少代理;默认为0Xovsh:洗牌交叉NewChrom=xovsh(OldChrom, XOVR)Xovshrs:减少代理的洗牌交叉NewChrom=xovshrs(OldChrom, XOVR)Xovsp:单点交叉NewChrom=xovsp(OldChrom, XOVR)Xovsprs:减少代理的单点交叉NewChrom=xovsprs(OldChrom, XOVR)变异⾼级函数 mutate:个体的变异NewChorm=mutate(MUT_F, OldChorm, FieldDR) NewChorm=mutate(MUT_F, OldChorm, FieldDR, MutOpt) NewChorm=mutate(MUT_F, OldChorm, FieldDR, MutOpt, SUBPOP) MUT_F为包含低级变异函数的字符串,例如mut, mutbga, recmutmut:离散变异算⼦NewChrom=mut(OldChorm, Pm) NewChrom=mut(OldChorm, Pm, BaseV)Pm为变异概率,默认为Pm=0.7/Lindmutbga:实值种群的变异(遗传算法育种器的变异算⼦) NewChrom=mutbga(OldChorm, FieldDR)NewChrom=mubga(OldChorm, FieidDR, MutOpt)MutOpt(1)是在[ 0 1]间的重组概率的标量,默认为1MutOpt(2)是在[0 1]间的压缩重组范围的标量,默认为1(不压缩)recmut:具有突变特征的线性重组NewChrom=recmut(OldChorm, FieldDR)NewChrom=recmut(OldChorm, FieidDR, MutOpt)重插⼊函数 reins:重插⼊⼦群到种群Chorm=reins(Chorm, SelCh)Chorm=reins(Chorm, SelCh, SUBPOP)Chorm=reins(Chorm, SelCh, SUBPOP, InsOpt, ObjVch)[Chorm, ObjVch]=reins(Chorm, SelCh, SUBPOP, InsOpt, ObjVch, ObjVSel)InsOpt(1)指明⽤⼦代代替⽗代的选择⽅法,0为均匀选择,1为基于适应度的选择,默认为0InsOpt(2)指明在[0 1]间每个⼦种群中重插⼊的⼦代个体在整个⼦种群的中个体的⽐率,默认为1ObjVch包含Chorm中个体的⽬标值,对基于适应度的重插⼊是必需的ObjVSel包含Selch中个体的⽬标值,如⼦代数量⼤于重插⼊种群的⼦代数量是必需的其他函数矩阵复试函数 rep:MatOut=rep(MatIn, REPN)REPN为复制次数以上这篇使⽤遗传算法求⼆元函数的最⼩值就是⼩编分享给⼤家的全部内容了,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

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 //染色体长度//注意,你是求最大值还是求最小值int functionmode=minimization;//变量的上下限的修改开始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);//-----------}。

相关文档
最新文档