搜档网
当前位置:搜档网 › 遗传算法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变异替换均匀变异,可能得到更好的效果。

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

读者可以从https://www.sodocs.net/doc/3613541420.html,, 目录coe/evol中的文件prog.c中获得。

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

输入的文件由几行组成:数目对应于变量数。且每一行提供次序——对应于变量的上下界。如第一行为第一个变量提供上下界,第二行为第二个变量提供上下界,等等。

*/

#include

#include

#include

/* 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 0

int 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, j, i;

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

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 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);

else

one = 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;

else

point = (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

{

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");

}

/***************************************************************/

遗传算法的c语言程序

一需求分析 1.本程序演示的是用简单遗传算法随机一个种群,然后根据所给的交叉率,变异率,世代数计算最大适应度所在的代数 2.演示程序以用户和计算机的对话方式执行,即在计算机终端上显示“提示信息”之后,由用户在键盘上输入演示程序中规定的命令;相应的输入数据和运算结果显示在其后。3.测试数据 输入初始变量后用y=100*(x1*x1-x2)*(x1*x2-x2)+(1-x1)*(1-x1)其中-2.048<=x1,x2<=2.048作适应度函数求最大适应度即为函数的最大值 二概要设计 1.程序流程图 2.类型定义 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]; 3.函数声明 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(); 4.程序的各函数的简单算法说明如下: (1).void generateinitialpopulation ()和void input ()初始化种群和遗传算法参数。 input() 函数输入种群大小,染色体长度,最大世代数,交叉率,变异率等参数。 (2)void calculateobjectvalue();计算适应度函数值。 根据给定的变量用适应度函数计算然后返回适度值。 (3)选择函数selectoperator() 在函数selectoperator()中首先用rand ()函数产生0~1间的选择算子,当适度累计值不为零时,比较各个体所占总的适应度百分比的累计和与选择算子,直到达到选择算子的值那个个体就被选出,即适应度为fi的个体以fi/∑fk的概率继续存在; 显然,个体适应度愈高,被选中的概率愈大。但是,适应度小的个体也有可能被选中,以便增加下一代群体的多样性。 (4)染色体交叉函数crossoveroperator() 这是遗传算法中的最重要的函数之一,它是对个体两个变量所合成的染色体进行交叉,而不是变量染色体的交叉,这要搞清楚。首先用rand ()函数产生随机概率,若小于交叉概率,则进行染色体交叉,同时交叉次数加1。这时又要用rand()函数随机产生一位交叉位,把染色

MATLAB课程遗传算法实验报告及源代码

硕士生考查课程考试试卷 考试科目: 考生姓名:考生学号: 学院:专业: 考生成绩: 任课老师(签名) 考试日期:年月日午时至时

《MATLAB 教程》试题: A 、利用MATLA B 设计遗传算法程序,寻找下图11个端点最短路径,其中没有连接端点表示没有路径。要求设计遗传算法对该问题求解。 a e h k B 、设计遗传算法求解f (x)极小值,具体表达式如下: 321231(,,)5.12 5.12,1,2,3i i i f x x x x x i =?=???-≤≤=? ∑ 要求必须使用m 函数方式设计程序。 C 、利用MATLAB 编程实现:三名商人各带一个随从乘船渡河,一只小船只能容纳二人,由他们自己划行,随从们密约,在河的任一岸,一旦随从的人数比商人多,就杀人越货,但是如何乘船渡河的大权掌握在商人手中,商人们怎样才能安全渡河? D 、结合自己的研究方向选择合适的问题,利用MATLAB 进行实验。 以上四题任选一题进行实验,并写出实验报告。

选择题目: B 、设计遗传算法求解f (x)极小值,具体表达式如下: 321231(,,)5.12 5.12,1,2,3i i i f x x x x x i =?=???-≤≤=? ∑ 要求必须使用m 函数方式设计程序。 一、问题分析(10分) 这是一个简单的三元函数求最小值的函数优化问题,可以利用遗传算法来指导性搜索最小值。实验要求必须以matlab 为工具,利用遗传算法对问题进行求解。 在本实验中,要求我们用M 函数自行设计遗传算法,通过遗传算法基本原理,选择、交叉、变异等操作进行指导性邻域搜索,得到最优解。 二、实验原理与数学模型(20分) (1)试验原理: 用遗传算法求解函数优化问题,遗传算法是模拟生物在自然环境下的遗传和进化过程而形成的一种自适应全局优化概率搜索方法。其采纳了自然进化模型,从代表问题可能潜在解集的一个种群开始,种群由经过基因编码的一定数目的个体组成。每个个体实际上是染色体带有特征的实体;初始种群产生后,按照适者生存和优胜劣汰的原理,逐代演化产生出越来越好的解:在每一代,概据问题域中个体的适应度大小挑选个体;并借助遗传算子进行组合交叉和主客观变异,产生出代表新的解集的种群。这一过程循环执行,直到满足优化准则为止。最后,末代个体经解码,生成近似最优解。基于种群进化机制的遗传算法如同自然界进化一样,后生代种群比前生代更加适应于环境,通过逐代进化,逼近最优解。 遗传算法是一种现代智能算法,实际上它的功能十分强大,能够用于求解一些难以用常规数学手段进行求解的问题,尤其适用于求解多目标、多约束,且目标函数形式非常复杂的优化问题。但是遗传算法也有一些缺点,最为关键的一点,即没有任何理论能够证明遗传算法一定能够找到最优解,算法主要是根据概率论的思想来寻找最优解。因此,遗传算法所得到的解只是一个近似解,而不一定是最优解。 (2)数学模型 对于求解该问题遗传算法的构造过程: (1)确定决策变量和约束条件;

基本遗传算法的C源程序。doc【精品毕业设计】(完整版)

/********************************************************** ********/ /* 基于基本遗传算法的函数最优化SGA.C */ /* A Function Optimizer using Simple Genetic Algorithm */ /* developed from the Pascal SGA code presented by David E.Goldberg */ //********************************************************** ********/ #include #include #include #include "graph.c" /* 全局变量*/ struct individual /* 个体*/ { unsigned *chrom; /* 染色体*/ double fitness; /* 个体适应度*/ double varible; /* 个体对应的变量值*/ int xsite; /* 交叉位置*/ int parent[2]; /* 父个体*/ int *utility; /* 特定数据指针变量*/ };

struct bestever /* 最佳个体*/ { unsigned *chrom; /* 最佳个体染色体*/ double fitness; /* 最佳个体适应度*/ double varible; /* 最佳个体对应的变量值*/ int generation; /* 最佳个体生成代*/ }; struct individual *oldpop; /* 当前代种群*/ struct individual *newpop; /* 新一代种群*/ struct bestever bestfit; /* 最佳个体*/ double sumfitness; /* 种群中个体适应度累计*/ double max; /* 种群中个体最大适应度*/ double avg; /* 种群中个体平均适应度*/ double min; /* 种群中个体最小适应度*/ float pcross; /* 交叉概率*/ float pmutation; /* 变异概率*/ int popsize; /* 种群大小*/ int lchrom; /* 染色体长度*/ int chromsize; /* 存储一染色体所需字节数*/ int gen; /* 当前世代数*/ int maxgen; /* 最大世代数*/ int run; /* 当前运行次数*/

基于遗传算法的matlab源代码

function youhuafun D=code; N=50;%Tunable maxgen=50;%Tunable crossrate=0.5;%Tunable muterate=0.08;%Tunable generation=1; num=length(D); fatherrand=randint(num,N,3); score=zeros(maxgen,N); while generation<=maxgen ind=randperm(N-2)+2;%随机配对交叉 A=fatherrand(:,ind(1:(N-2)/2)); B=fatherrand(:,ind((N-2)/2+1:end)); %多点交叉 rnd=rand(num,(N-2)/2); ind=rnd tmp=A(ind); A(ind)=B(ind); B(ind)=tmp; %%两点交叉 %for kk=1:(N-2)/2 %rndtmp=randint(1,1,num)+1; %tmp=A(1:rndtmp,kk); %A(1:rndtmp,kk)=B(1:rndtmp,kk); %B(1:rndtmp,kk)=tmp; %end fatherrand=[fatherrand(:,1:2),A,B]; %变异 rnd=rand(num,N); ind=rnd[m,n]=size(ind); tmp=randint(m,n,2)+1; tmp(:,1:2)=0; fatherrand=tmp+fatherrand; fatherrand=mod(fatherrand,3); %fatherrand(ind)=tmp; %评价、选择 scoreN=scorefun(fatherrand,D);%求得N个个体的评价函数 score(generation,:)=scoreN; [scoreSort,scoreind]=sort(scoreN); sumscore=cumsum(scoreSort); sumscore=sumscore./sumscore(end); childind(1:2)=scoreind(end-1:end); for k=3:N tmprnd=rand; tmpind=tmprnd difind=[0,diff(t mpind)]; if~any(difind) difind(1)=1; end childind(k)=scoreind(logical(difind)); end fatherrand=fatherrand(:,childind); generation=generation+1; end %score maxV=max(score,[],2); minV=11*300-maxV; plot(minV,'*');title('各代的目标函数值'); F4=D(:,4); FF4=F4-fatherrand(:,1); FF4=max(FF4,1); D(:,5)=FF4; save DData D function D=code load youhua.mat %properties F2and F3 F1=A(:,1); F2=A(:,2); F3=A(:,3); if(max(F2)>1450)||(min(F2)<=900) error('DATA property F2exceed it''s range (900,1450]') end %get group property F1of data,according to F2value F4=zeros(size(F1)); for ite=11:-1:1 index=find(F2<=900+ite*50); F4(index)=ite; end D=[F1,F2,F3,F4]; function ScoreN=scorefun(fatherrand,D) F3=D(:,3); F4=D(:,4); N=size(fatherrand,2); FF4=F4*ones(1,N); FF4rnd=FF4-fatherrand; FF4rnd=max(FF4rnd,1); ScoreN=ones(1,N)*300*11; %这里有待优化

一个简单实用的遗传算法c程序完整版

一个简单实用的遗传算 法c程序 HEN system office room 【HEN16H-HENS2AHENS8Q8-HENH1688】

一个简单实用的遗传算法c程序(转载) 2009-07-28 23:09:03 阅读418 评论0 字号:大中小 这是一个非常简单的遗传算法源代码,是由Denis Cormier (North Carolina State University)开发的,Sita (University of North Carolina at Charlotte)修正。代码保证尽可能少,实际上也不必查错。对一特定的应用修正此代码,用户只需改变常数的定义并且定义“评价函数”即可。注意代码的设计是求最大值,其中的目标函数只能取正值;且函数值和个体的适应值之间没有区别。该系统使用比率选择、精华模型、单点杂交和均匀变异。如果用Gaussian变异替换均匀变异,可能得到更好的效果。代码没有任何图形,甚至也没有屏幕输出,主要是保证在平台之间的高可移植性。读者可以从,目录 coe/evol中的文件中获得。要求输入的文件应该命名为‘’;系统产生的输出文件为‘’。输入的文件由几行组成:数目对应于变量数。且每一行提供次序——对应于变量的上下界。如第一行为第一个变量提供上下界,第二行为第二个变量提供上下界,等等。 /**************************************************************************/ /* 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 <> #include <> #include <> /* Change any of these parameters to match your needs */ #define POPSIZE 50 /* population size */

遗传算法求解函数极值C语言代码

#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 //最大代数200 int 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]; //种群变量group int 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个个体 {

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

C语言遗传算法代码 以下为遗传算法的源代码,计算一元代函数的代码和二元函数的代码以+++++++++++++++++++++++++++++++++++++为分割线分割开来,请自行选择适合的代码,使用时请略看完代码的注释,在需要更改的地方更改为自己需要的代码。 +++++++++++++++++++++++++++++++一元函数代码++++++++++++++++++++++++++++ #include #include #include #include #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;

一个简单实用的遗传算法c程序

一个简单实用的遗传算法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变异替换均匀变异,可能得到更好的效果。代码没有任何图形,甚至也没有屏幕输出,主要是保证在平台之间的高可移植性。读者可以从https://www.sodocs.net/doc/3613541420.html,,目录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 #include #include /* Change any of these parameters to match your needs */

遗传算法的C语言程序案例

遗传算法的C语言程序案例 一、说明 1.本程序演示的是用简单遗传算法随机一个种群,然后根据所给的交叉率,变异率,世代数计算最大适应度所在的代数 2.演示程序以用户和计算机的对话方式执行,即在计算机终端上显示“提示信息”之后,由用户在键盘上输入演示程序中规定的命令;相应的输入数据和运算结果显示在其后。3.举个例子,输入初始变量后,用y= (x1*x1)+(x2*x2),其中-2.048<=x1,x2<=2.048作适应度函数求最大适应度即为函数的最大值 4.程序流程图

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]; 3.函数声明 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(); 6.程序的各函数的简单算法说明如下: (1).void generateinitialpopulation ()和void input ()初始化种群和遗传算法参数。 input() 函数输入种群大小,染色体长度,最大世代数,交叉率,变异率等参数。 (2)void calculateobjectvalue();计算适应度函数值。 根据给定的变量用适应度函数计算然后返回适度值。 (3)选择函数selectoperator() 在函数selectoperator()中首先用rand ()函数产生0~1间的选择算子,当适度累计值不为零时,比较各个体所占总的适应度百分比的累计和与选择算子,直到达到选择算子的值那个个

遗传算法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变异替换均匀变异,可能得到更好的效果。 代码没有任何图形,甚至也没有屏幕输出,主要是保证在平台之间的高可移植性。 读者可以从https://www.sodocs.net/doc/3613541420.html,, 目录coe/evol中的文件prog.c中获得。 要求输入的文件应该命名为‘gadata.txt’;系统产生的输出文件为‘galog.txt’。 输入的文件由几行组成:数目对应于变量数。且每一行提供次序——对应于变量的上下界。如第一行为第一个变量提供上下界,第二行为第二个变量提供上下界,等等。 */ #include #include #include /* 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 0 int 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 变量*/

遗传算法典范MATLAB代码

遗传算法经典学习Matlab代码 遗传算法实例: 也是自己找来的,原代码有少许错误,本人都已更正了,调试运行都通过了的。对于初学者,尤其是还没有编程经验的非常有用的一个文件 遗传算法实例 % 下面举例说明遗传算法 % % 求下列函数的最大值 % % f(x)=10*sin(5x)+7*cos(4x) x∈[0,10] % % 将 x 的值用一个10位的二值形式表示为二值问题,一个10位的二值数提供的分辨率是每为 (10-0)/(2^10-1)≈0.01 。 % % 将变量域 [0,10] 离散化为二值域 [0,1023], x=0+10*b/1023, 其 中 b 是 [0,1023] 中的一个二值数。 % % %

%--------------------------------------------------------------------------------------------------------------% %--------------------------------------------------------------------------------------------------------------% % 编程 %----------------------------------------------- % 2.1初始化(编码) % initpop.m函数的功能是实现群体的初始化,popsize表示群体的大小,chromlength表示染色体的长度(二值数的长度), % 长度大小取决于变量的二进制编码的长度(在本例中取10位)。 %遗传算法子程序 %Name: initpop.m %初始化 function pop=initpop(popsize,chromlength) pop=round(rand(popsize,chromlength)); % rand随机产生每个单元 为 {0,1} 行数为popsize,列数为chromlength的矩阵,

人工智能之遗传算法论文含源代码

30维线性方程求解 摘要:非线性方程组的求解是数值计算领域中最困难的问题,大多数的数值求解算法例如牛顿法的收敛性和性能特征在很大程度上依赖于初始点。但是对于很多高维的非线性方程组,选择好的初始点是一件非常困难的事情。本文采用了遗传算法的思想,提出了一种用于求解非线性方程组的混合遗传算法。该混合算法充分发挥了遗传算法的群体搜索和全局收敛性。选择了几个典型非线性方程组,考察它们的最适宜解。 关键词:非线性方程组;混合遗传算法;优化 1. 引言遗传算法是一种通用搜索算法,它基于自然选择机制和自然遗传规律来模拟自然界的进化过程,从而演化出解决问题的最优方法。它将适者生存、结构化但同时又是 随机的信息交换以及算法设计人的创造才能结合起来,形成一种独特的搜索算法,把一些解决方案用一定的方式来表示,放在一起成为群体。每一个方案的优劣程度即为适应性,根据自然界进化“优胜劣汰”的原则,逐步产生它们的后代,使后代具有更强的适应性,这样不断演化下去,就能得到更优解决方案。 随着现代自然科学和技术的发展,以及新学科、新领域的出现,非线性科学在工农业、经济政治、科学研究方面逐渐占有极其重要的位置。在理论研究和应用实践中,几乎绝大多数的问题都最终能化为方程或方程组,或者说,都离不开方程和方程组的求解。因此,在非线性问题中尤以非线性方程和非线性方程组的求解最为基本和重要。传统的解决方法,如简单迭代法、牛顿法、割线法、延拓法、搜索法、梯度法、共轭方向法、变尺度法,无论从算法的选择还是算法本身的构造都与所要解决的问题的特性有很大的关系。很多情况下,算法中算子的构造及其有效性成为我们解决问题的巨大障碍。而遗传算法无需过多地考虑问题的具体形式,因为它是一种灵活的自适应算法,尤其在一些非线性方程组没有精确解的时候,遗传算法显得更为有效。而且,遗传算法是一种高度并行的算法,且算法结构简单,非常便于在计算机上实现。本文所研究的正是将遗传算法应用于求解非线性方程组的问题。 2. 遗传算法解非线性方程组为了直观地观察用遗传算法求解非线性方程组的效果,我们这里用代数非线性方程组作为求解的对象问题描述:非线性方程组指的是有n 个变量(为了简化讨论,这里只讨论实变量方程组)的方程组 中含有非线性方程。其求解是指在其定义域内找出一组数能满足方程组中的每 个方程。这里,我们将方程组转化为一个函数则求解方程组就转化为求一组值使得成立。即求使函数取得最小值0 的一组数,于是方程组求解问题就转变为函数优化问题 3. 遗传算子 遗传算子设计包括交叉算子、变异算子和选择算子的设计。

遗传算法的0-1背包问题(c语言)

基于遗传算法的0-1背包问题的求解 摘要: 一、前言 组合优化问题的求解方法研究已经成为了当前众多科学关注的焦点,这不仅在于其内在的复杂性有着重要的理论价值,同时也在于它们能在现实生活中广泛的应用。比如资源分配、投资决策、装载设计、公交车调度等一系列的问题都可以归结到组合优化问题中来。但是,往往由于问题的计算量远远超出了计算机在有效时间内的计算能力,使问题的求解变为异常的困难。尤其对于NP 完全问题,如何求解其最优解或是近似最优解便成为科学的焦点之一。 遗传算法已经成为组合优化问题的近似最优解的一把钥匙。它是一种模拟生物进化过程的计算模型,作为一种新的全局优化搜索算法,它以其简单、鲁棒性强、适应并行处理以及应用范围广等特点,奠定了作为21世纪关键智能计算的地位。 背包问题是一个典型的组合优化问题,在计算理论中属于NP-完全问题, 其 计算复杂度为 )2(O n ,传统上采用动态规划来求解。设w[i]是经营活动 i 所需要的资源消耗,M 是所能提供的资源总量,p[i]是人们经营活动i 得到的利润或收益,则背包问题就是在资源有限的条件下, 追求总的最大收益的资源有效分配问题。 二、问题描述 背包问题( Knapsack Problem)的一般提法是:已知n 个物品的重量(weight )及其价值(或收益profit )分别为0>i w 和0>i p ,背包的容量(contain )假设设为0>i c ,如何选择哪些物品装入背包可以使得在背包的容量约束限制之内 所装物品的价值最大? 该问题的模型可以表示为下述0/1整数规划模型: 目标函数:∑==n i i i n x c x x x f 1 21),,(max Λ ????? =∈≤∑=) ,2,1(}1,0{t .s 1n i x p x w i n i i i i Λ (*)

遗传算法案例分析及源代码

一.问题描述: 在某一区域内有n 个客户,拟建一个物流中心,已知客户j 地址坐标为),(i i y x 。确定物流中心的地址坐标),(y x ,使得该物流中心到几个客户之间的距离最短。 假设:简单的用两点之间的距离代替运输距离。 目标函数: 22)()(min i i y Y x X z -+-= 约束条件: } 8,7,6,5,4,3,2,1,0{}8,7,6,5,4,3,2,1,0{X ∈∈Y 假设某一区域内有 5 个客户,其位置坐标如下表所示, 客户坐标及相关需求量 客户 X (km) Y(km) 1 1 5 2 2 8 3 5 1 4 7 6 5 8 3 (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 ):价值函数(自适应度函数)。 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 ):变异运算 (1)遗传算法主程序 %遗传算法的主程序

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

遗传算法代码 #include #include #include #include #include #define cities 10 //城市的个数 #define MAXX 100//迭代次数 #define pc 0.8 //交配概率 #define pm 0.05 //变异概率 #define num 10//种群的大小 int bestsolution;//最优染色体 int distance[cities][cities];//城市之间的距离 struct group //染色体的结构 { int city[cities];//城市的顺序 int adapt;//适应度 double p;//在种群中的幸存概率 }group[num],grouptemp[num]; //随机产生10个城市之间的相互距离 void init() { int i,j; memset(distance,0,sizeof(distance)); srand((unsigned)time(NULL)); for(i=0;i

遗传算法解决TSP问答(C)

遗传算法解决TSP问题(C++版) 遗传算法流程: 交叉,编译,计算适应度,保存最优个体。 其中交叉过程是选择最优的两个染色体进行交叉操作,本文采用的是轮盘赌算法。 #include #include #include using namespace std; #define population 200//种群数量 #define pc 0.9//交叉的概率 #define pm 0.1//变异的概率 #define count 200//迭代的次数 #define num 10//城市的数量 int** city;//存放每个个体的访问顺序 int path[10][10] = { //0, 1, 2, 3, 4, 5, 6, 7, 8, 9 { 0, 23, 93, 18, 40, 34, 13, 75, 50, 35 },//0 { 23, 0, 75, 4, 72, 74, 36, 57, 36, 22 },//1 { 93, 75, 0, 64, 21, 73, 51, 25, 74, 89 },//2 { 18, 4, 64, 0, 55, 52, 8, 10, 67, 1 }, //3 { 40, 72, 21, 55, 0, 43, 64, 6, 99, 74 }, //4 { 34, 74, 73, 52, 43, 0, 43, 66, 52, 39 },//5 { 13, 36, 51, 8, 64, 43, 0, 16, 57, 94 },//6 { 75, 57, 25, 10, 6, 66, 16, 0, 23, 11 }, //7 { 50, 36, 74, 67, 99, 52, 57, 23, 0, 42 },//8 { 35, 22, 89, 1, 74, 39, 94, 11, 42, 0 }//9 }; int* dis;//存放每个个体的访问顺序下的路径长度 double* fitness;//存放灭个个体的适应度 int min_dis = 1000000; int min_index = -1;

使用MATLAB遗传算法工具实例(详细) (1)【精品毕业设计】(完整版)

最新发布的MA TLAB 7.0 Release 14已经包含了一个专门设计的遗传算法与直接搜索工具箱(Genetic Algorithm and Direct Search Toolbox,GADS)。使用遗传算法与直接搜索工具箱,可以扩展MATLAB及其优化工具箱在处理优化问题方面的能力,可以处理传统的优化技术难以解决的问题,包括那些难以定义或不便于数学建模的问题,可以解决目标函数较复杂的问题,比如目标函数不连续、或具有高度非线性、随机性以及目标函数没有导数的情况。 本章8.1节首先介绍这个遗传算法与直接搜索工具箱,其余各节分别介绍该工具箱中的遗传算法工具及其使用方法。 8.1 遗传算法与直接搜索工具箱概述 本节介绍MATLAB的GADS(遗传算法与直接搜索)工具箱的特点、图形用户界面及运行要求,解释如何编写待优化函数的M文件,且通过举例加以阐明。 8.1.1 工具箱的特点 GADS工具箱是一系列函数的集合,它们扩展了优化工具箱和MA TLAB数值计算环境的性能。遗传算法与直接搜索工具箱包含了要使用遗传算法和直接搜索算法来求解优化问题的一些例程。这些算法使我们能够求解那些标准优化工具箱范围之外的各种优化问题。所有工具箱函数都是MATLAB的M文件,这些文件由实现特定优化算法的MATLAB语句所写成。 使用语句 type function_name 就可以看到这些函数的MATLAB代码。我们也可以通过编写自己的M文件来实现来扩展遗传算法和直接搜索工具箱的性能,也可以将该工具箱与MATLAB的其他工具箱或Simulink结合使用,来求解优化问题。 工具箱函数可以通过图形界面或MA TLAB命令行来访问,它们是用MATLAB语言编写的,对用户开放,因此可以查看算法、修改源代码或生成用户函数。 遗传算法与直接搜索工具箱可以帮助我们求解那些不易用传统方法解决的问题,譬如表查找问题等。 遗传算法与直接搜索工具箱有一个精心设计的图形用户界面,可以帮助我们直观、方便、快速地求解最优化问题。 8.1.1.1 功能特点 遗传算法与直接搜索工具箱的功能特点如下: 图形用户界面和命令行函数可用来快速地描述问题、设置算法选项以及监控进程。 具有多个选项的遗传算法工具可用于问题创建、适应度计算、选择、交叉和变异。 直接搜索工具实现了一种模式搜索方法,其选项可用于定义网格尺寸、表决方法和搜索方法。 遗传算法与直接搜索工具箱函数可与MATLAB的优化工具箱或其他的MATLAB程序结合使用。 支持自动的M代码生成。 8.1.1.2 图形用户界面和命令行函数 遗传算法工具函数可以通过命令行和图形用户界面来使用遗传算法。直接搜索工具函数也可以通过命令行和图形用户界面来进行访问。图形用户界面可用来快速地定义问题、设置算法选项、对优化问题进行详细定义。 133

相关主题