梯形法求解常微分方程(c++)

梯形法求解常微分方程(c++)

#include<iostream>

#include<iomanip>

using namespace std;

int main()

{

      

      double x,y,yn,h,temp,f;     

      x=0;      //x赋初值

      y=1;      //y赋初值

      h=0.1;      //步长设置为0.1

      

      cout<<setiosflags(ios::left);

      cout<<setw(20)<<"y的计算值";

      cout<<setw(20)<<"y的理论值";

      cout<<setw(20)<<"x的值";

      cout<<setw(20)<<"误差"<<endl;

      cout<<setw(20)<<y;

      cout<<setw(20)<<y;

      cout<<setw(20)<<x;

      cout<<setw(20)<<0<<endl;

      

      for (int i=0;i<10;i++)

      {

            temp=y;      //每次迭代之前y未变化的值,用于后面的计算

            y=y+h*(y-2*x/y);      //使y显化

            f=y-2*x/y;      //保存未改变的fx,y)的值

            x+=h;

            

            do

            {

                  yn=y;

                  y=temp+h/2*(f+(y-(2*x/y)));

            }

            while (abs(yn-y)>0.0000001);

            cout<<setw(20)<<y;      //输出y的新值

            cout<<setw(20)<<sqrtf(1+2*x);      //计算y的理论值

            cout<<setw(20)<<x;      //输出x的新值

            cout<<setw(20)<<abs(y-sqrtf(1+2*x))<<endl     //计算误差

      }

      return 0;

}

梯形法求解常微分方程(c++)

posted @ 2015-11-27 18:59  硫酸亚铜  阅读(958)  评论(0编辑  收藏  举报