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

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

具体代码如下所示:

#include "stdafx.h"
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<ctime>//把日期和时间转换为字符串
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 子种群
 /*Declaration of procedures used by the gentic algorithm*/
 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;i<NVARS;i++)
   {
    for(j=0;j<POPSIZE+1;j++)
    {
       if(!i)
       {
        population[j].fitness=0;
        population[j].rfitness=0;
        population[j].cfitness=0;
       }
      population[j].lower[i]=LBOUND;
      population[j].upper[i]=UBOUND;
      population[j].gene[i]=randval(population[j].lower[i],population[j].upper[i]);
     }
   }
 }
//***************************************************************************
//Random value generator:generates a value within bounds
//***************************************************************************
 double randval(double low,double high)
 {
   double val;
   val=((double)(rand()%10000)/10000)*(high-low)+low;
  return val;
 }
//目标函数
 double funtion(double x,double y)
{
  double result1=sqrt(x*x+y*y)+sqrt((x-12)*(x-12)+y*y)+sqrt((x-8)*(x-8)+(y-6)*(y-6));
  return result1;
}
 //***************************************************************************
 //Evaluation function:evaluate the individual's fitness.评价函数给出个体适应值
//Each time the function is changes,the code has to be recompl
 //***************************************************************************
 void evaluate(void)
 {
  int mem;
  int i;
  double x[NVARS];
  for(mem=0;mem<POPSIZE;mem++)
   {

    for(i=0;i<NVARS;i++)
    x[i]=population[mem].gene[i];
    population[mem].fitness=funtion(x[0],x[1]);//将目标函数值作为适应值
  }
 }
 //***************************************************************************************
 //Keep_the_best function:This function keeps track of the best member of the population.
//找出种群中的个体最优值并将其移动到最后
//***************************************************************************************
 void keep_the_best()
 {
   int mem;
   int i;
   cur_best=0;
   for(mem=0;mem<POPSIZE;mem++)//找出最高适应值个体
  {
     if(population[mem].fitness<population[cur_best].fitness)
     {
       cur_best=mem;
    }
  }
  //将最优个体复制至population[POSIZE]
   if(population[cur_best].fitness<=population[POPSIZE].fitness||population[POPSIZE].fitness<1)//防止出现种群基因退化 故保留历史最优个体
  {
    population[POPSIZE].fitness=population[cur_best].fitness;
    for(i=0;i<NVARS;i++)
    population[POPSIZE].gene[i]=population[cur_best].gene[i];
  }
}
 //***************************************************************************
 //last in the array.If the best individual from the new populatin is better
//than the best individual from the previous population ,then copy the best
 //from the new population;else replace the worst individual from the current
 //population with the best one from the previous generation.防止种群最优值退化
//***************************************************************************
 void elitist()
{
   int i;
  double best,worst;//适应值
  int best_mem,worst_mem;//序号
  best_mem=worst_mem=0;
  best=population[best_mem].fitness;//最高适应值初始化
  worst=population[worst_mem].fitness;//最低适应值初始化
  for(i=1;i<POPSIZE;i++)//找出最高和最低适应值 算法有待改进
   {
     if(population[i].fitness<best)
     {
       best=population[i].fitness;
      best_mem=i;
     }
    if(population[i].fitness>worst)
     {
       worst=population[i].fitness;
      worst_mem=i;
    }
   }
  if(best<=population[POPSIZE].fitness)//赋值
   {
    for(i=0;i<NVARS;i++)
       population[POPSIZE].gene[i]=population[best_mem].gene[i];
    population[POPSIZE].fitness=population[best_mem].fitness;
   }
   else
  {
     for(i=0;i<NVARS;i++)
       population[worst_mem].gene[i]=population[POPSIZE].gene[i];
     population[worst_mem].fitness=population[POPSIZE].fitness;
   }
}
 //***************************************************************************
 //Select function:Standard proportional selection for maximization problems
//incorporating elitist model--makes sure that the best member survives.筛选函数并产生子代
//***************************************************************************
 void select(void)
 {
   int mem,i,j;
   double sum=0;
   double p;
   for(mem=0;mem<POPSIZE;mem++)//所有适应值求和
  {
     sum+=population[mem].fitness;
   }
   for(mem=0;mem<POPSIZE;mem++)
   {
    population[mem].rfitness=population[mem].fitness/sum;//个人认为还不如建一个种群类 把sum看成类成员
  }
  population[0].cfitness=population[0].rfitness;
  for(mem=1;mem<POPSIZE;mem++)
  {
    population[mem].cfitness=population[mem-1].cfitness+population[mem].rfitness;
  }
   for(i=0;i<POPSIZE;i++)
  {
     p=rand()%1000/1000.0;
     if(p<population[0].cfitness)
    {
       newpopulation[i]=population[0];
     }
     else
    {
      for(j=0;j<POPSIZE;j++)
         if(p>=population[j].cfitness&&p<population[j+1].cfitness)
           newpopulation[i]=population[j+1];
     }
   }
   for(i=0;i<POPSIZE;i++)//子代变父代
     population[i]=newpopulation[i];
}
//***************************************************************************
 //Crossover:performs crossover of the selected parents.
 //***************************************************************************
void Xover(int one,int two)//基因重组函数
{
   int i;
  int point;
  if(NVARS>1)
  {
     if(NVARS==2)
      point=1;
    else
      point=(rand()%(NVARS-1))+1;//两个都重组吗?
    for(i=0;i<point;i++)//只有第一个基因发生重组有待改进
      swap(&population[one].gene[i],&population[two].gene[i]);
   }
 }
//***************************************************************************
//Swapp: a swap procedure the helps in swappling 2 variables
//***************************************************************************
 void swap(double *x,double *y)
 {
  double temp;
  temp=*x;
  *x=*y;
  *y=temp;
}
 //***************************************************************************
 //Crossover function:select two parents that take part in the crossover.
 //Implements a single point corssover.杂交函数
 //***************************************************************************
void crossover(void)
 {
   int mem,one;
   int first=0;
   double x;
  for(mem=0;mem<POPSIZE;++mem)
  {
    x=rand()%1000/1000.0;
    if(x<PXOVER)
     {
       ++first;
      if(first%2==0)//选择杂交的个体对 杂交有待改进 事实上往往是强者与强者杂交 这里没有考虑雌雄与杂交对象的选择
        Xover(one,mem);
      else
         one=mem;
 }
  }
 }
//***************************************************************************
 //Mutation function:Random uniform mutation.a variable selected for mutation
 //变异函数 事实基因的变异往往具有某种局部性
 //is replaced by a random value between lower and upper bounds of the variables.
 //***************************************************************************
 void mutate(void)
 {
   int i,j;
   double lbound,hbound;
   double x;
   for(i=0;i<POPSIZE;i++)
     for(j=0;j<NVARS;j++)
     {
       x=rand()%1000/1000.0;
       if(x<PMUTATION)
      {
         lbound=population[i].lower[j];
         hbound=population[i].upper[j];
         population[i].gene[j]=randval(lbound,hbound);
       }
     }
 }
//***************************************************************************
 //Report function:Reports progress of the simulation.
 //***************************************************************************
 double report(void)
 {
  int i;
  double best_val;//种群内最优适应值
  double avg;//平均个体适应值
   //double stddev;
  double sum_square;//种群内个体适应值平方和
  //double square_sum;
  double sum;//种群适应值
  sum=0.0;
  sum_square=0.0;
  for(i=0;i<POPSIZE;i++)
   {
     sum+=population[i].fitness;
     sum_square+=population[i].fitness*population[i].fitness;
   }
  avg=sum/(double)POPSIZE;
   //square_sum=avg*avg*(double)POPSIZE;
   //stddev=sqrt((sum_square-square_sum)/(POPSIZE-1));
  best_val=population[POPSIZE].fitness;
  fprintf(galog,"%6d %6.3f %6.3f %6.3f %6.3f %6.3f\n",generation,best_val,population[POPSIZE].gene[0],population[POPSIZE].gene[1],avg,sum);
  return avg;
 }
 //***************************************************************************
//main function:Each generation involves selecting the best members,performing
 //crossover & mutation and then evaluating the resulting population,until the
//terminating condition is satisfied.
 //***************************************************************************
 void main(void)
 {
   int i;
   double temp;
   double temp1;
   if((galog=fopen("data.txt","w"))==NULL)
  {
    exit(1);
   }
  generation=1;
  srand(time(NULL));//产生随机数
  fprintf(galog,"number value  x1   x2   avg   sum_value\n");
  printf("generation best average standard\n");
  initialize();
  evaluate();
  keep_the_best();
  temp=report();//记录,暂存上一代个体平均适应值
   do
   {
     select();//筛选
     crossover();//杂交
     mutate();//变异
     evaluate();//评价
     keep_the_best();//elitist();
     temp1=report();
     diff=fabs(temp-temp1);//求浮点数x的绝对值
     temp=temp1;
     generation++;
   }while(generation<MAXGENS&&diff>=STOP);
   //fprintf(galog,"\n\n Simulation completed\n");
   //fprintf(galog,"\n Best member:\n");
   printf("\nBest member:\ngeneration:%d\n",generation);
   for(i=0;i<NVARS;i++)
   {
     //fprintf(galog,"\n var(%d)=%3.3f",i,population[POPSIZE].gene[i]);
     printf("X%d=%3.3f\n",i,population[POPSIZE].gene[i]);
   }
   //fprintf(galog,"\n\n Best fitness=%3.3f",population[POPSIZE].fitness);
   fclose(galog);
   printf("\nBest fitness=%3.3f\n",population[POPSIZE].fitness);
 }

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

(0)

相关推荐

  • 深入理解Java遗传算法

    关于遗传算法的详细原理以及具体的定义这里就不多介绍,想了解的可以自行百度,下面就简单介绍下自己对遗传算法的理解,本文对基因的编码采用二进制规则. 算法思想:       遗传算法参照达尔文的进化论,认为物种都是向好的方向去发展(适者生存),因此可以认为到足够的代数之后,得到的最值可实际的最值很接近. 算法步骤: 1)随机产生一个种群: 2)计算种群的适应度.最好适应度.最差适应度.平均适应度等指标: 3)验证种群代数是否达到自己设置的阈值,如果达到结束计算,否则继续下一步计算: 4)采用转盘赌法

  • C++实现遗传算法

    本文实例讲述了C++实现简单遗传算法.分享给大家供大家参考.具体实现方法如下: // CMVSOGA.h : main header file for the CMVSOGA.cpp //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// #if !defined(AFX_CMV

  • java实现遗传算法实例分享(打印城市信息)

    复制代码 代码如下: import java.util.*;public class Tsp {      private String cityName[]={"北京","上海","天津","重庆","哈尔滨","长春","沈阳","呼和浩特","石家庄","太原","济南","

  • C++实现简单遗传算法

    本文实例讲述了C++实现简单遗传算法.分享给大家供大家参考.具体实现方法如下: //遗传算法 GA #include<iostream> #include <cstdlib> #include<bitset> using namespace std; const int L=5; //定义编码的长度 int f(int x) //定义测设函数f(x) { int result; result=x*x*x-60*x*x+900*x+100; return result;

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

    本文所述为C++实现的遗传算法的类文件实例.一般来说遗传算法可以解决许多问题,希望本文所述的C++遗传算法类文件,可帮助你解决更多问题,并且代码中为了便于读者更好的理解,而加入了丰富的注释内容,是新手学习遗传算法不可多得的参考代码. 具体代码如下所示: #include "stdafx.h" #include<iostream> #include<cstdio> #include<cstdlib> #include<cmath> #inc

  • Java高效读取大文件实例分析

    1.概述 本教程将演示如何用Java高效地读取大文件.Java--回归基础. 2.在内存中读取 读取文件行的标准方式是在内存中读取,Guava和ApacheCommonsIO都提供了如下所示快速读取文件行的方法: Files.readLines(new File(path), Charsets.UTF_8); FileUtils.readLines(new File(path)); 这种方法带来的问题是文件的所有行都被存放在内存中,当文件足够大时很快就会导致程序抛出OutOfMemoryErro

  • R语言操作XML文件实例分析

    XML是一种文件格式,它使用标准ASCII文本共享万维网,内部网和其他地方的文件格式和数据. 它代表可扩展标记语言(XML). 类似于HTML它包含标记标签. 但是与HTML中的标记标记描述页面的结构不同,在xml中,标记标记描述了包含在文件中的数据的含义. 您可以使用"XML"包读取R语言中的xml文件. 此软件包可以使用以下命令安装. install.packages("XML") 输入数据 通过将以下数据复制到文本编辑器(如记事本)中来创建XMl文件. 使用.

  • python解析xml文件实例分析

    本文实例讲述了python解析xml文件的方法.分享给大家供大家参考.具体如下: python解析xml非常方便.在dive into python中也有讲解. 如果xml的结构如下: <?xml version="1.0" encoding="utf-8"?> <books> <book> <author>zoer</author> <title>think in java</title

  • Yii框架的布局文件实例分析

    本文实例讲述了Yii框架的布局文件.分享给大家供大家参考,具体如下: 首先,何为布局文件呢?我的理解就是布局存放了视图文件中的相同代码,使用布局文件可以减少视图文件代码的冗余.下面介绍如何使用Yii的布局文件. 首先在views\layouts下面创建自己的布局文件 common.php <!doctype html> <html lang="zh"> <head> <meta charset="UTF-8"> <

  • PHP常用文件操作函数和简单实例分析

    PHP最常用的文件操作就是读取和写入了,今天就主要讲解一下读取和写入函数,并且做一个页面访问的计数功能,来记录一个页面的访问量. fopen():PHP中没有文件创建函数,创建和打开文件都用fopen()函数,函数的形式为:resource fopen( string filename, string mode ) 参数filename为打开或创建并打开的文件名,参数mode为打开的模式,具体模式如下: fread():PHP中可用于读取文件,函数的形式为:string fread( resou

  • PHP文件缓存smarty模板应用实例分析

    本文实例分析了PHP文件缓存smarty模板应用.分享给大家供大家参考,具体如下: 一.使用缓存 要开启smarty的缓存,只需将caching设为true,并指定cache_dir即可. 使用cache_lefetime指定缓存生存时间,单位为秒 要对相同页面生成多个不同的缓存,在display或fetch中加入第二参数cache_id,如: $smarty->display('index.tpl',$my_cache_id); 此特性可用于对不同的$_GET进行不同的缓存   二.清除缓存

  • GO语言文件的创建与打开实例分析

    本文实例分析了GO语言文件的创建与打开用法.分享给大家供大家参考.具体分析如下: 文件操作是个很重要的话题,使用也非常频繁,熟悉如何操作文件是必不可少的.Golang 对文件的支持是在 os package 里,具体操作都封装在 type File struct {} 结构体中. 一.func Open(name string) (file *File, err error) 再简单不过了,给一个路径给它,返回文件描述符,如果出现错误就会返回一个 *PathError. 这是一个只读打开模式,实

  • JSP页面文件中base标记用法实例分析

    本文实例分析了JSP页面文件中base标记用法.分享给大家供大家参考,具体如下: 我们在用IDE工具生成JSP页面时通常都包含下面的两段代码, <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %

  • 可兼容php5与php7的cURL文件上传功能实例分析

    本文实例讲述了可兼容php5与php7的cURL文件上传功能.分享给大家供大家参考,具体如下: 为啥要写这个示例 最近修改一个项目,需要通过cURL上传文件. 记得之前做过类似实现的,于是翻出来之前的代码,使用的是"@"前缀方式. 但同样的方法现在不行了!后来发现,是版本兼容问题. 奔着开源分享的精神,同时避免自己遗忘,于是写了下面的示例程序. 示例程序 特别说明: 共3个文件,都放在web根目录的test目录下,同时保证该目录可写.上传的图片也会保存在该目录. 如果要将程序文件放在其

随机推荐