用牛顿法解方程xe(x) -1=0
程序流程图如下:
//方程求根的迭代法——牛顿迭代法
/*************Analysis**********
*1.初值x0,精度e,迭代次数N
*2.牛顿法解方程f(x)=x*e**x-1
*3.取初值为0.5
********************************/
#include<iostream>
#include<math.h>
using namespace std;
//原函数
double f(double x)
{
return x*exp(x)-1;
}
//导数
double derivative(double x)
{
return (1+x)*exp(x);
}
int main()
{
double x0,x1;
double e;//precision
unsigned N=0;
unsigned k=0;
cout<<"----------NewtonIteration-----------"<<endl;
cout<<"Please input initial value x0:"<<endl;
cin>>x0;
cout<<"导数:"<<derivative(x0)<<endl;
cout<<"Please input precision e:"<<endl;
cin>>e;
cout<<"Please input iteration times N:"<<endl;
cin>>N;
k=1;
while(true)
{
if(derivative(x0)!=0)
{
//迭代关系式
x1=x0-f(x0)/derivative(x0);
cout<<"x1:"<<x1<<endl;
if(fabs(x1-x0)<e)
{
cout<<"x1:"<<x1<<endl;
break;
}
else
{
if(k==N)
{
cout<<"Sorry,the iteratting failed..."<<endl;
break;
}
else
{
k=k+1;
//cout<<"k:"<<k<<endl;
x0=x1;
cout<<"x0:"<<x0<<endl;
}
}
}
else
{
cout<<"The derivative of equation at x0 is 0 "<<endl;
break;
}
}
cout<<"Hello,Boker..."<<endl;
system("pause");
return 0;
}
运行结果如下: