不动点迭代法 一元非线性方程求根 C语言实现
标签:计算方法实验
/*本实验用迭代法求方程f(x) = e^(-x) - x + 1的根。
*/
#include <stdio.h>
#include <math.h>#define maxrept 1000 //最大迭代次数double fa(double x){ //迭代函数fa(x)return exp(-x) + 1;
}int main(){double x1, d;double x0 = 100; //迭代初值x0double eps = 0.0005; //求解精度epsint k = 0; //迭代次数do{k++;x1 = fa(x0);printf("%d %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 iteration is failed!\n"); //要求迭代公式收敛,否则会出现溢出return 0;
}
实验结果: