C语言实现差分进化算法求z(i,j)=-20exp((0.2sqrt((x(i)^2+y(j)^2)/2)))-exp((cos(2pix(i))+cos(2piy(j)))/2)+exp(1);的最小值,x属于-5到5,y属于-5到5
时间: 2023-10-04 22:12:16 浏览: 165
c代码-求ax平方+bx+c+=0
5星 · 资源好评率100%
差分进化算法是一种全局优化算法,可以用于求解非线性优化问题。下面是C语言实现差分进化算法求解z(i,j)=-20exp((0.2sqrt((x(i)^2+y(j)^2)/2)))-exp((cos(2pix(i))+cos(2piy(j)))/2)+exp(1);的最小值,x属于-5到5,y属于-5到5的代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#define NP 50 // 种群规模
#define F 0.7 // 缩放因子
#define CR 0.5 // 交叉概率
#define MAX_GENERATION 1000 // 最大迭代次数
#define EPSILON 1e-6 // 收敛精度
double randDouble(double a, double b) {
return a + (b - a) * rand() / (RAND_MAX + 1.0);
}
double z(double x, double y) {
return -20 * exp(-0.2 * sqrt(0.5 * (x * x + y * y))) - exp(0.5 * (cos(2 * M_PI * x) + cos(2 * M_PI * y))) + exp(1);
}
void init(double (*pop)[2]) {
for (int i = 0; i < NP; ++i) {
pop[i][0] = randDouble(-5, 5);
pop[i][1] = randDouble(-5, 5);
}
}
void mutate(double (*pop)[2], int r, double (*trial)[2]) {
int a, b, c;
do {
a = rand() % NP;
} while (a == r);
do {
b = rand() % NP;
} while (b == r || b == a);
do {
c = rand() % NP;
} while (c == r || c == a || c == b);
for (int j = 0; j < 2; ++j) {
trial[r][j] = pop[a][j] + F * (pop[b][j] - pop[c][j]);
}
}
void crossover(double (*pop)[2], int r, double (*trial)[2]) {
int j_rand = rand() % 2;
for (int j = 0; j < 2; ++j) {
if (randDouble(0, 1) < CR || j == j_rand) {
trial[r][j] = pop[r][j];
}
}
}
void select(double (*pop)[2], double (*trial)[2]) {
for (int i = 0; i < NP; ++i) {
double f = z(trial[i][0], trial[i][1]);
double f_old = z(pop[i][0], pop[i][1]);
if (f < f_old) {
pop[i][0] = trial[i][0];
pop[i][1] = trial[i][1];
}
}
}
int main() {
srand(time(NULL));
double pop[NP][2];
double trial[NP][2];
init(pop);
for (int gen = 0; gen < MAX_GENERATION; ++gen) {
for (int i = 0; i < NP; ++i) {
mutate(pop, i, trial);
crossover(pop, i, trial);
}
select(pop, trial);
double f_best = z(pop[0][0], pop[0][1]);
for (int i = 1; i < NP; ++i) {
double f = z(pop[i][0], pop[i][1]);
if (f < f_best) {
f_best = f;
}
}
printf("generation: %d, best: %.6f\n", gen, f_best);
if (f_best < EPSILON) {
printf("converged!\n");
break;
}
}
printf("x: %.6f, y: %.6f, z: %.6f\n", pop[0][0], pop[0][1], z(pop[0][0], pop[0][1]));
}
```
在该代码中,init函数用于初始化种群,mutate函数用于进行变异操作,crossover函数用于进行交叉操作,select函数用于选择操作。在主函数中,我们反复进行变异、交叉和选择操作,直到满足收敛精度或达到最大迭代次数为止。最终,输出最优解以及对应的函数值。
阅读全文