使AbstractOdeSolver类库以数字方式解决微分方程(c ++)

时间:2017-10-22 12:52:59

标签: c++ ode differential-equations differentiation

我正在尝试使用c ++和数值方法(euler,heun和runge kutta)制作和解决。首先,我为ode求解要求制作了抽象类,然后我为从ABClass继承的每个求解器创建了一个单独的类。代码excpet没有问题,它只适用于一阶微分方程为dydt = y 但是我需要将它扩展为能够求解一阶微分方程组,如dydt = x-y& dxdt = y在一起

这是头文件

    #ifndef ABSTRACTODESOLVER_H_INCLUDED
    #define ABSTRACTODESOLVER_H_INCLUDED
    #include <iostream>

    using namespace std;

    class AbstractOdeSolver
       {
    private:
       double stepsize;
       double initialTime;
       double finalTime;
       double initialValue;
    public:

       double (*RHS)(double, double); //pointer to function

       void SetStepSize(double h);
       void SetIntervalTime(double t0, double t1);
       void SetInitialValue(double y0);
       void setRHS(double (*pRHS)(double, double)); //set pointer function

       double getStepSize(){return stepsize;}
       double getInitialTime(){return initialTime;}
       double getFinalTime(){return finalTime;}
       double getInitialValue(){return initialValue;}

      virtual void SolveEquation() = 0;
     };

     class EulerSolver : public AbstractOdeSolver
     {
       public:
        virtual void SolveEquation();
     };

     class HeunSolver : public AbstractOdeSolver
     {
       public:
        virtual void SolveEquation();
     };

    class RungeKuttaSolver : public AbstractOdeSolver
    {
      public:
        virtual void SolveEquation();
     };
   #endif // ABSTRACTODESOLVER_H_INCLUDED

这是一个求解器的源代码:

    void EulerSolver::SolveEquation(){

double yNew = 0.0;
double yOld = getInitialValue(); // y0 initial value of Y
double tInit = getInitialTime(); // t0 initial value of T
double tFinal = getFinalTime();
double h = getStepSize();

    for (double i = tInit; i <= tFinal; i += h){

        yNew = yOld + (h * RHS(tInit,yOld));
        yOld = yNew;
        tInit += h;
        cout << left << setw(5) << tInit << " " << setw(5) << yNew << endl;
    }

}

这是一个程序:

    double Func(double t, double y){
return y;
   }

    EulerSolver euler1;
euler1.SetIntervalTime(0,0.6);
euler1.SetInitialValue(1);
euler1.SetStepSize(0.1);
euler1.setRHS(Func);
euler1.SolveEquation(); 

这里我使用函数指针RHS允许求解器每次在迭代中使用该函数,但是我需要有多个函数才能解决更高度方程和问题我不知道的方法使用相关变量(dydt = xy&amp; dxdt = y)创建两个单独的函数,然后在每个函数上都有一个指针并在数组中返回答案! 任何想法都会很棒。

0 个答案:

没有答案