⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 单根牛顿切线法2.cpp

📁 我们的作业 计算方法里面的牛顿切线法求根
💻 CPP
字号:
////////////////////////////
///////newton iteration////
/////////////////////////// 
#include<iostream.h>
#include<math.h>

double f(double);
double f1(double);
void main()
{
	double a,b;
	double p0,y0,p1,y1;   //the initial point p0 and value y0
	double dp,df,rerr,eps;
	int n;
	int Max,cond;       // maxrepeat
	a=b=eps=pow(10,-6);
	Max=100;
	cond=0;
	n=0;
	cout<<"请输入初始值:"<<endl;
	cin>>p0;
	y0=f(p0);
	do
	{
		df=f1(p0);
		if(fabs(df)<eps)
		{
			cond=1;
			dp=0;
		}
		else
			dp=y0/df;//f(xn)/f'(xn)
		p1=p0-dp;//xn+1
		y1=f(p1);
		rerr=2*fabs(dp)/(fabs(p1)+eps);
		if((rerr<a)&&fabs(y1)<b)
			if(cond!=1)   cond=2;
		p0=p1;
		y0=y1;
		n++;
	}while(n<Max&&cond==0);
	cout<<"The iterate times:"<<n<<endl;
	cout<<"The current iterate   "<<p1<<"   consecutive iterates differ by  "<<dp<<endl;
    cout<<"The value of f(x) is  "<<y1<<endl;
    if(cond==1)  cout<<"Division by zero was encoutered"<<endl;
	if(cond==2)  cout<<"The root was found with the  desired tolerance."<<endl;
}

double f(double x)
{
	double t;
	t=x*x-4;
	return t;
}

double f1(double x)
{
	double t;
	t=2*x;
	return t;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -