當前位置:首頁 » 操作系統 » 遺傳演算法c實現

遺傳演算法c實現

發布時間: 2023-08-14 14:30:26

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、遺傳演算法具有可擴展性,易於與其他技術混合使用。以上幾點便是遺傳演算法作為優化演算法所具備的優點。遺傳演算法的缺點:遺傳演算法在進行編碼時容易出現不規范不準確的問題。

熱點內容
不懂加工怎麼看數控車床配置 發布:2025-03-11 02:54:33 瀏覽:596
埋點系統存儲方案 發布:2025-03-11 02:41:20 瀏覽:442
編程要很久 發布:2025-03-11 02:41:10 瀏覽:195
筆記本電腦播放mp4時提醒伺服器運行失敗 發布:2025-03-11 02:40:32 瀏覽:440
吉利星瑞尊貴版配置有哪些 發布:2025-03-11 02:34:33 瀏覽:889
ecs中怎麼配置slb 發布:2025-03-11 02:33:17 瀏覽:719
vb圖片保存到資料庫 發布:2025-03-11 02:31:05 瀏覽:842
元件符號編譯器 發布:2025-03-11 02:30:12 瀏覽:73
位交換演算法 發布:2025-03-11 01:57:41 瀏覽:342
網游跟上傳 發布:2025-03-11 01:46:07 瀏覽:62