牛顿迭代法c语言aun
时间: 2023-07-02 21:19:45 浏览: 50
以下是使用C语言实现牛顿迭代法求解函数f(x)=0的代码示例:
```c
#include <stdio.h>
#include <math.h>
// 定义待求解的函数
double f(double x) {
return x * x - 2; // 求解根号2的平方
}
// 定义f(x)的导数
double df(double x) {
return 2 * x;
}
int main() {
double x0, x1, eps;
int max_iter, iter;
// 输入初始值、精度和最大迭代次数
printf("Enter initial guess, accuracy and maximum iterations: ");
scanf("%lf %lf %d", &x0, &eps, &max_iter);
// 迭代求解
iter = 0;
do {
x1 = x0 - f(x0) / df(x0);
printf("Iteration %d: x = %.8f\n", iter, x1);
iter++;
if (fabs(x1 - x0) < eps) {
printf("Convergence achieved: x = %.8f\n", x1);
return 0;
}
x0 = x1;
} while (iter < max_iter);
printf("Maximum number of iterations reached: x = %.8f\n", x1);
return 0;
}
```
该程序的运行结果如下:
```
Enter initial guess, accuracy and maximum iterations: 1.0 0.00001 10
Iteration 0: x = 1.50000000
Iteration 1: x = 1.41666667
Iteration 2: x = 1.41421569
Iteration 3: x = 1.41421356
Convergence achieved: x = 1.41421356
```
其中,初始值为1.0,精度为0.00001,最大迭代次数为10。程序通过迭代求出f(x)=x^2-2=0的解x=1.41421356,满足精度要求。