粒子群算法原理:
https://blog.csdn.net/daaikuaichuan/article/details/81382794
代码||注释||结果
package PSO;
/*
* Target function : F(x, y) = x^2 + y^2;
* Opti Solution is F(0, 0) = 0, Certainly;
*
* According to PSO
*
* v' = w * v + c1 * rand() * (localbest - x) + c2 * rand() * (globalbest - x);
* x' = x + v';
*
* In our case, c1 = c2 = 0;
* w = 0.6;
* rand() ranges from -0.5 to 1.5
*/
class Pos{ //Position
private double posx;
private double posy;
Pos(double x, double y){
posx = x;
posy = y;
}
Pos copy(){
return new Pos(posx, posy);
}
Pos(){
posx = Math.random() * 100 - 50;
posy = Math.random() * 100 - 50;
}
public double getPosx() { return posx; }
public double getPosy() { return posy; }
void UpdatePos(Vec v) {
this.posx += v.getVecx();
this.posy += v.getVecy();
}
}
class Vec{ //speed
private double vecx;
private double vecy;
public Vec() {
vecx = Math.random() * 2 - 1;
vecy = Math.random() * 2 - 1;
}
public double getVecx() {
return vecx;
}
public double getVecy() {
return vecy;
}
void UpdateVec(Pos p, Pos bp, Pos bgp) {
// TODO Auto-generated method stub
double R1 = (Math.random() * 2 - 0.5);
double R2 = (Math.random() * 2 - 0.5);
vecx *= 0.6;
vecy *= 0.6;
vecx += R1 * (bp.getPosx() - p.getPosx()) + R2 * (bgp.getPosx() - p.getPosx());
vecy += R1 * (bp.getPosy() - p.getPosy()) + R2 * (bgp.getPosy() - p.getPosy());
}
}
public class Particle {
Pos pos;
Vec vec;
Pos bpos;
double curscore;
double localbest = Double.MAX_VALUE;
static double globalbest = Double.MAX_VALUE; //'static' makes that the only global best data exists
static Pos globalPos = null; //no matter how many particles there are.
//init
Particle(){
pos = new Pos();
vec = new Vec();
bpos = pos.copy();
globalPos = pos.copy();
curscore = pos.getPosx() * pos.getPosx() + pos.getPosy() * pos.getPosy();
localbest = Math.min(localbest, curscore);
globalbest= Math.min(localbest, curscore);
}
//Prey(鸟群捕食)
void Update() {
// TODO Auto-generated method stub
vec.UpdateVec(pos, bpos, globalPos);
pos.UpdatePos(vec);
//System.out.println("bgPos = " + globalPos.getPosx() + " " + globalPos.getPosy());
//System.out.println("beatscore = " + globalbest);
curscore = pos.getPosx() * pos.getPosx() + pos.getPosy() * pos.getPosy();
if(curscore < localbest) { //Update Local Best Score & Pos
localbest = curscore;
bpos = pos.copy();
}
if(curscore < globalbest) { Update Global Best Score & Pos
globalbest = curscore;
globalPos = pos.copy();
}
}
public static void main(String[] args) {
Particle[] particles = new Particle[100];
for(int i = 0; i < 100; ++i) {
particles[i] = new Particle();
System.out.println(particles[i].curscore);
}
for(int i = 0; i < 1000; i++) {
for(int j = 0; j < 100; j++) {
particles[j].Update();
}
//System.out.println("beatscore = " + globalbest);
}
System.out.println("bgPos = " + globalPos.getPosx() + " " + globalPos.getPosy());
System.out.println("beatscore = " + globalbest);
}
}