牛顿迭代法应用——求数的平方根和立方根

牛顿迭代法。从一个值開始。用无限逼近的方式得出结果。

#include<stdio.h>
#include<math.h>

int main()
{
    double a;
    double x;
    scanf("%lf",&a);//求a的平方根和立方根
    x = a/2;

    ////平方根/////
    while( fabs(x*x-a) > (1e-6) )
    {
        x = (x+a/x)/2;
    }
    printf("%lf\n",x);

    /////立方根////////////////
    x=1;//从1開始。当然也能够从其它数開始
    while(fabs(x*x*x-a) > (1e-6) )
    {
        x = (2*x +a/(x*x))/3;
    }
    printf("%lf\n",x);

    return 0;
}
posted @ 2016-04-11 16:14  yxwkaifa  阅读(445)  评论(0编辑  收藏  举报