计算方法之牛顿迭代法求方程根

来源:互联网 发布:淘宝助手5.7 编辑:程序博客网 时间:2024/05/22 02:25
/************************************** 用牛顿迭代法求非线性方程* f(x)=x-e^(-x)=0* 在区间[0,1]的根,取ξ=10^(-5),x0 = 0.5**************************************/#include<stdio.h>#include<math.h>#include<conio.h>#define maxrept 1000float 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);elseprintf("the iterate id failed\n");return 0;}

原创粉丝点击