使用牛顿法求函数零点

发布于 2021-09-13  651 次阅读


对于一个函数f(x)x_0为函数零点的近似值,使用牛顿迭代法,有迭达公式x_{k+1} = x_k - \frac{f(x_k)}{f^{\prime}(x_k)} , k=0, 1,2...。当k逐渐增大时,x_{k+1}趋近与所求零点的精确值。
实现如下:

#include<iostream>
#include<string>
#include<cmath>
#define e 0.00001 //迭代精度要求
#define N 50 //最大迭达次数
using namespace std;
double f(double x) //目标函数
{
      double c = sin(10 * x) - x;
      double d = 10 * cos(10 * x) - 1;
      return (c / d);
}

void newton(double x0)
{
    double a = x0;
    double x = x0 - f(x0);
    int i = 0;
    while (abs(x - a) > e)
    {
        cout << a << endl;
        a = x;
        i++;
        x = x - f(x);
        if (i > N)
        {
            cout << "Can't find zeros!" << endl;
            return;
        }
    } 
    cout << a << " is a root" << endl;
}

int main()
{
    double x0;
    cin >> x0;
    newton(x0);
    return 0;

}
「雪霁融雾月,冰消凝夜雨」
最后更新于 2021-09-13