http://blog.csdn.net/blesh/article/details/21180695 有全部的測試函數(shù)的C代碼
http://wenku.baidu.com/link?url=dXPZ4HOwqTE1URtlXFOTD4ojwRsUVWaYZROgYdE15OQApswr2MIxuE7LAwrQcTCThd6Dzw70T2ichDK1uMsBBdRS9XYypzdSAZFZzk6uMjO
超簡潔的隨機粒子群算法(PSO)程序(C/C++)
2014-03-13 17:33 827人閱讀 評論(0) 收藏 舉報#include"stdio.h"
#include"stdlib.h"
#include"time.h"
#include"math.h"
const int NUM=40;//粒子數(shù)
const int DIM=30;//維數(shù)
const double c1=1.8;//參數(shù)
const double c2=1.8;//參數(shù)
double xmin=-100.0;//位置下限
double xmax=100.0;//位置上限
double gbestx[DIM];//全局最優(yōu)位置
double gbestf;//全局最優(yōu)適應(yīng)度
struct particle {//定義一個粒子
double x[DIM];//當(dāng)前位置矢量
double bestx[DIM];//歷史最優(yōu)位置
double f;//當(dāng)前適應(yīng)度
double bestf;//歷史最優(yōu)適應(yīng)度
}swarm[NUM];//定義粒子群
#define randf ((rand()%10000+rand()%10000*10000)/100000000.0) //產(chǎn)生-1隨機浮點數(shù)
double f1(double x[]) {//測試函數(shù):超球函數(shù)
float z=0;
for(int i=0;i<DIM;i++)
z+=(x[i])*(x[i]);
return z;
}
void main() {
for(int i=0; i<DIM; i++)//初始化全局最優(yōu)
gbestx[i]=randf*(xmax-xmin)+xmin;
gbestf=100000000000000.0;
for(int i=0; i<NUM; i++) {//初始化粒子群
particle* p1=&swarm[i];
for(int j=0; j<DIM; j++)
p1->x[j]=randf*(xmax-xmin)+xmin;
p1->f=f1(p1->x);
p1->bestf=100000000000000.0;
}
for(int t=0; t<5000; t++) {
for(int i=0; i<NUM; i++) {
particle* p1=&swarm[i];
for(int j=0; j<DIM; j++)//進化方程
p1->x[j]+=c1*randf*(p1->bestx[j]-p1->x[j])
+c2*randf*(gbestx[j]-p1->x[j]);
p1->f=f1(p1->x);
if(p1->f<p1->bestf) {//改變歷史最優(yōu)
for(int j=0;j<DIM;j++)
p1->bestx[j]=p1->x[j];
p1->bestf=p1->f;
}
if(p1->f<gbestf) {//改變?nèi)肿顑?yōu)
for(int j=0;j<DIM;j++)
gbestx[j]=p1->x[j];
for(int j=0; j<DIM; j++)//把當(dāng)前全局最優(yōu)的粒子隨機放到另一位置
p1->x[j]=randf*(xmax-xmin)+xmin;
gbestf=p1->f;
}
}
}
PRintf("%g/n", gbestf);
}