用c语言编程黄金搜值法求f(x)=x*x-4*x+4在[0,4]之间的最小值,直接·给出完整代码
时间: 2024-02-22 18:57:42 浏览: 142
好的,以下是用C语言编写的黄金分割法求解$f(x)=x^2-4x+4$在区间 $[0,4]$ 上的最小值的完整代码:
```c
#include <stdio.h>
#include <math.h>
#define R 0.618 // 黄金分割点
double f(double x) {
return x * x - 4 * x + 4;
}
double golden_section(double left, double right, double epsilon) {
double x1, x2, y1, y2;
x1 = left + (1 - R) * (right - left);
x2 = left + R * (right - left);
y1 = f(x1);
y2 = f(x2);
while (fabs(right - left) > epsilon) {
if (y1 < y2) {
right = x2;
x2 = x1;
y2 = y1;
x1 = left + (1 - R) * (right - left);
y1 = f(x1);
} else {
left = x1;
x1 = x2;
y1 = y2;
x2 = left + R * (right - left);
y2 = f(x2);
}
}
return (left + right) / 2;
}
int main() {
double left = 0, right = 4, epsilon = 1e-5;
double x = golden_section(left, right, epsilon);
printf("The minimum value of f(x) is %.5lf at x = %.5lf\n", f(x), x);
return 0;
}
```
在上述代码中,`f(x)` 函数用来计算函数值,`golden_section` 函数是黄金分割法的具体实现,`main` 函数用于测试。其中,`left` 和 `right` 分别表示区间左右端点,`epsilon` 表示精度,可以根据需要进行调整。程序输出的结果为最小值及其对应的 $x$ 值。
阅读全文