栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++遗传算法类文件实例分析

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++遗传算法类文件实例分析

本文所述为C++实现的遗传算法的类文件实例。一般来说遗传算法可以解决许多问题,希望本文所述的C++遗传算法类文件,可帮助你解决更多问题,并且代码中为了便于读者更好的理解,而加入了丰富的注释内容,是新手学习遗传算法不可多得的参考代码。

具体代码如下所示:

#include "stdafx.h"
#include
#include
#include
#include
#include//把日期和时间转换为字符串
using namespace std;
//Parametes setting    
#define POPSIZE 200   //population size 
#define MAXGENS 1000  //max number of generation 
#define NVARS 2     //no of problem variables 
#define PXOVER  0.75 //probalility of crossover 
#define PMUTATION 0.15 //probalility of mutation 
#define TRUE 1
#define FALSE 0
#define LBOUND 0    
#define UBOUND 12   
#define STOP 0.001
int generation;     //current generation no
int cur_best;      //best individual
double diff;      
FILE *galog;      //an output file
struct genotype
{
   double gene[NVARS];   //a string of variables基因变量
   double upper[NVARS];  //individual's variables upper bound 基因变量取值上确界
   double lower[NVARS];  //individual's batiables lower bound 基因变量取值下确界
   double fitness;     //individual's fitness个体适应值
   double rfitness;    //relative fitness个体适应值占种群适应值比例
   double cfitness;    //curmulation fitness个体适应值的累加比例
 };
struct genotype population[POPSIZE+1]; 
//population 当前种群 population[POPSIZE]用于存放个体最优值并假设最优个体能存活下去
//在某些遗传算法中最优值个体并不一定能够存活下去
struct genotype newpopulation[POPSIZE+1]; //new population replaces the old generation 子种群
 
 void initialize(void);   //初始化函数
 double randval(double,double);      //随机函数
 double funtion(double x1,double x2);  //目标函数
 void evaluate(void);   //评价函数
 void keep_the_best(void); //保留最优个体
 void elitist(void);     //当前种群与子代种群最优值比较
 void select(void);
 void crossover(void);   //基因重组函数
 void swap(double *,double *);      //交换函数
 void mutate(void);     //基因突变函数
 double report(void);   //数据记录函数
void initialize(void)
 {
  int i,j;
   for(i=0;iworst)
     {
worst=population[i].fitness;
      worst_mem=i;
    }  
   }
  if(best<=population[POPSIZE].fitness)//赋值
   {
    for(i=0;i=population[j].cfitness&&p1)
  {
     if(NVARS==2)
      point=1;
    else
      point=(rand()%(NVARS-1))+1;//两个都重组吗?
    for(i=0;i=STOP);
   //fprintf(galog,"nn Simulation completedn");
   //fprintf(galog,"n Best member:n");
   printf("nBest member:ngeneration:%dn",generation);
   for(i=0;i

感兴趣的读者可以动手测试一下代码,希望对大家学习C++算法能有所帮助。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/65603.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号