差分進化アルゴリズムC言語実装
3281 ワード
以前の1篇の中で自分の大学院生の期間C実現の基本粒子群のアルゴリズムを貼って、実行速度は明らかに他の高級言語より速くて、これも各プログラミング言語の間の違いで、今かつて輝かしい差分進化のアルゴリズムに対してC言語の実現を行います.変異戦略はDE/rand/1を採用しており,これは最も一般的である.間違ったところがあればどうぞ.
/***************Differential Evolution Algorithm*************************/
/*
* @Author: Gong Xu
* (c) Copyright 2018 ,DSP Laboratory of Lanzhou University of Technology, All rights reserved.
*
*/
# include
# include
# include
#include
#define nVar 30 // Number of variables
#define nPop 50 // Number of Population
#define Iter 1000 // Maximum number of iterations
struct individual
{
double position[nVar];
double fitness;
};
struct DE
{
struct individual ptcle[nPop];
double F;
double CR;
double(*function)(double *); // Function pointer definition
double global_fitness;
double global_solution[nVar];
double x_low_bound;
double x_up_bound;
};
// sum(X^2)
double function_fitness(double *var)
{
double result = 0;
for (int i = 0; i de.x_up_bound)
{
mutate[i].position[j] = de.x_up_bound;
}
if (mutate[i].position[j] < de.x_low_bound)
{
mutate[i].position[j] = de.x_low_bound;
}
}
}
//crossover
for (int i = 0; i < nPop; i++)
{
int randc = (int)rand() % nVar;
for (int j = 0; j < nVar; j++)
{
double rand_cr = (double)rand() / RAND_MAX;
if ((j == randc) || (rand_cr < de.CR))
{
cross[i].position[j] = mutate[i].position[j];
}
else
{
cross[i].position[j] = de.ptcle[i].position[j];
}
// limit of variables of bound
if (cross[i].position[j] > de.x_up_bound)
{
cross[i].position[j] = de.x_up_bound;
}
if (cross[i].position[j] < de.x_low_bound)
{
cross[i].position[j] = de.x_low_bound;
}
}
cross[i].fitness = de.function(cross[i].position);
}
// select
for (int i = 0; i < nPop; i++)
{
if (cross[i].fitness < de.ptcle[i].fitness)
{
de.ptcle[i].fitness = cross[i].fitness;
memcpy(&de.ptcle[i].position, &cross[i].position, sizeof(double)*nVar);
if (de.ptcle[i].fitness