Newton iteration method algorithm:
Thought:
Divide the nonlinear equation into linear equations infinitely, and iterate using the triangular relationship of the slope (derivative) of the linear equation:
- Given an initial solution x0
- Calculate f(x0) and df(x0)
- Update x0=x0 - ((f(x0)) / (df(x1)));
- End if the change is less than the threshold or the number of iterations is reached
- Repeat the above process.
C++ tearing Newton iteration method
Example:
Use Newton's method to solve a real root of the equation f(x)=(x*e^x)-1=0 in [0,1], take the initial point x0=0.5 and the precision is e-5
//牛顿迭代解非线性方程组
#include <iostream>
#include <cmath>
using namespace std;
//非线性方程
double f(double x) {
double f = x * exp(x) - 1;
return f;
}
//求导
double df(double x) {
double df = (x + 1) * exp(x);
return df;
}
double EPS;
//迭代
double Newton(double x0)
{
double x1 = 0;
int itCount = 0;//迭代次数
do
{
if (itCount)
x0 = x1;
x1 = x0 - ((f(x0)) / (df(x1)));
cout << " 第" << ++itCount <<"次迭代后x="<<x1<< endl;
} while (abs(x1 - x0) > EPS);
return x1;
}
void main()
{
double x;
cout << " 请输入初值 x0: ";
cin >> x;
cout << "请输入EPS:";
cin >> EPS;
x = Newton(x);
cout << " 达到计算精度使f(x)=0的解为: " << x << endl;
cout << endl;
system("pause");
}