遗传算法c实现
采用位域表示方法,可以节省存储,又能方便访问和操作。
structbs{
unsignedv0:3;
unsignedv1:3;
unsignedv2:3;
......
unsignedv31:3;
}data;
每个变量只需要三个bit,32个变量需要:32*3/8=12个字节,效率非常高。这里v0~v31也可以取更有意义的名字。
㈡ vc程序设计(遗传算法)
/**************************************************************/
/* 基于基本遗传算法的函数最优化 */
/* 同济大学计算机系 王小平 2000年5月 */
/**************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<graphics.h>
#include<math.h>
#include<time.h>
#include<string.h>
#include "graph.c"
#include "operator.c"
#define POP_SIZE 25 /* 种群大小 */
#define G_LENGTH 8 /* 染色体长度 */
#define C_RATE 0.2 /* 交叉概率 */
#define M_RATE 0.01 /* 变异概率 */
#define XMAX 255 /* 函数变量最大值 */
#define X1 350 /* 函数图形区窗口左上点X坐标 */
#define Y1 40 /* 函数图形区窗口左上点Y坐标 */
#define XR1 255 /* 函数图形区窗口长度 */
#define YR1 200 /* 函数图形区窗口高度 */
#define X2 360 /* 适应度图形区窗口左上点X坐标 */
#define Y2 280 /* 适应度图形区窗口左上点Y坐标 */
#define XR2 250 /* 适应度图形区窗口长度 */
#define YR2 100 /* 适应度图形区窗口宽度 */
#define STEP 2 /* 适应度图形区X方向步长 */
void initialize_gene(gene,pop_size,g_length)
/* 种群中个体遗传基因型的初始化 */
unsigned char *gene; /* 遗传基因 */
int pop_size; /* 种群大小 */
int g_length; /* 个体染色体长度 */
{
int i,j;
randomize();
for(i=0;i<pop_size;i++)
for(j=0;j<g_length;j++)
*(gene+i*g_length+j)=random(2);
}
int gene_to_pheno(gene,g_length)
/* 基因型到表现型的变换--解码 */
unsigned char *gene; /* 基因型 */
int g_length; /* 染色体长度 */
{
int i,pheno;
pheno=0;
for(i=0;i<g_length;i++)
pheno=pheno*2+*(gene+i);
return(pheno);
}
void calc_fitness(gene,fitness,pop_size,g_length,func, max_fit,avg_fit)
/* 计算种群中个体的适应度 */
unsigned char *gene; /* 个体的遗传基因 */
double *fitness; /* 个体的适应度 */
double *func; /* 评价函数 */
double *max_fit,*avg_fit; /* 最大适应度与平均适应度 */
int pop_size; /* 种群大小 */
int g_length; /* 个体染色体长度 */
{
unsigned char *g; /* 个体的遗传基因指针变量 */
int pheno; /* 个体的表现型 */
int i,j;
double f;
*max_fit=0.0;
*avg_fit=0.0;
f=(double)pop_size;
for(i=0;i<pop_size;i++)
{
g=gene+i*g_length;
pheno=gene_to_pheno(g,g_length);
*(fitness+i)=*(func+pheno);
if(*(fitness+i)>*max_fit)
*max_fit=*(fitness+i);
*avg_fit=*avg_fit+*(fitness+i)/f;
}
}
void sga_reproction(gene,fitness,new_gene,new_fitness,pop_size,g_length)
/* 基于个体的适应度评价进行新一代个体的选择(轮盘赌方法),选择后分别将新的基因型和适应度代入到新个体中 */
unsigned char *gene; /* 当前代的个体遗传基因型 */
unsigned char *new_gene; /* 新一代的个体遗传基因型 */
double *fitness; /* 当前代的个体适应度 */
double *new_fitness; /* 新一代的个体适应度 */
int pop_size; /* 种群大小 */
int g_length; /* 染色体长度 */
{
double sum_of_fitness;
double border;
double r; /* 轮盘上的选择位置变量 */
int i,j;
int num;
sum_of_fitness=0.0;
for(i=0;i<pop_size;i++) /* 轮盘赌的选择循环 */
sum_of_fitness=sum_of_fitness+*(fitness+i);
for(i=0;i<pop_size;i++)
{
r=sum_of_fitness*(random(10001)/10000.0);
num=0;
border=*fitness;
while(border<r)
{
num++;
border=border+*(fitness+num);
}
for(j=0;j<g_length;j++)
*(new_gene+i*g_length+j)=*(gene+num*g_length+j);
*(new_fitness+i)=*(fitness+num);
}
}
void sga_crossover(gene,pop_size,g_length,c_rate)
/* 基本遗传算法的交叉操作--单点交叉 */
unsigned char *gene; /* 遗传基因 */
int pop_size; /* 种群大小 */
int g_length; /* 个体染色体长度 */
double c_rate; /* 交叉概率 */
{
unsigned char *gene1; /* 父个体1的遗传基因指针变量 */
unsigned char *gene2; /* 父个体1的遗传基因指针变量 */
unsigned char work; /* 中间变量 */
int i,j;
int c_pos; /* 交叉位置变量 */
double r; /* 随机数变量 */
for(i=0;i<pop_size-1;i=i+2)
{
r=random(10001)/10000.0;
if(r<=c_rate)
{
gene1=gene+g_length*i;
gene2=gene1+g_length;
c_pos=random(g_length-2)+1;
for(j=c_pos;j<g_length;j++) /* 两个父个体之间部分遗传基因的交换 */
{ work=*(gene1+j);
*(gene1+j)=*(gene2+j);
*(gene2+j)=work;
}
}
}
}
void sga_mutation(gene,pop_size,g_length,m_rate)
/* 基本遗传算法的变异操作--个体遗传基因按小概率翻转 */
unsigned char *gene; /* 遗传基因 */
int pop_size; /* 种群大小 */
int g_length; /* 染色体长度 */
double m_rate; /* 变异概率 */
{
int i,j;
double r;
for(i=0;i<pop_size;i++)
{
for(j=0;j<g_length;j++)
r=random(10001)/10000.0;
if(r<=m_rate) /* 变异发生判断 */
{
if ( *(gene+g_length*i+j)==0)
*(gene+g_length*i+j)=1;
else
*(gene+g_length*i+j)=0;
}
}
}
void make_function(func,xmax)
/* 生成一个函数, 用于最优化计算的目标函数(最大化) */
/* f=∑ai*sin(x* bi+ci) 其中 ai∈[0, 0.35]的均匀随机数
bi∈[2*pi, 5*2*pi] /xmax的均匀随机数
ci∈[0, 2*pi]的均匀随机数
x∈[0,xmax]为优化变量
i=1,2,3 */
double *func; /* 函数值 */
int xmax; /* 变量最大值 <XMAX */
{
int x,i;
double a[3],b[3],c[3];
double pi=3.141592;
double fxmax,fx,f_value;
double f_min,f_max,f_mid,f_range;
double dbl;
randomize();
fxmax=(double)xmax;
for(i=0;i<3;i++) /* 优化函数为三个三角函数之和 */
{
a[i]=0.35*(random(10001)/10000.0);
b[i]=(4*(random(10001)/10000.0)+1)*2.0*pi/fxmax;
c[i]=2.0*pi*(random(10001)/10000.0);
}
f_min=1.0;
f_max=0.0;
for(x=0;x<=xmax;x++) /* 将优化函数正规化为[0,1]区间数 */
{
fx=(double)x;
f_value=0.0;
for(i=0;i<3;i++)
{
dbl=b[i]*fx+c[i];
f_value=f_value+a[i]*sin(dbl);
}
f_value=f_value+0.5;
if(f_value>f_max) f_max=f_value;
if(f_value<f_min) f_min=f_value;
*(func+x)=(double)f_value;
}
f_range=f_max-f_min;
f_mid=(f_max+f_min)/2.0;
for(x=0;x<=xmax;x++)
{
f_value=(*(func+x)-f_mid)/f_range+0.5;
if(f_value>1.0) f_value=1.0;
else if(f_value<0.0) f_value=0.0;
*(func+x)=f_value;
}
}
void g_draw_func(func,xmax)
/* 绘制优化函数的图形 */
double *func; /* 函数值 */
int xmax; /* 变量最大值 */
{
int x,y,x_old,y_old,i;
double f;
g_rectangle(X1+1,Y1+1,X1+XR1-1,Y1+YR1-1,0,1);
g_rectangle(X1+1,Y1-12,X1+XR1,Y1-1,8,1);
g_rectangle(X1,Y1,X1+XR1,Y1+YR1,6,0);
x_old=X1;
y_old=Y1+YR1-(int)(*func*YR1);
f=XR1/(double)xmax;
for(i=1;i<=xmax;i++)
{
x=X1+(int)(i*f);
y=Y1+YR1-(int)(*(func+i)*YR1);
g_line(x_old,y_old,x,y,12);
x_old=x;
y_old=y;
}
}
void g_init_grph(func,xmax)
/* 初始化画面的图形 */
double *func; /* 函数值 */
int xmax; /* 变量最大值 */
{
int x,y,x_old,y_old,i;
char c[5];
/*初始化函数图形区*/
g_rectangle(320,0,639,399,8,1);
g_rectangle(321,1,638,16,8,1);
disp_hz16("基于基本遗传算法的函数最优化",370,1,15);
disp_hz16("g(x)",X1-30,Y1-18,15);
disp_hz16("1.0",X1-30,Y1,15);
disp_hz16("0",X1-10,Y1+YR1,15);
disp_hz16("x",X1+XR1+10,Y1+YR1-20,15);
disp_hz16("XMAX",X1+XR1-10,Y1+YR1,15);
g_draw_func(func,xmax);
/* 初始化适应度图形区 */
g_rectangle(X2,Y2,X2+XR2,Y2+YR2,0,1);
g_rectangle(X2,Y2,X2+XR2,Y2+YR2,6,0);
setcolor(15);
disp_hz16("最大适应度",X2+5,Y2-18,15);
g_line(X2+90,Y2-10,X2+110,Y2-10,11);
setcolor(15);
disp_hz16("平均适应度",X2+120,Y2-18,15);
g_line(X2+205,Y2-10,X2+225,Y2-10,9);
setcolor(15);
disp_hz16("世代数",X2+168,Y2+YR2+10,15);
g_text(X2-30,Y2,15,"1.0");
/* g_text(X2-30,Y2+YR2,15,"0.0");*/
}
void g_plot_grph(num,gene,fitness,pop_size,g_length,func, xmax,max_fit,m_f_old,avg_fit,a_f_old,gen_num)
/* 随世代进化更新图形 */
unsigned char *gene; /* 遗传基因 */
double *fitness; /* 适应度 */
double *func; /* 函数值 */
double max_fit,m_f_old; /* 当前代最大适应度,上一代最大适应度 */
double avg_fit,a_f_old; /* 当前代平均适应度,上一代平均适应度 */
int num; /* 当前世代数 */
int pop_size; /* 种群大小 */
int g_length; /* 染色体长度 */
int xmax; /* 变量最大值 */
int gen_num; /* 最大世代数 */
{
int i,j,x,y,x_old,y_old;
double f;
unsigned char *g;
char c[10];
/* 显示当前世代种群中个体的遗传基因 */
if(num==gen_num-1)
{
for(i=0;i<pop_size;i++)
{
printf("Indv.%2d:",i+1);
for(j=0;j<g_length;j++)
printf("%d",*(gene+i*g_length+j));
printf("==>Fitness %.4f\n",*(fitness+i));
}
printf("Max_fit=%f \n",max_fit);
printf("Avg_fit=%f \n",avg_fit);
}
/* 显示个体在函数图形区中的位置 */
g_draw_func(func,xmax);
f=XR1/(double)xmax;
for(i=0;i<pop_size;i++)
{
g=gene+i*g_length;
j=gene_to_pheno(g,g_length);
x=X1+(int)(j*f);
y=Y1+YR1-*(func+j)*YR1;
g_line(x,y-10,x,y,15);
}
/* 适应度曲线的更新 */
if(num!=1 && num<=XR2/STEP)
{
if(num%10==0) /* 每隔10代更新一次 */
{
x=X2+(num-1)*STEP;
g_line(x,Y2+1,x,Y2+YR2-1,1);
sprintf(c,"%d",num);
if(num<100 || num%20==0)
g_text(x-8,Y2+YR2,15,c);
}
x_old=X2+(num-1)*STEP;
x=x_old+STEP;
y_old=Y2+YR2-(int)(m_f_old*YR2);
y=Y2+YR2-(int)(max_fit*YR2);
g_line(x_old,y_old,x,y,11);
y_old=Y2+YR2-(int)(a_f_old*YR2);
y=Y2+YR2-(int)(avg_fit*YR2);
g_line(x_old,y_old,x,y,9);
}
}
void generation(gene,fitness,pop_size,g_length, c_rate,m_rate,new_gene,new_fitness,func,xmax)
/* 世代进化的模拟 */
unsigned char *gene; /* 当前世代的个体遗传基因型 */
unsigned char *new_gene; /* 新一代的个体遗传基因型 */
double *fitness; /* 当前世代的个体适应度 */
double *new_fitness; /* 新一代的个体适应度 */
double *func; /* 优化函数 */
double c_rate,m_rate; /* 交叉概率和变异概率 */
int pop_size, g_length; /* 种群大小与染色体长度 */
{ int gen_max; /* 最大模拟世代数 */
int i,j,k;
double max_fit,avg_fit; /* 当前代最大适应度和平均适应度 */
double m_f_old,a_f_old; /* 新一代最大适应度和平均适应度 */
char choice[3];
setcolor(15);
disp_hz16("输入最大模拟世代数:",10,1,20);
gscanf(170,1,4,0,3,"%s",choice);
gen_max=atoi(choice);
m_f_old=0.0;
a_f_old=0.0;
for(i=0;i<gen_max;i++)
{
if(i==gen_max-1)
{
printf("\n");
printf("************Gen.%d*************\n",i+1);
}
calc_fitness(gene,fitness,pop_size,g_length,func,
&max_fit,&avg_fit);
sga_reproction(gene,fitness,new_gene,new_fitness,
pop_size,g_length);
for(j=0;j<pop_size;j++)
{
*(fitness+j)=*(new_fitness+j);
for(k=0;k<g_length;k++)
*(gene+g_length*j+k)=*(new_gene+g_length*j+k);
}
sga_crossover(gene,pop_size,g_length,c_rate);
sga_mutation(gene,pop_size,g_length,m_rate);
g_plot_grph(i,gene,fitness,pop_size,g_length,func,
xmax,max_fit,m_f_old,avg_fit,a_f_old,gen_max);
m_f_old=max_fit;
a_f_old=avg_fit;
}
}
main() /* 主程序 */
{
/*当前代的个体遗传基因型与新一代的个体遗传基因型 */
unsigned char gene[POP_SIZE][G_LENGTH], new_gene[POP_SIZE][G_LENGTH];
/*当前代的个体适应度与新一代个体的适应度 */
double fitness[POP_SIZE], new_fitness[POP_SIZE];
/* 优化函数 */
double func[XMAX+1];
/* 初始化图形设置 */
g_init();
/* 生成优化函数 */
make_function(func,XMAX);
/* 初始化显示画面 */
g_init_grph(func,XMAX);
/* 初始化种群 */
initialize_gene(gene,POP_SIZE,G_LENGTH);
/* 世代进化模拟 */
generation(gene,fitness,POP_SIZE,G_LENGTH,
C_RATE,M_RATE,new_gene,new_fitness,func,XMAX);
setcolor(9);
disp_hz16("回车键结束",350,430,20);
getch();
}
㈢ 如图,如何用这个PSO算法或遗传算法来求函数极值,用C语言编写代码
需要很多的子函数 %子程序:新物种交叉操作,函数名称存储为crossover.m function scro=crossover(population,seln,pc); BitLength=size(population,2); pcc=IfCroIfMut(pc);%根据交叉概率决定是否进行交叉操作,1则是,0则否 if pcc==1 chb=round(rand*(BitLength-2))+1;%在[1,BitLength-1]范围内随机产生一个交叉位 scro(1,:)=[population(seln(1),1:chb) population(seln(2),chb+1:BitLength)] scro(2,:)=[population(seln(2),1:chb) population(seln(1),chb+1:BitLength)] else scro(1,:)=population(seln(1),:); scro(2,:)=population(seln(2),:); end %子程序:计算适应度函数,函数名称存储为fitnessfun.m function [Fitvalue,cumsump]=fitnessfun(population); global BitLength global boundsbegin global boundsend popsize=size(population,1);%有popsize个个体 for i=1:popsize x=transform2to10(population(i,:));%将二进制转换为十进制 %转化为[-2,2]区间的实数 xx=boundsbegin+x*(boundsend-boundsbegin)/(power(2,BitLength)-1); Fitvalue(i)=targetfun(xx);%计算函数值,即适应度 end %给适...
望采纳!
㈣ C遗传算法
一个非常简单的遗传算法源代码,是由Denis Cormier (North Carolina State University)开发的,Sita S.Raghavan (University of North Carolina at Charlotte)修正。代码保证尽可能少,实际上也不必查错。对一特定的应用修正此代码,用户只需改变常数的定义并且定义“评价函数”即可。注意代码的设计是求最大值,其中的目标函数只能取正值;且函数值和个体的适应值之间没有区别。该系统使用比率选择、精华模型、单点杂交和均匀变异。如果用Gaussian变异替换均匀变异,可能得到更好的效果。代码没有任何图形,甚至也没有屏幕输出,主要是保证在平台之间的高可移植性。读者可以从ftp.uncc.e,目录 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 indivial 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 0
int generation; /* current generation no. */
int cur_best; /* best indivial */
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 proceres 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 of the best indivial */
/***************************************************************/
void keep_the_best()
{
int mem;
int i;
cur_best = 0; /* stores the index of the best indivial */
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, 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 indivial from the new population is better than */
/* the best indivial from the previous population, then */
/* the best from the new population; else replace the */
/* worst indivial 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, 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);
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 procere 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 */
/* mped into the output file are separated by commas */
/***************************************************************/
。。。。。
代码太多 你到下面呢个网站看看吧
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");
}
另外,虚机团上产品团购,超级便宜
㈤ 求C代码:遗传算法求函数最大值f(x)=x^2 x 从0到30
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
float f(float x)
{
return x * x;
}
void main()
{
float x[10];
float f1, f2;
int i, j;
float fmax;
int xfmax;
srand(time(NULL));
xfmax = 0;
x[0] = 15.0f;
f1 = f(x[0]);
f2 = f1 + 1.0f;
for (j = 0; fabs(f1 - f2) >= 0.0001f || j < 50; j++)
{
for (i = 0; i < 10; i++)
{
if (i != xfmax)
{
x[i] = -1;
while (!(x[i] >= 0 && x[i] <= 30))
{
x[i] = x[xfmax] + ((float)rand() / RAND_MAX * 2 - 1) * (15.0f / (j * 2 + 1));
}
}
}
xfmax = -1;
for (i = 0; i < 10; i++)
{
if (xfmax < 0 || fmax < f(x[i]))
{
fmax = f(x[i]);
xfmax = i;
}
}
f2 = f1;
f1 = fmax;
}
printf("f(%f) = %f\n", x[xfmax], fmax);
}
㈥ 求遗传算法(GA)C语言代码
.----来个例子,大家好理解..--
基于遗传算法的人工生命模拟
#include<stdio.h>
#include<stdlib.h>
#include<graphics.h>
#include<math.h>
#include<time.h>
#include<string.h>
#include "graph.c"
/* 宏定义 */
#define TL1 20 /* 植物性食物限制时间 */
#define TL2 5 /* 动物性食物限制时间 */
#define NEWFOODS 3 /* 植物性食物每代生成数目 */
#define MUTATION 0.05 /* 变异概率 */
#define G_LENGTH 32 /* 个体染色体长度 */
#define MAX_POP 100 /* 个体总数的最大值 */
#define MAX_FOOD 100 /* 食物总数的最大值 */
#define MAX_WX 60 /* 虚拟环境的长度最大值 */
#define MAX_WY 32 /* 虚拟环境的宽度最大值 */
#define SX1 330 /* 虚拟环境图左上角点x坐标 */
#define SY1 40 /* 虚拟环境图左上角点y坐标 */
#define GX 360 /* 个体数进化图形窗口的左上角点X坐标 */
#define GY 257 /* 个体数进化图形窗口的左上角点Y坐标 */
#define GXR 250 /* 个体数进化图形窗口的长度 */
#define GYR 100 /* 个体数进化图形窗口的宽度 */
#define GSTEP 2 /* 个体数进化图形窗口的X方向步长 */
#define R_LIFE 0.05 /* 初期产生生物数的环境比率 */
#define R_FOOD 0.02 /* 初期产生食物数的环境比率 */
#define SL_MIN 10 /* 个体寿命最小值 */
/* 全局变量 */
unsigned char gene[MAX_POP][G_LENGTH]; /* 遗传基因 */
unsigned char iflg[MAX_POP]; /* 个体死活状态标志变量 */
㈦ c语言实现*/遗传算法改进BP神经网络原理和算法实现怎么弄
遗传算法有相当大的引用。遗传算法在游戏中应用的现状在遗传编码时, 一般将瓦片的坐标作为基因进行实数编码, 染色体的第一个基因为起点坐标, 最后一个基因为终点坐标, 中间的基因为路径经过的每一个瓦片的坐标。在生成染色体时, 由起点出发, 随机选择当前结点的邻居节点中的可通过节点, 将其坐标加入染色体, 依此循环, 直到找到目标点为止, 生成了一条染色体。重复上述操作, 直到达到指定的种群规模。遗传算法的优点:1、遗传算法是以决策变量的编码作为运算对象,可以直接对集合、序列、矩阵、树、图等结构对象进行操作。这样的方式一方面有助于模拟生物的基因、染色体和遗传进化的过程,方便遗传操作算子的运用。另一方面也使得遗传算法具有广泛的应用领域,如函数优化、生产调度、自动控制、图像处理、机器学习、数据挖掘等领域。2、遗传算法直接以目标函数值作为搜索信息。它仅仅使用适应度函数值来度量个体的优良程度,不涉及目标函数值求导求微分的过程。因为在现实中很多目标函数是很难求导的,甚至是不存在导数的,所以这一点也使得遗传算法显示出高度的优越性。3、遗传算法具有群体搜索的特性。它的搜索过程是从一个具有多个个体的初始群体P(0)开始的,一方面可以有效地避免搜索一些不必搜索的点。另一方面由于传统的单点搜索方法在对多峰分布的搜索空间进行搜索时很容易陷入局部某个单峰的极值点,而遗传算法的群体搜索特性却可以避免这样的问题,因而可以体现出遗传算法的并行化和较好的全局搜索性。4、遗传算法基于概率规则,而不是确定性规则。这使得搜索更为灵活,参数对其搜索效果的影响也尽可能的小。5、遗传算法具有可扩展性,易于与其他技术混合使用。以上几点便是遗传算法作为优化算法所具备的优点。遗传算法的缺点:遗传算法在进行编码时容易出现不规范不准确的问题。