牛顿下山法

来源:互联网 发布:ubuntu 14.04 安装教程 编辑:程序博客网 时间:2024/04/30 19:41

牛顿法来源于泰勒展开式,牛顿法的几何意义为斜率不断地接近零点,所以简单的代码如下

#include<stdio.h>         //牛顿下山#include<math.h>#define f(x) (pow(x,3)-x-1)#define ff(x) (pow((x+1),(1.0/3)))int main(){    int i,k,n=500,m=50;    double x0,x,e=0.000001;    printf("x0=");scanf("%lf",&x0);    double r=1;    while(ff(x0))    {        x=x0-r*f(x0)/ff(x0);        if(f(x)<f(x0))        {            k=0;            while(k<=n)        {   x=x0-r*f(x0)/ff(x0);            if(fabs(x-x0)<e){            printf("根为:%lf\tr=%lf\n",x,r);            return 0;}            else {                x0=x;                printf("x%d=%lf\n",k,x);        }   k++;    }        }    else {            i=0;            if(i>m)            printf("r error\n");            else{                i++;r*=0.5;            }        }    }    printf("ff(x) error\n");    return 0;}

这里写图片描述

0 0