Skip to content

Instantly share code, notes, and snippets.

@martinus
Created September 22, 2014 07:53
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martinus/7434625df79d820cd4d9 to your computer and use it in GitHub Desktop.
Save martinus/7434625df79d820cd4d9 to your computer and use it in GitHub Desktop.
Differential Evolution - Sample Code
/* Example adapted from http://www.drdobbs.com/database/differential-evolution/184410166
*
* This implements the DE/rand/1/bin optimization algorithm.
*
*/
/* Initialize individuals */
for (i=0; i<NP; i++) {
/* randomly initialize all individuals */
for (j=0; j<D; j++) {
currentPos[i][j] = rnd_uni()*(maxPos[j] - minPos[j]) + minPos[j];
}
cost[i] = evaluate(currentPos[i]);
}
/* Halt after gen_max generations. */
while (count < gen_max) {
/* Start loop through population. */
for (i=0; i<NP; i++) {
/********** Mutate/recombine **********/
/* Randomly pick 3 vectors, all different from i */
do a = rnd_uni()*NP; while (a==i);
do b = rnd_uni()*NP; while (b==i || b==a);
do c = rnd_uni()*NP; while (c==i || c==a || c==b);
/* Randomly pick an index for forced evolution change */
k = rnd_uni()*D;
/* Load D parameters into trialPos[]. */
for (j=0; j<D; j++) {
/* Perform D-1 binomial trials. */
if (rnd_uni() < CR || j==k) {
/* Source for trialPos[j] is a random vector plus weighted differential */
trialPos[j] = currentPos[c][j] + F * (currentPos[a][j] - currentPos[b][j]);
} else {
/* or trialPos parameter comes from currentPos[i][j] itself. */
trialPos[j] = currentPos[i][j];
}
}
/********** Evaluate/select **********/
/* Evaluate trialPos with your function. */
score = evaluate(trialPos);
/* If trialPos[] improves on currentPos[i][], move trialPos[] to personalBestPos and store improved cost */
if (score <= cost[i]) {
for (j=0; j<D; j++) {
personalBestPos[i][j] = trialPos[j];
}
cost[i] = score;
} else {
/* otherwise, move currentPos[i][] to secondary array. */
for (j=0; j<D; j++) {
personalBestPos[i][j] = currentPos[i][j];
}
}
}
/********** End of population loop; swap arrays **********/
for (i=0; i<NP; i++) {
/* After each generation, move secondary array into primary array. */
for (j=0; j<D; j++) {
currentPos[i][j] = personalBestPos[i][j];
}
}
count++;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment