牛頓法

先佔個坑, 以後來寫講解

代碼實現

求解 f(x)=x^5+2x-1 = 0的解

#include <iostream>
#include <cmath>
using namespace std;
// newtown method
double newtown(double (*fun)(double x), double (*deriv)(double x), double x0, double threshold)
{
    while (abs(0 - fun(x0)) > threshold)
    {
        x0 -= fun(x0) / deriv(x0);
    }
    return x0;
}
// main
int main(int argc, char const *argv[])
{
    double x0 = 0, threshold = 0.0002;
    auto fun = [](double x) -> double {
        return pow(x, 5.0) + 2 * x - 1;
    };
    auto deriv = [](double x) -> double {
        return 5 * pow(x, 4.0) + 2;
    };
    double res = newtown(fun, deriv, x0, threshold);
    cout << res << endl;
    cout << 18.0 / 37.0 << endl;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章