1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
| #include<iostream>
#include<cmath>
#include<cstdlib>
#include<cstdio>
#include "data.h"
using namespace std;
#define C1 2
#define C2 2
#define VMAX 5.0
#define Iteration 10000
#define rand1() (double)(rand() / (double)RAND_MAX)
double global_best = 10000.0;
double v[100000] = {0};
const int X_const = 5;
double time_pso = 0.0;
struct particle{
double current;
double personal_best;
};
struct particle p[100000];
double fitness(double x){
return x * x - 20 * x + 100;
}
void init(){
int i;
for(i = 0; i < 100000; i++){
p[i].current = -2 + i;
p[i].personal_best = p[i].current;
v[i] = 0;
}
}
void cpso_sk(){
int iter = 1;
clock_t start, end;
start = clock();
int particle_num = 100000;
int split = 1000;
int count = particle_num / split;
for(int i = 0; i < particle_num; i+=count){
while(iter < Iteration){
for(int j = i; j < count; j++)
if(fitness(p[j].current) < fitness(p[j].personal_best))
p[j].personal_best = p[j].current;
for(int k = i; k < count; k++)
if(fitness(p[k].current) < fitness(global_best))
global_best = p[k].current;
for(int u = i; u < count; u++){
v[u] =X_const * (v[u] + C1 * rand1() * (p[u].personal_best - p[u].current) + C2 * rand1() * (global_best - p[u].current));
if(v[u] > VMAX)
v[u] = VMAX;
}
for(int j = i; j < count; j++)
p[j].current += v[j];
iter++;
}
end = clock();
time_pso = end - start;
}
}
int main(){
init();
cpso_sk();
cout<<"The cpso algorithm use "<<time_pso<<" in the funtion 1 and the global best is "<<global_best;
return 0;
}
|