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

📄 ga_enhangced1225.c

📁 求解两个变量的优化程序
💻 C
📖 第 1 页 / 共 2 页
字号:
/*  .C -- liqiang's projects*/

#include "stdio.h"
#include "conio.h"
#include "stdlib.h"
#include "time.h"
#include "math.h"
#include "graphics.h"
#define closegr closegraph

void initgr(void) /* BGI初始化 */
{
  int gd = DETECT, gm = 0; /* 和gd = VGA,gm = VGAHI是同样效果 */
  registerbgidriver(EGAVGA_driver);/* 注册BGI驱动后可以不需要.BGI文件的支持运行 */
  initgraph(&gd, &gm, "");
}

/************************************************************
*           Define Constants                                *
************************************************************/
#define POPSIZE 100         /*size of the one population*/
#define MAXIMIZATION 1      /*optimum mode*/
#define MINIMIZATION 2

#define Cmax    10          /*two constants related to fitness calculation*/
#define Cmin    0


/************************************************************
*           Define global variables                         *
************************************************************/

/*------THESE THREE CHANGES WHENEVER NUMBER CHANGES----------*/
#define NUMBER 2
#define CHROMLENGTH 12+12
int Length[NUMBER]={12,12};

double X_optimal[NUMBER];                        /*the optimal value of variables*/
double x_max[NUMBER]={2.048,2.048};              /*the maximal value of variables*/
double x_min[NUMBER]={-2.048,-2.048};            /*the minimal value of variables*/
/*-----------------------------------------------------------*/

int FunctionMode=MAXIMIZATION;
int MaxGeneration   =200;       /*the maximal loops of compution*/
double Pc           =0.6;       /*probality of crossover*/
double Pm           =0.001;     /*probality of mutation*/



/************************************************************
*           Define structures and logs                      *
************************************************************/
struct individual
{
    char chrom[CHROMLENGTH+1];  /*a string of code representing individual*/
    double value;               /*object value of individual*/
    double fitness;             /*fitness value of individual*/
};

int generation;                 /*number of generation*/
int best_index;                 /*index of best individual*/
int worst_index;                /*index of worst individual*/
struct individual bestIndividual;       /*best individual of current generation*/
struct individual worstIndividual;      /*worst individual of current generation*/
struct individual currentBest;          /*best individual so far*/
struct individual population[POPSIZE];  /*all population*/

struct log                  /*chain used to record every new generation's best individual*/
{
    int generation;         /*current generation*/
    double info[NUMBER];    /*variables of current generation*/
    double value;           /*object value of current generation*/
    struct log *next;
}*recordLog,*head,*end;     /*define a chain recordLog to record the optimal value of each generation*/
int log_length;             /*length of chain log*/
/************************************************************
*           Declaration of Function                         *
************************************************************/
double function(double x[NUMBER])
{
    int i;
    double y=0;
    y=100*(x[0]*x[0]-x[1])*(x[0]*x[0]-x[1])+(1-x[0])*(1-x[0]);
    /*y=x[0]*x[0]+x[1]*x[1]+x[2]*x[2];*/
    /*y=x[0]*(x[0]+4);*/
    /*y=(4-2.1*x[0]*x[0]+pow(x[0],4)/3.0)*x[0]*x[0]+x[0]*x[1]+(-4+4*x[1]*x[1])*x[1]*x[1];*/
    return y;
}
/************************************************************
*           Declaration of Prototype                        *
************************************************************/
void GenerateInitialPopulation(void);
void GenerateNextPopulation(void);
void EvaluatePopulation(void);
long DecodeChromosome(char * ,int ,int );
void CalculateObjectValue(void);
void CalculateFitnessValue(void);
void FindBestAndWorstIndividual(void);
void PerformEvolution(void);
void SelectionOperator(void);
void CrossoverOperator(void);
void MutationOperator(void);
void OutputTextReport(void);
void writeToFile(void);
void drawLine(void);

void bin2grad(char grad[],char bin[]);
void grad2bin(char bin[],char grad[]);

/************************************************************
*     Function: the Main Function.                          *
*     Variables:    None.                                   *
************************************************************/
void main(void)
{
    struct tm *local;
    /*=============================================================*/

    /*the place you can define variables*/

    /*the end of the place you can define variables*/
    /*---------------------------------------------------*/

    time_t tm;
    tm=time(NULL);
    local=localtime(&tm);
    printf("Local time and data:%s\n",asctime(local));

    /*--------------------------------------------------*/

    /*the place you can edit*/
    generation=0;
    GenerateInitialPopulation();
    EvaluatePopulation();
    while(generation<MaxGeneration)
    {
        generation++;
        GenerateNextPopulation();
        EvaluatePopulation();
        PerformEvolution();
        OutputTextReport();
    }
    writeToFile();
    /*the end of the place you can edit*/
    /*--------------------------------------------------*/

    /*=============================================================*/
    printf("\n");
    printf("************************************************** \n");
    printf("*                                                * \n");
    printf("*       This  job  is  done  by  li qiang        * \n");
    printf("*                                                * \n");
    printf("************************************************** \n");

    getch();

    /*================draw the convergence process================*/
    drawLine();

}
/************************************************************
*     Function: Generate the first population.              *
*     Variables:    None.                                   *
************************************************************/
void GenerateInitialPopulation(void)
{
    int i,j;
    randomize();
    for(i=0;i<POPSIZE;i++)
    {   for(j=0;j<CHROMLENGTH;j++)
            population[i].chrom[j]=(random(10)<5)?'0':'1'; /*initialize chromosome as a series composed of '0'and'1'only*/
        population[i].chrom[CHROMLENGTH]='\0';
    }
}
/************************************************************
*     Function: Initialize the first population.            *
*     Variables:    None.                                   *
************************************************************/
void GenerateNextPopulation(void)
{
    SelectionOperator();
    CrossoverOperator();
    MutationOperator();
}
/************************************************************
*     Function: Evaluate population according to            *
*               certain formula.                            *
*     Variables:    None.                                   *
************************************************************/
void EvaluatePopulation(void)
{
    CalculateObjectValue();
    CalculateFitnessValue();
    FindBestAndWorstIndividual();
}
/************************************************************
*     Function: Decode a binary into a decimal integer.     *
*     Variables:    None.                                   *
************************************************************/
long DecodeChromosome(char *string,int point,int length)
{
    int i;
    long decimal=0L;
    char *pointer;

    for(i=0,pointer=string+point;i<length;i++,pointer++)
        decimal+=(*pointer-'0')<<(length-1-i);

    return (decimal);
}
/************************************************************
*     Function: Calculate the object value.                 *
*     Variables:    None.                                   *
*     Note:                                                 *
*     f(x1,x2)=100*(x1**2-x2)**2+(1-x1)**2;                 *
*     Its maximal value is:                                 *
*     f(-2.048,-2.048)=3905.926227                          *
************************************************************/
void CalculateObjectValue(void)
{
    int i,j;
    long temp[NUMBER];
    double x[NUMBER];

    /*RosenBrock Function*/
    for(i=0;i<POPSIZE;i++)
    {
        temp[0]=DecodeChromosome(population[i].chrom,0,Length[0]);
        x[0]=(x_max[0]-x_min[0])*temp[0]/((pow(2,Length[0])-1.0))-(x_max[0]-x_min[0])/2.0;
        for(j=1;j<NUMBER;j++)
        {    temp[j]=DecodeChromosome(population[i].chrom,Length[j-1],Length[j]);
             x[j]=(x_max[j]-x_min[j])*temp[j]/((pow(2,Length[j])-1.0))-(x_max[j]-x_min[j])/2.0;
        }
        population[i].value=function(x);
    }
}
/************************************************************
*     Function: Calculate the fitness value.                *
*     Variables:    None.                                   *
************************************************************/
void CalculateFitnessValue(void)
{
    int i;
    double temp;

    for(i=0;i<POPSIZE;i++)
    {
        if(FunctionMode==MAXIMIZATION)
        {
            if((population[i].value+Cmin)>0.0)
                temp=Cmin+population[i].value;
            else
                temp=0.0;
        }
        else if(FunctionMode==MINIMIZATION)
        {
            if(population[i].value<Cmax)
                temp=Cmax-population[i].value;
            else
                temp=0.0;
        }
        population[i].fitness=temp;
    }
}

⌨️ 快捷键说明

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