通过简单的例子来认识和实践牛顿法

时间:2021-05-26 14:17:44

牛顿法认识与实践

中文参考:[1]

数学定义与推导

通过简单的例子来认识和实践牛顿法
通过简单的例子来认识和实践牛顿法

举例说明

利用牛顿法来近似求解正数平方根
英文教学材料:[2]

#include <iostream>
#include <math.h>
using namespace std;

int LOOP_COUNTER = 0;
// Square Roots by Newton's Method, differ from sqrt in math.h
double nsqrt(double x, double epsilon=0.0001)
{
    double approximate = 1;
    while(fabs(approximate*approximate-x)>epsilon){
        LOOP_COUNTER++;
        approximate = (x/approximate + approximate)/2;
    }
    return approximate;
}

int main()
{
    double n=1;
    while(n>0){
        cin>>n;
        cout<<n<<" square root is "<<nsqrt(n);
        cout<<". Loop times:"<<LOOP_COUNTER<<endl;
        LOOP_COUNTER = 0;
    }
    return 0;
}