#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdlib>
#include<ctime>
#include<random>
using namespace std;
//----------参数设置------------
#define Max 200;
constexpr auto N = 3;//种群大小
constexpr auto T = 200;//迭代次数
double w = 0.5;//惯量权重
double c1 = 2.0;//加速系数
double c2 = 2.0;//加速系数
double r1, r2;//速度更新公式的随机参数
double favorite;//记录适应函数的最优结果
int flag;//标记位置
double pBest[N][2];//历史最优位置
double gBest[2];//全局最优位置
//--------------------------------
default_random_engine e(time(NULL));
uniform_int_distribution<int> random1(-10, 10);
uniform_int_distribution<int> random2(-4, 4);
uniform_real_distribution<double> random3(0, 1);
class particle {
public:
particle() {//初始化粒子的随机速度和位置
X[0] = random1(e);
X[1] = random1(e);
V[0] = random2(e);
V[1] = random2(e);
}
double* getV() {//获得粒子速度
return V;
}
double* getX() {//获得粒子位置
return X;
}
void setV(double v1, double v2) {
V[0] = v1;
V[1] = v2;
}
void setX(double x1, double x2) {
X[0] = x1;
X[1] = x2;
}
private:
double V[2];//粒子速度
double X[2];//粒子位置
};
//适应函数
double function(particle &p) {
return (p.getX()[0])*(p.getX()[0])+ (p.getX()[1])*(p.getX()[1]);
}
int main(void)
{
int count=T;
particle p[N];//定义种群
//定义粒子历史最优位置的适应函数值并初始化
double s[N];
for (int i = 0; i < N; i++)
{
s[i] = Max;
}
do{
//------------判断历史最优位置-----------
for (int i = 0; i < N; i++)
{
if (s[i] > function(p[i])) {
s[i] = function(p[i]);
pBest[i][0] = p[i].getX()[0];
pBest[i][1] = p[i].getX()[1];
}
}
//-----------判断全局最优位置------------
double favorite = s[0];
flag = 0;
for (int i = 0; i < N; i++)
{
if (favorite > s[i]) {
favorite = s[i];
flag = i;
}
}
gBest[0] = pBest[flag][0];
gBest[1] = pBest[flag][1];
//-------------输出结果------------------
/* for (int i = 0; i < N; i++)
{
cout << "p" << i + 1 << "的位置" << endl;
cout << p[i].getX()[0] << " " << p[i].getX()[1] << " " << function(p[i]) << endl;
}
for (int i = 0; i < N; i++)
{
cout << "p" << i + 1 << "的历史最优位置" << endl;
cout << pBest[i][0] << " " << pBest[i][1] << " " << s[i] << endl;
}*/
cout <<"第"<<T-count+1<< "次迭代"<<'\t';
cout << gBest[0] <<'\t'<< gBest[1] <<'\t'<< favorite << endl;
//------------粒子速度与位置的更新------------
for (int i = 0; i < N; i++)
{
double v[2], x[2];
r1 = random3(e);//0到1之间的随机数
r2 = random3(e);
for (int j = 0; j < 2; j++)
{
v[j] = w * p[i].getV()[j] + c1 * r1*(pBest[i][j] - p[i].getX()[j]) + c2 * r2*(gBest[j] - p[i].getX()[j]);
x[j] = p[i].getX()[j] + v[j];
if (x[j] > 10) {//位置越界判断
x[j] = 10;
}
}
p[i].setV(v[0], v[1]);
p[i].setX(x[0], x[1]);
}
count--;
} while (count);
return 0;
}