遗传算法解决二次函数问题
![遗传算法解决二次函数问题](https://img.360docs.net/imgde/1pxvsst8ncuxa3fgzqmgw4g2m0fpmiab-e1.webp)
![遗传算法解决二次函数问题](https://img.360docs.net/imgde/1pxvsst8ncuxa3fgzqmgw4g2m0fpmiab-12.webp)
<遗传算法>技术文档
问题:
利用遗传算法求解区间[0, 31]上的二次函数y=x2的最大值
VS2005 C++ 环境
C++面向对象的思想设计遗传算法
1、各参数变量的说明
(1)short bitString; //个体的二进制编码(2)short fitness; //个体的适应度
(3)static const short bitCount = 5; //个体二进制码的长度
(4)static const short popuScale = 10; //种群规模
(5)#define CROSS_MUTATE_PRO_COMP 100 //交叉、变异的基数
(6)static const short pc = 40; //交叉个体数相对于基数
(7)static const short pm = 5; //变异个体数相对于基数
(8)Individual popuArray[popuScale]; //种群(9)short gen = 0; //种群进化的代数
2、遗传操作的设计思想
分别设计了一个个体类、种群类,种群由个体组成,这是类库设计,对用户来说,分别使用这两个类来实现遗传算法,其中选择中采用轮盘赌来选择下一代。
(1)、个体类设计如下:
#ifndef __INDIVIDUAL_H__
#define __INDIVIDUAL_H__
#include
class Individual
{
private:
short bitString; //个体的二进制编码
short fitness; //个体的适应度
public:
static const short bitCount = 5; //个体二进制码的长度
Individual();
Individual(short n);
Individual(short bitStr,int fit);
~Individual();
short GetFitness() const;
short GetBitString()const;
//void setBitString();
//void setFitness();
bool operator>(const Individual & indi)const;
bool operator==(const Individual & indi)const;
friend std::ostream & operator<< (std::ostream & os, const Individual & indi);
void ShowIndividual(void)const;
};
#endif
(2)种群类设计如下:
#ifndef __POPULATION_H__
#define __POPULATION_H__
#include"individual.h"
#define CROSS_MUTATE_PRO_COMP 100 //交叉、变异的基数
class Population
{
public:
static const short popuScale = 10; //种群规模
private:
static const short pc = 40; //交叉个体数相对于基数
static const short pm = 5; //变异个体数相对于基数
Individual popuArray[popuScale];
public:
Population();
void Selection(); //选择
void Crossover(); //交叉
void Mutation(); //变异
const Individual & GetbestIndividual()const;
const Individual & GetRepresatationIndividual()const;
friend std::ostream & operator<<(std::ostream &os, const Population & p);
void ShowPopulation()const;
~Population();
};
#endif
(3)用户区程序代码(遗传算法实现):
#include
#include"individual.h"
#include"population.h"
void GA(void);
int main()
{
GA();
}
void GA(void)
{
std::cout<<"Please enter how many generations you want the population to evolve!"< short gen = 0; //种群进化的代数 std::cin>>gen; Population birds; for(int i = 0; i < gen; i++) { std::cout<<"the "<< i << "th generation :"<< std::endl; std::cout< birds.Selection(); std::cout<<"after selection the population is : "<< std::endl; std::cout< birds.Crossover(); std::cout<<"after crossover the population is :" << std::endl; std::cout< birds.Mutation(); std::cout<<"after mutation the population is :" << std::endl; std::cout< std::cout< } std::cout<<"After "<< gen << " evolution the best fitness Individual bird is :"< std::cout< std::cout<<"After "<< gen << " evolution the represetational Individual bird is :"< std::cout< } 3、程序流程图 4、程序执行结果 当gen种群的代数取得越大,取到最优解的概率就越大,在一般情况下,基本上能取到最大解,x = 31,在有的情况下,求不到最优解,但向最优解靠近。