牛顿迭代法 一元非线性方程求根 C语言实现

来源:互联网 发布:mac常用办公软件 编辑:程序博客网 时间:2024/04/30 03:19

牛顿迭代法 一元非线性方程求根 C语言实现

标签:计算方法实验

/*    本实验用牛顿迭代法求f(x) = x - e^(-x) = 0在区间[0, 1]的根。*/#include <stdio.h>#include <math.h>#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;}

实验结果:
output