本文共 756 字,大约阅读时间需要 2 分钟。
/* 本实验用牛顿迭代法求f(x) = x - e^(-x) = 0在区间[0, 1]的根。*/#include#include #define maxrept 1000 //最大迭代次数double f(double x){ //函数f(x) return (x - exp(-x));}double df(double x){ //f(x)的导数 return (1 + exp(-x));}double iterate(double x){ //牛顿迭代函数 return (x - f(x) / df(x));}int main(){ double x1, d; double x0 = 0.5; //迭代初值x0 double eps = 0.00001; //求解精度eps int k = 0; //迭代次数 do{ k++; x1 = iterate(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("\nthe iteration is failed!\n"); return 0;}
实验结果: