C ++牛顿拉夫森法比对分法慢吗?

时间:2020-05-01 18:49:55

标签: c++ methods iteration bisection


我的任务是在10E-7的误差范围内使用Newton Raphson和二分法找到函数的根。 总而言之,我们了解到牛顿拉夫森法更快,更有效。 现在由于某种原因,我得出相反的结果。尽管我知道这两种方法中对根的初始猜测会严重影响必要的迭代次数。但是我在两种算法中都输入了类似的猜测,而我的同学没有得到我做的结果。

对分法:

#include <iostream>
#include <iomanip>

using namespace std;


//Declaring the given function
double func1(double x) {

    return 0.00000000027 * (x - 10000000) - 0.16460351745 * (-1 + ((1000000000) / (x))) * 1 / (sqrt(x));

}

int main() {
    std::fixed;


    //Initial guess: root ist at 10 to the 7.
    double x1 = 10000000;
    double x2 = 1000000000;
    double eps = 0.0000001;
    int i = 0;
    double x0[100000];
    x0[0] =0;


    //Exception handler
    if (func1(x1) * func1(x2) > 0) {
        cout << "Root is not inside the bracket.";
        goto end;
    }
    goto start;


    //Bisection Algorithm 
    while (abs(x0[i] - x0[i-1]) >= eps) {

    start:

        i = i + 1;
        x0[i] = 0.5 * (x1 + x2);


        if (func1(x1) * func1(x0[i]) < 0) {

            x2 = x0[i];
        }
        else {
            x1 = x0[i];
        }





    }

    cout << endl << "Bisection Method: " << fixed << setprecision(10) << x0[i] << endl << "Iterations: " << i << endl << endl << endl << endl << endl;

    end:
    return 0;
}
}

牛顿·拉夫森:

#include <iostream>
#include <iomanip>

using namespace std;

// Declaring the function and its derivative
 double func1(double x) {

  return 0.00000000027 * (x - 10000000) - 0.16460351745 * (-1 + ((1000000000) / (x))) * 1 / (sqrt(x));

}

double funcderiv1(double x) {

     return 0.00000000027+((0.1646035174)/(2*x*x*sqrt(x)))*(30000000-x);

}


int main()
{
    std::fixed;
    double eps = 1;
    double x_start = 10000000;
    double c;

    int i = 0;

    while (eps >= 0.0000001) {


        c = x_start - ((func1(x_start)) / (funcderiv1(x_start)));
        eps = abs(func1(x_start) / funcderiv1(x_start));
        x_start = c;

        i = i + 1;



    }

    cout << fixed << setprecision(5) << "RESULT " << c << endl << " Iterations: " << i << endl;

}


根源为17903534.23630

有人知道为什么我的二分法需要55次迭代,而Newton Raphson却需要82次吗?

1 个答案:

答案 0 :(得分:1)

对于功能

f(x) = A * (x - B) - C * (D / x - 1) / sqrt(x)

A = 0.00000000027
B = 10000000
C = 0.16460351745
D = 1000000000

正确的导数是:

f'(x) = A - C (x - 3D) / (2 * x * x * sqrt(x))

将此与您的表情进行比较:

g(x) = A - C (x - 3B) / (2 * x * x * sqrt(x))

修正公式(通过添加两个零)后,您的代码进行了6次迭代:

RESULT 17903534.23630

 Iterations: 6
相关问题