?? 單根牛頓切線法2.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 + -