利用查分进化算法,分别求解下列函数的最大值以及对应的x和y值,设定求解精度为15位小数。函数f(x)=(6.452*(x+0.125y)*(cos(x)-cos(2y)^2))/(0.8+(x-4.2)^2+2(y-7)^2))^0.5+3.226y,x∈[0,10),y∈[0,10),c++代码
时间: 2023-10-08 08:09:30 浏览: 82
函数优化示例-智能计算之遗传算法
以下是使用差分进化算法求解函数最大值及对应的x和y值的C++代码:
```c++
#include <iostream>
#include <cstdio>
#include <cmath>
#include <ctime>
#include <cstdlib>
using namespace std;
const int MAXN = 100;
const double eps = 1e-15;
double f(double x, double y) {
return sqrt(6.452 * (x + 0.125 * y) * (cos(x) - pow(cos(2 * y), 2)) / (0.8 + pow(x - 4.2, 2) + 2 * pow(y - 7, 2))) + 3.226 * y;
}
double rand01() {
return (double) rand() / RAND_MAX;
}
double rand_range(double a, double b) {
return a + rand01() * (b - a);
}
void de(double (*f)(double, double), double &ans, double &x, double &y) {
srand(time(NULL));
double fmax = -1e100;
double pop[MAXN][2];
double pop_new[MAXN][2];
for (int i = 0; i < MAXN; i++) {
pop[i][0] = rand_range(0, 10);
pop[i][1] = rand_range(0, 10);
double fval = f(pop[i][0], pop[i][1]);
if (fval > fmax) {
fmax = fval;
ans = fval;
x = pop[i][0];
y = pop[i][1];
}
}
double F = 0.8;
double CR = 0.9;
int G = 1000;
for (int g = 1; g <= G; g++) {
for (int i = 0; i < MAXN; i++) {
int a, b, c;
do {
a = rand() % MAXN;
} while (a == i);
do {
b = rand() % MAXN;
} while (b == i || b == a);
do {
c = rand() % MAXN;
} while (c == i || c == a || c == b);
int R = rand() % 2;
for (int j = 0; j < 2; j++) {
if (rand01() < CR || j == R) {
pop_new[i][j] = pop[a][j] + F * (pop[b][j] - pop[c][j]);
if (pop_new[i][j] < 0) {
pop_new[i][j] = 0;
}
if (pop_new[i][j] > 10) {
pop_new[i][j] = 10;
}
} else {
pop_new[i][j] = pop[i][j];
}
}
double f_new = f(pop_new[i][0], pop_new[i][1]);
if (f_new > fmax) {
fmax = f_new;
ans = f_new;
x = pop_new[i][0];
y = pop_new[i][1];
}
if (f_new > f(pop[i][0], pop[i][1])) {
pop[i][0] = pop_new[i][0];
pop[i][1] = pop_new[i][1];
}
}
}
}
int main() {
double ans, x, y;
de(f, ans, x, y);
printf("ans = %.15f, x = %.15f, y = %.15f\n", ans, x, y);
return 0;
}
```
其中,`de` 函数是差分进化算法的实现,`f` 函数是待求解的函数,`rand01` 函数用于生成0到1之间的随机数,`rand_range` 函数用于生成指定区间内的随机数。
在主函数中,首先调用 `de` 函数求解最大值及对应的x和y值,然后输出结果。其中, `MAXN` 定义了种群大小, `eps` 定义了求解精度, `F` 和 `CR` 分别表示缩放因子和交叉概率, `G` 表示迭代次数。
阅读全文