c语言遗传算法 解决 y=x2问题
// 遗传算法 解决 y=x2问题
//编译环境 vc++6.0
//声明:部分代码来自网络
//email: happyppme@http://doc.docsou.com
#include
#include
#include
#include
#define POPSIZE 500 //种群大小
#define chromlength 8 //染色体长度
int popsize ; //种群大小
int maxgeneration; //最大世代数
double pc = 0.0; //交叉率
double pm = 0.0; //变异率
struct individual //定义染色体个体结构体
{
int chrom[chromlength]; //定义染色体二进制表达形式,edit by ppme 将char 转为 int
double value; //染色体的值
double fitness; //染色体的适应值
};
int generation; //当前执行的世代数
int best_index; //最好的染色体索引序号
int worst_index; //最差的染色体索引序号
struct individual bestindividual; //最佳染色体个体
struct individual worstindividual; //最差染色体个体
struct individual currentbest; //当前最好的染色体个体 currentbest
struct individual population[POPSIZE];//种群数组
//函数声明
void generateinitialpopulation(); //ok-初始化当代种群
void generatenextpopulation(); //??产生下一代种群
void evaluatepopulation(); //评价种群
void calculateobjectfitness(); //计算种群适应度
//long decodechromosome(char *,int,int);//染色体解码
double decodechromosome(int,int); //染色体解码
void findbestandworstindividual(); //寻找最好的和最坏的染色体个体
void performevolution(); //进行演变进化
void selectoperator(); //选择操作
void crossoveroperator(); //交换操作
void mutationoperator(); //变异操作
void input(); //输入接口
void outputtextreport(); //输出文字报告
void main() //主函数
{
int i;
srand((unsigned)time(NULL)); //强制类型转化,以当前时间戳定义随机数种子
printf("本程序为求函数y=x*x的最大值\n");
generation=0; //初始化generation当前执行的代
input(); //初始化种群大小、交叉率、变异率
/*edit by ppme*/
//调试用。。。。。显示input()结果
printf("popsize %d;maxgeneration %d;pc %f;pm %f\n\n",popsize,maxgeneration,pc,pm);
/*edit by ppme*/
generateinitialpopulation(); //产生初始化种群
evaluatepopulation(); //评价当前种群,(A.计算种群/个体的适应度;B.找出最好和最差的个体)
while(generation
{
generation++;
generatenextpopulation(); //生成子代种群(A.选择; B.交叉; C.变异)
evaluatepopulation(); //评价新生子代种群
performevolution(); //进行子代进化
outputtextreport(); //输入当代最终种群
}
printf("\n");
printf(" 统计结果: ");
printf("\n");
printf("最大函数值等于:%f\n",currentbest.fitness);
printf("其染色体编码为:");
//计算currentbest的value
for( i = 0 ; i < chromlength ; i++ )
printf(" %d",currentbest.chrom[i]);
}
void gen