目录

​1、原理​

​2、案例 ​

​3、代码实现​

​4、结果​

​5、误差分析与心得 ​


1、原理

牛顿下山法(C语言实现)_代码实现

2、案例 

牛顿下山法(C语言实现)_代码实现_02

3、代码实现

#include"iostream"
#include"stdlib.h"
#include"math.h"
#include"conio.h"
using namespace std;

double function(double x)
{
return sqrt(x)-x*x*x+2;
}

double function_dao(double x)
{
return 0.5*(1/sqrt(x))-3*x*x;
}
void error_output(int p)
{
switch(p)
{
case 1:cout<<"If the number of downhill times is exceeded, please select another initial value!"<<endl;
case 2:cout<<"Number of iterations exceeded, failed!";
}


}


int main()
{

double x,e,l=1,x1;
int m,n,k=1,j;
cout<<"Please enter the initial value: ";
cin>>x;
cout<<"Input accuracy: ";
cin>>e;
cout<<"Enter the maximum number of iterations: ";
cin>>m;
cout<<"Enter the maximum number of downhill trips: ";
cin>>n;

loop:
j=1;
if(function(x)==0){
cout<<"The initial value is the root of the equation!";
cout<<endl;
return 1;
}
x1=x-l*function(x)/function_dao(x);
for(l=1,j=1;j<=n&&k==1;j++)
{
x1=x-l*function(x)/function_dao(x);
if(fabs(function(x1))>fabs(function(x))){
l=l/2;
cout<<"x0 "<<x<<" x1 "<<x1<<endl;
}
else break;
}
for(l=1,j=1;j<=n&&k!=1;j++)
{
x1=x-l*function(x)/function_dao(x);
if(fabs(function(x1))>fabs(function(x))){
l=l/2;
cout<<"x0 "<<x<<" x1 "<<x1<<endl;
}
else break;
}
if(j>n)error_output(1);
if(fabs(x1-x)<e)cout<<"Find the root of the equation:"<<x1<<endl;
else{
if(k==m)error_output(2);
else {
k=k+1;
x=x1;
goto loop;
}
}
getch();
return 1;


}

4、结果

牛顿下山法(C语言实现)_代码实现_03

5、误差分析与心得 

牛顿下山法(C语言实现)_c语言_04