Newton Raphson 方法 - While 循环不会取消

Newton Raphson method - While loop doesnt cancel

我正在尝试编写 Newton Raphson 算法来查找函数的根。为了有足够的精度,我输入了一个区间"eps",这样只有误差小于"eps"才会给出根。初始x-起点被我设置为1.5.

double func(double x) {

    return x * x * x - 4 * x + 1;
}

double funcprime(double x) {

    return 3 * x * x - 4;
}

int main()
{
    double x_start = 1.5;
    double x0= x_start - ((func(x_start)) / (funcprime(x_start)));
    double eps = abs(x_start - x0);


    while (eps > 0.000001) {

        x0 = x_start - ((func(x_start)) / (funcprime(x_start)));

        double eps = abs(x_start - x0);

        //Following line is there to analyze the problem
        cout << "x0= " << x0 <<" " << "x_start= " << x_start << " "<< "eps= " << eps << endl;

        x_start = x0;                       
    }

    cout << x0;

    return 0;

}

我遇到的问题在于 while 循环。虽然在大约 4 次迭代后,eps 已经小于 0.000001,甚至显示为 eps=0,但 while 循环不会取消并永远继续。我希望有人能帮助我。

您正在 while 循环内重新初始化 eps(作为双精度)。因此,在 while 循环中删除 eps = abs(x_start - x0) 之前的 double。

更正后的代码:

double func(double x) {

    return x * x * x - 4 * x + 1;
}

double funcprime(double x) {

    return 3 * x * x - 4;
}

int main()
{
    double x_start = 1.5;
    double x0= x_start - ((func(x_start)) / (funcprime(x_start)));
    double eps = abs(x_start - x0);


    while (eps > 0.000001) {

        x0 = x_start - ((func(x_start)) / (funcprime(x_start)));

        eps = abs(x_start - x0);  // double removed here

        //Following line is there to analyze the problem
        cout << "x0= " << x0 <<" " << "x_start= " << x_start << " "<< "eps= " << eps << endl;

        x_start = x0;                       
    }

    cout << x0;

    return 0;


}