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

目录

1、原理

2、案例 

3、代码实现

4、结果

5、误差分析与心得 


1、原理

2、案例 

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、结果

5、误差分析与心得 

 

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

荔枝科研社

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值