一、牛顿迭代法算法:
设已知
第3步 求线性方程组的解
重复上述过程。
二、牛顿迭代法C++程序代码
//牛顿迭代解非线性方程组
#include <iostream>
#include <cmath>
using namespace std;
double f1(double x) {
double f = x * exp(x) - 1;
return f;
}
double f2(double x) {
double df = (x + 1)*exp(x);
return df;
}
double EPS = 1e-5;
double Newton(double x0)
{
double x1=0;
int itCount = 0;//迭代次数
do
{
if (itCount)
x0 = x1;
x1 = x0 - ((f1(x0)) / (f2(x1)));
itCount++;
} while (abs(x1 - x0) > EPS);
cout << " 运算迭代次数: " << itCount-1 << endl;
return x1;
}
void main()
{
double x;
double X;
cout << " 请输入初值 x0: ";
cin >> x;
X = Newton(x);
cout << " 达到计算精度使f(x)=0的解为: " << X << endl;
cout << endl;
system("pause");
}
例3(示例验证)用牛顿法求解方程f(x)=(x*e^x)-1=0在[0,1]内的一个实根,取初始点x0=0.5精度为10^-5。
三、牛顿法解非线性方程组MATLAB程序验证
function x=manewton(fun,dfun,x0,ep,N)
if nargin<5,N=500;end
if nargin<4,ep=1e-4;end
k=0;
while k<N
x=x0-feval(fun,x0)/feval(dfun,x0);
if abs(x-x0)<ep
break;
end
x0=x;k=k+1;
end
if k==N,waring('已达迭代次数上限');end
disp(['k=',num2str(k)])
验证结论:结果一致,代码正确。