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

📄 individual.h

📁 遗传策略的最小路径(tsp)的实际应用
💻 H
字号:
#include <iostream>
#include <fstream>
#include <math.h> 
using namespace std; 

const double pi = 3.1415926; 
const double e  = 2.7182818;
const double MAX_1 =12.1;
const double MIN_1 =-3.0;
const double MAX_2 =5.8;
const double MIN_2 =4.1;
const int POP_SIZE =50;
const int Temp_POP_SIZE = 8*POP_SIZE;

class Individual {

private:

    double X1;     
    double X2;
	double Sigma1;
	double Sigma2;
public:

    void set(double X1,double X2,double Sigma1,double Sigma2) { 
		this->X1 = X1;
	    this->X2 = X2;
        this->Sigma1 =Sigma1;
        this->Sigma2 =Sigma2;
	}
    
    Individual operator =(Individual c) { 
		this->X1 = c.X1; 
		this->X2 = c.X2;
        this->Sigma1 = c.Sigma1;
        this->Sigma2 = c.Sigma2;	
        return *this;
	}


    double FitnessEvaluate() { 

       return X1 * (double)sin(4*pi*X1) + X2 * (double)sin(20*pi*X2)+21.5;  //求F( )的函数值

    }

    void print() {
		ofstream myf("记录.txt",ios::app);

   cout << "\t\tx1 = " <<X1<<"\tx2= "<<X2<<  "\tF(x1,x2) = " << FitnessEvaluate()<<endl;
   myf << "\t\tx1 = " <<X1<<"\tx2= "<<X2<<  "\tF(x1,x2) = " << FitnessEvaluate()<<endl;
	}

    double random()            //产生0-1之间的随机数
  {   
    int   a;   
    double   r;   
    
    a=rand();   
    r=(double)a/RAND_MAX;   
    
    return   r;   
    
  }   

    double  Nrand(double   mu,double  sigma)   //产生正态分布的随机数
  {   
    double   r1,r2;   
    
    r1=random();   
    r2=random();   
    
    return   sqrt(-2*log(r1))*cos(2*pi*r2)*sigma+mu   ;   
    
  }   

   Individual recombination(Individual ind1, Individual ind2)     //对当前个体进行重组的操作
{      Individual temp;
      int n1,n2;
      n1=rand()%2;
	  n2=rand()%2;

	   if  (n1==0)
		   temp.X1=ind1.X1;
	   else 
		   temp.X1=ind2.X1;

        if (n2==0)
		   temp.X2=ind1.X2;
	   else 
		   temp.X2=ind2.X2;
		
		   temp.Sigma1=(ind1.Sigma1+ind2.Sigma1)/2;

	       temp.Sigma2=(ind1.Sigma2+ind2.Sigma2)/2;
				  
        return temp;

}

  Individual mutation()               //对当前个体进行变异的操作 
	{double n=0.08*Nrand(0.0,1.0);
     Sigma1*=pow(e,n+0.06*Nrand(0.0,1.0));  
     if(Sigma1<0.0001)
	 { Sigma1=0.0001;}

	 Sigma2*=pow(e,n+0.03*Nrand(0.0,1.0));
     if(Sigma2<0.0001)
	 { Sigma2=0.0001;}

double temp;
temp=X1;
for(int i=0;i<99;i++)
{
	
    X1+= Nrand(0.0,Sigma1);
	if(X1>MAX_1||X1<MIN_1)
	X1=temp;
	else 
	break;
}
temp=X2;
for(int i=0;i<99;i++)
{
	
    X2+= Nrand(0.0,Sigma2);
	if(X2>MAX_2||X2<MIN_2)
	X2=temp;
	else 
	break;
}

return *this;}
};

⌨️ 快捷键说明

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