牛顿拉普森方法--当循环不取消的时候。

问题描述 投票:0回答:1

我正试图编程一个牛顿拉普森算法来寻找一个函数的根。为了有足够的精度,我输入了一个区间 "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循环并没有取消,而是一直持续下去。希望有人能帮我解决这个问题。

loops while-loop conditional-statements root infinite
1个回答
0
投票

你在 while 循环中重新初始化了 eps(为 double)。所以,在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;


}
© www.soinside.com 2019 - 2024. All rights reserved.