天天看點

牛頓下山法C++實作

目标:

      用牛頓下山法,求非線性方程x*x*x-x-1=0,的根。

要求:

       輸入,初值,誤差限,最大疊代次數,最大下山次數;

       輸出,近似根以及下山因子;

代碼(C++實作):

//牛頓下山法

//非線性方程求根

#include"iostream"

#include"stdlib.h"

#include"math.h"

#include"conio.h"

using namespace std;

double function(double x)

{

       return x*x*x-x-1;

       }

double function_dao(double x)

{

       return 3*x*x-1;

       }

void error_output(int p)

{

     switch(p)

     {

              case 1:cout<<"超出下山次數,請另選擇初值!"<<endl;

              case 2:cout<<"超出疊代次數,失敗!";

              }

     }   

int main()

{

  double x,e,l=1,x1;

  int m,n,k=1,j;

  cout<<"請輸入初值: ";

  cin>>x;

  cout<<"輸入精度: ";

  cin>>e;

  cout<<"輸入最大疊代次數 : ";

  cin>>m;

  cout<<"輸入最大下山次數:  ";

  cin>>n;

  loop:

       j=1;

        if(function(x)==0){

                           cout<<"該初值就是方程的根!";

                           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<<"求得方程的根:"<<x1<<endl;

        else{

             if(k==m)error_output(2);

             else {

                  k=k+1;

                  x=x1;

                  goto loop;

                  }

                  }

  getch();

  return 1;

}

以上程式在DEV C++中調試通過,由于時間倉觸,未對程式進行優化。但算法核心無誤,基本達到要求;