/********************************************************** ********/
/* 基于基本遗传算法的函数最优化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; /* 当前运行次数*/
int maxruns; /* 总运行次数*/
int printstrings; /* 输出染色体编码的判断,0 -- 不输出, 1 -- 输出*/ int nmutation; /* 当前代变异发生次数*/
int ncross; /* 当前代交叉发生次数*/
/* 随机数发生器使用的静态变量*/
static double oldrand[55];
static int jrand;
static double rndx2;
static int rndcalcflag;
/* 输出文件指针*/
FILE *outfp ;
/* 函数定义*/
void advance_random();
int flip(float);rnd(int, int);
void randomize();
double randomnormaldeviate();
float randomperc(),rndreal(float,float);
void warmup_random(float);
void initialize(),initdata(),initpop();
void initreport(),generation(),initmalloc();
void freeall(),nomemory(char *),report();
void writepop(),writechrom(unsigned *);
void preselect();
void statistics(struct individual *);
void title(),repchar (FILE *,char *,int);
void skip(FILE *,int);
int select();
void objfunc(struct individual *);
int crossover (unsigned *, unsigned *, unsigned *, unsigned *); void mutation(unsigned *);
void initialize() /* 遗传算法初始化*/
{
/* 键盘输入遗传算法参数*/
initdata();
/* 确定染色体的字节长度*/
chromsize = (lchrom/(8*sizeof(unsigned)));
if(lchrom%(8*sizeof(unsigned))) chromsize++;
/*分配给全局数据结构空间*/
initmalloc();
/* 初始化随机数发生器*/
randomize();
/* 初始化全局计数变量和一些数值*/ nmutation = 0;
ncross = 0;
bestfit.fitness = 0.0;
bestfit.generation = 0;
/* 初始化种群,并统计计算结果*/ initpop();
statistics(oldpop);
initreport();
}
void initdata() /* 遗传算法参数输入*/
{
char answer[2];
setcolor(9);
disp_hz16("种群大小(20-100):",100,150,20); gscanf(320,150,9,15,4,"%d", &popsize);
if((popsize%2) != 0)
{
fprintf(outfp, "种群大小已设置为偶数\n"); popsize++;
};。