【问题标题】:Newton Raphson method - While loop doesnt cancelNewton Raphson 方法 - While 循环不会取消
【发布时间】:2020-08-09 05:31:39
【问题描述】:

我正在尝试编写 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 循环不会取消并永远继续。我希望有人可以帮助我。

【问题讨论】:

    标签: loops while-loop conditional-statements root infinite


    【解决方案1】:

    您正在重新初始化 while 循环内的 eps(as 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;
    
    
    }
    

    【讨论】:

      猜你喜欢
      • 2014-03-13
      • 1970-01-01
      • 2014-03-21
      • 2015-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多