方程求根的迭代法——牛顿迭代法

用牛顿法解方程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;
}

运行结果如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值