#include <stdio.h> #include <math.h> #define MAX_ITER 100000 // 最大迭代次数 #define TOL 1e-6 // 收敛精度 double f(double x, double y) { return 100 * pow(y - x * x, 2) + pow(1 - x, 2); } int main() { double x = 0, y = 0, tmp_x, tmp_y, fx, fy, diff, max_diff; int iter = 0; do { max_diff = 0; fx = f(x, y); fy = f(x, y); tmp_x = x; tmp_y = y; // 坐标轮换 x = (1 - sqrt(5)) / 2 * y; y = (1 - sqrt(5)) / 2 * tmp_x; diff = fabs(fx - f(x, y)); if (diff > max_diff) { max_diff = diff; } diff = fabs(fy - f(x, y)); if (diff > max_diff) { max_diff = diff; } iter++; } while (max_diff >= TOL && iter < MAX_ITER); printf("Minimum value of f(x,y) = %.6f\n", f(x, y)); printf("Optimal solution: x = %.6f, y = %.6f\n", x, y); return 0; }注释一下
时间: 2023-12-16 17:04:54 浏览: 90
C标准库函数集
5星 · 资源好评率100%
以下是对代码的注释:
```c
#include <stdio.h>
#include <math.h>
#define MAX_ITER 100000 // 最大迭代次数
#define TOL 1e-6 // 收敛精度
// 目标函数
double f(double x, double y) {
return 100 * pow(y - x * x, 2) + pow(1 - x, 2);
}
int main() {
double x = 0, y = 0, tmp_x, tmp_y, fx, fy, diff, max_diff;
int iter = 0;
do {
max_diff = 0;
fx = f(x, y); // 保存当前点的函数值
fy = f(x, y); // 保存当前点的函数值
tmp_x = x; // 保存当前x坐标
tmp_y = y; // 保存当前y坐标
// 坐标轮换
x = (1 - sqrt(5)) / 2 * y; // 优化x坐标
y = (1 - sqrt(5)) / 2 * tmp_x; // 优化y坐标
// 计算当前点与上一次迭代点的函数值之差,并更新最大差值
diff = fabs(fx - f(x, y));
if (diff > max_diff) {
max_diff = diff;
}
diff = fabs(fy - f(x, y));
if (diff > max_diff) {
max_diff = diff;
}
iter++; // 迭代次数加1
} while (max_diff >= TOL && iter < MAX_ITER); // 当最大差值小于收敛精度或达到最大迭代次数时停止迭代
// 输出最小值和最优解
printf("Minimum value of f(x,y) = %.6f\n", f(x, y));
printf("Optimal solution: x = %.6f, y = %.6f\n", x, y);
return 0;
}
```
阅读全文