📄 ga.cpp
字号:
#include<iostream>
#include<math.h>
using namespace std;
const int MAXGENE=20;
const int MAXPOPSIZE=500;
const int EPOCH=50;
const double Pc=0.7;
const double Pm=0.1;
double OptFun(double x,double y)
{
//return 100*(x*x-y)*(x*x-y)+(1-x)*(1-x);
return x*x;
}
class Chormosome
{
public:
int Gene[MAXGENE];
double Fitness;
void CalculateFitness();
Chormosome()
{
for(int i=0;i<MAXGENE;i++)
Gene[i]=rand()%2;
}
};
void Chormosome::CalculateFitness()
{
double x=0,y=0;
for(int i=0;i<MAXGENE/2;i++)
{
x=x+Gene[i]*pow(2,i);
y=y+Gene[i+MAXGENE/2]*pow(2,i);
}
x=(4*x)/1023-2;
y=(4*y)/1023-2;
/* x=(4.096*x)/1023-2.048;
y=(4.096*y)/1023-2.048;//*/
Fitness=OptFun(x,y);
}
class Population
{
public:
double dbestFitness;
Chormosome chorm[MAXPOPSIZE];
void Selection();
void Crossover();
void Mutation();
void Evolution();//*/
void Inital();
};
void Population::Selection()
{
Chormosome chormtemp[MAXPOPSIZE];
double dFitnessTotal=0,dFitnessFractile[MAXPOPSIZE];
int i;
for(i=0;i<MAXPOPSIZE;i++)
dFitnessTotal+=chorm[i].Fitness;
for(i=0;i<MAXPOPSIZE;i++)
dFitnessFractile[i]=chorm[i].Fitness/dFitnessTotal;
for(i=0;i<MAXPOPSIZE;i++)
{
double p=(double)rand()/RAND_MAX;
double ptemp=0;
for(int j=0;j<MAXPOPSIZE;j++)
{
ptemp+=dFitnessFractile[j];
if(p<ptemp)
{chormtemp[i]=chorm[j];break;}
}
}
for(i=0;i<MAXPOPSIZE;i++)
chorm[i]=chormtemp[i];
}
void Population::Crossover()
{
Chormosome temp;
int i;
for(i=0;i<MAXPOPSIZE;i++)
{
int j=rand()%(MAXPOPSIZE);
temp=chorm[i];chorm[i]=chorm[j];chorm[j]=temp;
}
for(i=0;i<MAXPOPSIZE;i+=2)
{
double p=(double)rand()/RAND_MAX;
if(p<Pc)
{
for(int j=0;j<MAXGENE/2;j++)
{
int inttemp;
inttemp=chorm[i].Gene[j];
chorm[i].Gene[j]=chorm[i+1].Gene[j];
chorm[i+1].Gene[j]=inttemp;
}
}
}
}
void Population::Mutation()
{
int i;
for(i=0;i<MAXPOPSIZE;i++)
{
double p=(double)rand()/RAND_MAX;
if(p<Pm)
{
int Pos=rand()%MAXGENE;
if(chorm[i].Gene[Pos]==0)
chorm[i].Gene[Pos]=1;
else chorm[i].Gene[Pos]=0;
}
}
}
void Population::Evolution()
{
int curgene=0;double dgoalFitness=0;
while(curgene<EPOCH)
{
Population::Selection();
Population::Crossover();
Population::Mutation();
Population::Inital();
curgene++;
if(dgoalFitness<dbestFitness)dgoalFitness=dbestFitness;
cout<<"第"<<curgene<<"代"<<"Fitness:"<<dbestFitness<<endl;
cout<<"全局最好值:"<<dgoalFitness<<endl;
}
}
void Population::Inital()
{
dbestFitness=0;
for(int i=0;i<MAXPOPSIZE;i++)
{
chorm[i].CalculateFitness();
if(dbestFitness<chorm[i].Fitness)
dbestFitness=chorm[i].Fitness;
}
}
void main()
{
Population Pop;
Pop.Evolution();
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -