⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 gasԴ

📁 利用简单遗传算法求解一元函数优化问题:
💻
字号:
/************************************************************************************
*                               Simple Genetic Algorithm                           *
*                                                                                  *
*                                      Version 1.0                                 *
*                                                                                  *
*                               Programmed by Rui GUO    1/7,2006                  *
*********************************************************************************A*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
/**********************************************************************************
*                          The definition of constant                             *
*                                                                                 *
********************************************************************************B*/
#define POPSIZE 30       
#define PI 3.1415926      //pi的大小
/**********************************************************************************
*                       THE DEFINATION OF USER DATA                               *
*                                                                                 *
********************************************************************************C*/
#define Cmax 10                //最大评价
#define Cmin 0                 //最小
#define LENGTH1 22             //染色体长度           
int PopSize=30;                //种群规模
int MaxGeneration=150;         //最大迭代次数=150
double Pc=0.8;                 //交叉概率 交叉率=0.8
double Pm=0.05;                //变异概率 变异率=0.05
/*要求用使用基本遗传算法,遗传算法参数:染色体长度=22*/
/**********************************************************************************
*                       THE DEFINATION OF DATA STRUCTURE                          *
*                                                                                 *
********************************************************************************D*/
struct individual{
	char chrom[LENGTH1+1];  //染色体
	double value;          //函数值
	double fitness;        //适应度 
};
/**********************************************************************************
*                       THE DEFINATION OF GLOBLE VARIABLES                        *
*                                                                                 *
********************************************************************************E*/
int generation;                                //代数
int best_index;//最好的位置
int worst_index;//最坏的位置 
struct individual bestindividual;//最好个体
struct individual worstindividual;//最坏个体
struct individual currentbest;//当前最好
struct individual population[POPSIZE];//种群 
/**********************************************************************************
*                     DECLARATION OF PROTOTYPE                                    *
*                                                                                 *
********************************************************************************F*/
void GenerateInitialPopulation(void);
void GenerateNextPopulation(void);
void EvaluatePopulation(void);
double DecodeChromosome(char *,int,int);
void CalulateObjectValue(void);
void CalulateFitnessValue(void);
void FindBestAndWorstIndividual(void);
void PerformEvolution(void);
void SelectionOperator(void);
void Crossoverperator(void);
void MutationOperator(void);
void OutputTextReport(void);
/**********************************************************************************
*                    main progrom                                                 *
*                    Variable: None                                               *
*                    Note:                                                        *

********************************************************************************01*/
void main(void){
	char c;
	printf("***************************************************************************\n");
	printf("一元函数优化优化问题:MAX f(x)=x*sin(10*PI*x)+2.0\n");
	printf("		交叉概率:     0.8\n		变异概率:     0.05\n		种群规模:     30\n");
	printf("		染色体长度:   22\n		最大迭代次数: 150");	
	printf("\n***************************************************************************\n");
	printf("按'N'退出,按其余键继续:");
    scanf("%c",&c);
	if(c=='N'||c=='n')
	{   printf("程序退出\n");
		exit;
	
	}
	else
	{  	generation=0;
		GenerateInitialPopulation();//种群初始化
		EvaluatePopulation();//评价函数 
		while(generation<MaxGeneration)
		{
		generation++;
		GenerateNextPopulation();//生成下一代
		EvaluatePopulation();//评价函数
		PerformEvolution();//表现型
		OutputTextReport();//输出
		}
	}
   //OutputTextReport();//输出//////////////////////////////////////////////
}

/**********************************************************************************
*                    Function: generate the first population                      *
*                    Variable: None                                               *
*                    Note:                                                        *
********************************************************************************02*/
void GenerateInitialPopulation(void){
int i,j,temp;
time_t t;
for(i=0;i<PopSize;i++){
    for(j=0;j<LENGTH1;j++){
        srand( time(&t) );
        temp=rand()%9;//得到随机数
	    population[i].chrom[j]=(temp<5)?'0':'1';
	//	printf("%c",population[i].chrom[j]);//输出值,以便于函数调整
	}
population[i].chrom[LENGTH1]='\0';
//printf("\n%d\n",population[i].chrom);
}
}
/**********************************************************************************
*                    Function: initial the next generation                        *
*                    Variable: None                                               *
*                    Note:                                                        *
********************************************************************************03*/
void GenerateNextPopulation(void){
 SelectionOperator();//选择运算
 Crossoverperator();//交叉运算
 MutationOperator();//变异运算
}
/**********************************************************************************
*              Function: evalution population according to certain formula        *
*              Variable: None                                                     *
*              Note:                                                              *
********************************************************************************04*/
void EvaluatePopulation(void){//评价函数
 CalulateObjectValue();//计算目标函数值
 CalulateFitnessValue();//计算适应度
 FindBestAndWorstIndividual();//最好和最差变量
}
/**********************************************************************************
*              Function: To decode a binary chromosome into adecimal integer      *
*              Variable: None                                                     *
*              Note: 关键,有疑问????????????                         *
********************************************************************************05*/
double DecodeChromosome(char *string,int point,int length){
	int i;
	double decimal=0L;//二进制解码
	char *pointer;
	for(i=0,pointer=string+point;i<length;i++,pointer++){
		decimal+=(*pointer-'0')<<(length-1-i);
	//	printf("(%d) ",decimal);
	}
	return(decimal);
}
/**********************************************************************************
*              Function: To caclculate object value                               *
*              Variable: None                                                     *
*              Note:                                                              *
********************************************************************************06*/
void CalulateObjectValue(void){
	int i;
	double temp1;
	double x1;
	//Rosenbrock function
	for(i=0;i<PopSize;i++){
		temp1=DecodeChromosome(population[i].chrom,0,LENGTH1);//解码  
    	//printf("(%d,",temp1);
		x1=temp1/(1024.0*1024.0*4.0)+1;   //计算表现型 		
		//printf("_%f_ ",x1);
		population[i].value=x1*sin(10*PI*x1)+2.0;//计算函数值
        //printf("|%f| ",population[i].value);
	}
}
/**********************************************************************************
*              Function: To caclculate fitness value                              *
*              Variable: None                                                     *
*              Note:                                                              *
********************************************************************************07*/
void CalulateFitnessValue(void){
	int i;
	double temp;

	for(i=0;i<PopSize;i++)
		population[i].fitness=population[i].value;//直接将函数值作为适应度
	
    
}
/**********************************************************************************
*              Function: To find out the best individual so farcurrent            *
*                        generation                                               *
*              Variable: None                                                     *
*              Note:                                                              *
********************************************************************************08*/
void FindBestAndWorstIndividual(void){
	int i;
	double sum=0.0;

	bestindividual=population[0];
    worstindividual=population[0];

	for(i=1;i<=PopSize;i++){
		if(population[i].fitness>bestindividual.fitness){
			bestindividual=population[i];
			best_index=i;
		}
		else
			if(population[i].fitness<worstindividual.fitness){
              worstindividual=population[i];
			  worst_index=i;
			}
			sum+=population[i].fitness;
	}

	if(generation==0){
		currentbest=bestindividual;
	}
	else{
		if(bestindividual.fitness>currentbest.fitness){
            currentbest=bestindividual;}
	}
}
/**********************************************************************************
*              Function: To perform evolution operation based on elitise model    *
*                        Elitist modest is to replace the worst indivadual of     *
*                        this generation by the current best one                  *
*              Variable: None                                                     *
*              Note:                                                              *
********************************************************************************09*/
void PerformEvolution(void){
	if(bestindividual.fitness>currentbest.fitness){
		currentbest=population[best_index];//最好
	}
	else {
		population[worst_index]=currentbest;//最坏
	}
}
/**********************************************************************************
*              Function: To reproduce a chromosome by proportional selection      *
*              Variable: None                                                     *
*              Note:                                                              *
********************************************************************************10*/
void SelectionOperator(void){
	int i,index;
	double p,sum=0.0;
	double cfitness[POPSIZE];
	struct individual newpopulation[POPSIZE];
	for(i=0;i<PopSize;i++){sum+=population[i].fitness;}
	for(i=0;i<PopSize;i++){cfitness[i]=population[i].fitness/sum;}
	for(i=1;i<PopSize;i++){cfitness[i]=cfitness[i-1]+cfitness[i];}
	for(i=0;i<PopSize;i++){
		p=rand()%1000/1000.0;
		index=0;
		while(p>cfitness[index]){index++;}
		newpopulation[i]=population[index];
	}
	for(i=0;i<PopSize;i++){population[i]=newpopulation[i];
	}
}
/**************************************************************************************
*              Function: Crossover two chromosome by means of one_point crossover     *
               Variable: None                                                         *
*              Note:                                                                  *
************************************************************************************11*/

void Crossoverperator(void){
	int i,j;
	int index[POPSIZE];
	int point,temp;
	double p;
	char ch;

	for(i=0;i<PopSize;i++){index[i]=i;}
  
	
    for(i=0;i<PopSize;i++){
		point=rand()%(PopSize-i);
		temp=index[i];
		index[i]=index[point+i];
		index[point+i]=temp;	
	}

	for(i=0;i<PopSize-1;i+=2){
		p=rand()%1000/1000.0;
		if(p<Pc){
			point=rand()%(LENGTH1-1)+1;
			for(j=point;j<LENGTH1;j++){
				ch=population[index[i]].chrom[j];
                population[index[i]].chrom[j]=population[index[i+1]].chrom[j];
				population[index[i+1]].chrom[j]=ch; 
			}
		}
	}
}
/**************************************************************************************
*              Function: Mutation of a chromosome                                     *    
               Variable: None                                                         *
*              Note:                                                                  *
************************************************************************************12*/

void MutationOperator(void){
	int i,j;
	double p;

	for(i=0;i<PopSize;i++){
		for(j=0;j<LENGTH1;j++){
			p=rand()%1000/1000.0;
			if(p<Pm){
				population[i].chrom[j]=(population[i].chrom[j]=='0')?'1':'0';
			}
		
		}
	}
}
/**************************************************************************************
*              Function: Output the results of current population                     *
               Variable: None                                                         *
*              Note:                                                                  *
************************************************************************************13*/
void OutputTextReport(void){
	int i;
	double sum;
	double XBest;
	double average;

	sum=0.0;
	for(i=0;i<PopSize;i++){
		sum+=population[i].value;
	}
	average=sum/PopSize;
    printf("\n***************************************************************************\n");
	printf("迭代次数=%d		平均值是=%f		最佳个体是=%f",generation,average,currentbest.value);
	printf("\n            编码为:");
	for(i=0;i<LENGTH1;i++){
		printf("%c",currentbest.chrom[i]);
	}
    XBest=DecodeChromosome(currentbest.chrom,0,LENGTH1)/(1024.0*1024.0*4.0)+1.0;
    printf("\nx的值是:%f\n",XBest);
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -