遗传算法的c语言程序

遗传算法的c语言程序
遗传算法的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()函数随机产生一位交叉位,把染色

体的交叉位的后面部分交叉即可;若大于交叉概率,则进行简单的染色体复制即可。

(5)染色体变异函数mutation()

变异是针对染色体字符变异的,而不是对个体而言,即个体变异的概率是一样。随机产生比较概率,若小于变异概率,则1变为0,0变为1,同时变异次数加1。

(6)long decodechromosome(char *,int,int)

本函数是染色体解码函数,它将以数组形式存储的二进制数转成十进制数,然后才能用适应度函数计算。

(7)void findbestandworstindividual()本函数是求最大适应度个体的,每一代的所有个体都要和初始的最佳比较,如果大于就赋给最佳。

(8)void outputtextreport () 输出种群统计结果

输出每一代的种群的最大适应度和平均适应度,最后输出全局最大值

三运行环境

本程序的开发工具是VC++,在VC++下运行。

四源代码

#include

#include

#include

#include

#define POPSIZE 500

#define maximization 1

#define minimization 2

#define cmax 100

#define cmin 0

#define length1 10

#define length2 10

#define chromlength length1+length2 //染色体长度

int functionmode=maximization;

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;

相关主题
相关文档
最新文档