using System;
namespace PSO
{
class Program
{
static int N =100;
int min = -10;
int max = 10;
double v_max = 5;
double v_min = -5;
double w = 0.5;
double c1 = 2;
double c2 = 2;
Random r = new Random();
double[,] particle = new double[N,2];
double[,] current_v = new double[N,2];
double[,] pBest = new double[N, 2];
double[] gBest = new double[2];
double[] current_Fitness = new double[N];
double[] particle_local_best_Fitness = new double[N];
double particle_global_Fitness;
public void Initial()
{
int i, j;
for (i = 0; i < N; i++)
{
for (j = 0; j < 2; j++)
{
particle[i, j] = -min + (max - min) * r.NextDouble();
pBest[i, j] = particle[i, j];
current_v[i, j] = v_min + 2 * v_max * r.NextDouble();
}
}
for (i = 0; i < N; i++)
{
current_Fitness[i] = Fitness(particle[i, 0], particle[i, 1]);
particle_local_best_Fitness[i] = current_Fitness[i];
}
particle_global_Fitness = particle_local_best_Fitness[0];
j = 0;
for (i = 0; i < N; i++)
{
if (particle_local_best_Fitness[i] < particle_global_Fitness)
{
particle_global_Fitness = particle_local_best_Fitness[i];
j = i;
}
}
for (i = 0; i < 2; i++)
{
gBest[i] = pBest[j, i];
}
Console.WriteLine("初始化粒子完成!");
Console.WriteLine("正在进行迭代...");
}
public void Renew_location()
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < 2; j++)
{
double r1 = r.NextDouble();
double r2 = r.NextDouble();
current_v[i, j] += (w * current_v[i, j] + c1 * r1 * (pBest[i, j] - particle[i, j]) +
c2 * r2 * (gBest[j] - particle[i, j]));
particle[i, j] += current_v[i, j];
if (particle[i, j] > max)
{
particle[i, j] = max;
}
if (particle[i, j] < min)
{
particle[i, j] = min;
}
}
}
}
static double Fitness(double x1, double x2)
{
return Math.Pow(x1, 2.0) + Math.Pow(x2, 2.0);
}
public void Renew_Fitness()
{
int j = -1;
for (int i = 0; i < N; i++)
{
if (Fitness(particle[i, 0], particle[0, 1]) < current_Fitness[i])
{
pBest[i, 0] = particle[i, 0];
pBest[i, 1] = particle[i, 1];
}
particle_local_best_Fitness[i] = Fitness(pBest[i, 0], pBest[i, 1]);
if (particle_local_best_Fitness[i] < particle_global_Fitness)
{
particle_global_Fitness = particle_local_best_Fitness[i];
j = i;
}
}
}
static void Main(string[] args)
{
Program PSO = new Program();
PSO.Initial();
for (int i = 0; i < 10000; i++)
{
PSO.Renew_location();
PSO.Renew_Fitness();
}
Console.WriteLine("迭代完成,最小值y={0}", PSO.particle_global_Fitness);
Console.ReadLine();
}
}
}