#include stdio.h
創(chuàng)新互聯(lián)公司是一家專注于做網(wǎng)站、網(wǎng)站制作與策劃設(shè)計,石棉網(wǎng)站建設(shè)哪家好?創(chuàng)新互聯(lián)公司做網(wǎng)站,專注于網(wǎng)站建設(shè)10余年,網(wǎng)設(shè)計領(lǐng)域的專業(yè)建站公司;建站業(yè)務(wù)涵蓋:石棉等地區(qū)。石棉做網(wǎng)站價格咨詢:028-86922220
#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);
}
一個非常簡單的遺傳算法源代碼,是由Denis Cormier (North Carolina State University)開發(fā)的,Sita S.Raghavan (University of North Carolina at Charlotte)修正。代碼保證盡可能少,實際上也不必查錯。對一特定的應(yīng)用修正此代碼,用戶只需改變常數(shù)的定義并且定義“評價函數(shù)”即可。注意代碼的設(shè)計是求最大值,其中的目標函數(shù)只能取正值;且函數(shù)值和個體的適應(yīng)值之間沒有區(qū)別。該系統(tǒng)使用比率選擇、精華模型、單點雜交和均勻變異。如果用Gaussian變異替換均勻變異,可能得到更好的效果。代碼沒有任何圖形,甚至也沒有屏幕輸出,主要是保證在平臺之間的高可移植性。讀者可以從,目錄 coe/evol中的文件prog.c中獲得。要求輸入的文件應(yīng)該命名為‘gadata.txt’;系統(tǒng)產(chǎn)生的輸出文件為‘galog.txt’。輸入的文件由幾行組成:數(shù)目對應(yīng)于變量數(shù)。且每一行提供次序——對應(yīng)于變量的上下界。如第一行為第一個變量提供上下界,第二行為第二個變量提供上下界,等等。
/**************************************************************************/
/* This is a simple genetic algorithm implementation where the */
/* evaluation function takes positive values only and the */
/* fitness of an individual is the same as the value of the */
/* objective function */
/**************************************************************************/
#include stdio.h
#include stdlib.h
#include math.h
/* Change any of these parameters to match your needs */
#define POPSIZE 50 /* population size */
#define MAXGENS 1000 /* max. number of generations */
#define NVARS 3 /* no. of problem variables */
#define PXOVER 0.8 /* probability of crossover */
#define PMUTATION 0.15 /* probability of mutation */
#define TRUE 1
#define FALSE 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, 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
ppopulation[j+1].cfitness)
newpopulation[i] = population[j+1];
}
}
/* once a new population is created, copy it back */
for (i = 0; i POPSIZE; i++)
population[i] = newpopulation[i];
}
/***************************************************************/
/* Crossover selection: selects two parents that take part in */
/* the crossover. Implements a single point crossover */
/***************************************************************/
void crossover(void)
{
int i, mem, one;
int first = 0; /* count of the number of members chosen */
double x;
for (mem = 0; mem POPSIZE; ++mem)
{
x = rand()%1000/1000.0;
if (x PXOVER)
{
++first;
if (first % 2 == 0)
Xover(one, mem);
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 */
/***************************************************************/
。。。。。
代碼太多 你到下面呢個網(wǎng)站看看吧
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(generationMAXGENS)
{
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");
}
首先y=x*x在[0,31]這個函數(shù)的極值是取31的時候,用遺傳算法來解答這樣的問題是有點多余的。遺傳算法的主要步驟是4步,初始化種群,選擇,交叉,變異。這里說的淘汰函數(shù),很可能就是在選擇選擇算子,這個算子是根據(jù)最適合最優(yōu)先的算法來實現(xiàn)。舉個簡單的例子,你要用數(shù)字進行遺傳算法,肯定得把他轉(zhuǎn)化為2進制的染色體,【0-31】就是從00000-11111,每條染色體5個基因。對于選擇運算來說,每次要從種群選擇最優(yōu)的幾個,第一次完全是隨機的。假如隨機選4個染色體,選的4條染色體是1,2,3,4。很明顯他們的值是1,4,9,16,總和是30,那么選擇4的概率就是30分之16,這樣就可以盡可能的選擇大的數(shù)值。這里的淘汰域3,可能是每次淘汰3條染色體,或者每次只選擇3條最優(yōu)的染色體,視其選擇的條數(shù)而定。我看在程序里沒有用到這個東西。遺傳算法以及進化算法不限定于特殊的程序,每個人有不同的理解,不必拘泥于概念。
需要很多的子函數(shù) %子程序:新物種交叉操作,函數(shù)名稱存儲為crossover.m function scro=crossover(population,seln,pc); BitLength=size(population,2); pcc=IfCroIfMut(pc);%根據(jù)交叉概率決定是否進行交叉操作,1則是,0則否 if pcc==1 chb=round(rand*(BitLength-2))+1;%在[1,BitLength-1]范圍內(nèi)隨機產(chǎn)生一個交叉位 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 %子程序:計算適應(yīng)度函數(shù),函數(shù)名稱存儲為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,:));%將二進制轉(zhuǎn)換為十進制 %轉(zhuǎn)化為[-2,2]區(qū)間的實數(shù) xx=boundsbegin+x*(boundsend-boundsbegin)/(power(2,BitLength)-1); Fitvalue(i)=targetfun(xx);%計算函數(shù)值,即適應(yīng)度 end %給適...
望采納!