/*************************************
* 用牛顿迭代法求非线性方程
* f(x)=x-e^(-x)=0
* 在区间[0,1]的根,取ξ=10^(-5),x0 = 0.5
**************************************/
#include<stdio.h>
#include<math.h>
#include<conio.h>
#define maxrept 1000
float f(float x) {
return x - exp(-x);
}
float df(float x) {
return 1 + exp(-x);
}
float iterate(float x) {
float x1;
x1 = x - f(x) / df(x);
return x1;
}
int main() {
float x0, x1, eps, d;
int k = 0;
printf("\nplease input x0 =");
scanf("%f", &x0);
printf("\nplease input eps =");
scanf("%f", &eps);
printf("\n\tk\tx0\n");
printf("\n\t%d\t%f\n", k, x0);
do {
k++;
x1 = iterate(x0);
printf("\n\t%d\t%f\n", k, x1);
d = fabs(x1 - x0);
x0 = x1;
} while ((d >= eps) && (k < maxrept));
if (k < maxrept)
printf("the root of f(x)=0 is x=%f,k=%d\n", x1, k);
else
printf("the iterate id failed\n");
return 0;
}
计算方法之牛顿迭代法求方程根
最新推荐文章于 2022-05-18 22:59:05 发布