在CodeBlocks中运行C ++代码会将nan作为输出

时间:2016-11-15 13:08:43

标签: c++ codeblocks

我正在研究Epdidemic建模项目,我为此创建了一个SIR模型但现在当我在CodeBlocks中运行以下c ++代码时,它给了我一堆nan作为输出,我不确定究竟是什么导致了错误。我哪里错了?

 #include<iostream>
 #include<cmath>
 using namespace std;
 class SIR
 {

  private:

       double t,s,i,r,states[3];
       double diffstate[3],dt;
       double b,k;
       double time;

  public:

       SIR();
       SIR(double bCurr, double kCurr, double deltat, double sCurr, double iCurr, double maxtime);
       ~SIR();

        void stepStates(double states[3]);
        void Runge_Kutta();
        void printResult();
};

    SIR::SIR(double bCurr, double kCurr, double deltat, double sCurr,double iCurr, double maxtime)
{
      b = bCurr;
      k =kCurr;
      dt = deltat;
      s=sCurr;
      i = iCurr;
      r = 1 - s - i;
      time = maxtime;
  }

    SIR::~SIR(){}

    void SIR::stepStates(double states[3])
    {
      diffstate[0] = - b*states[0]*states[1];
      diffstate[1] = b*states[0]*states[1] - k*states[1];
      diffstate[2] = k*states[1];

    }

    void SIR::Runge_Kutta()
    {
       int i;
       double y1[3], y2[3], y3[3], y4[3];
       double x[3], initialStates[3];

       initialStates[0]=s; initialStates[1]=i; initialStates[2]=r;
       stepStates(initialStates);

         for(i=0;i<3;i++)
            {
              y1[i]=diffstate[i];
              x[i]=initialStates[i]+dt*y1[i]/2;
         }


          stepStates(x);
          for(i=0;i<3;i++)
            {
              y2[i]=diffstate[i];
              x[i]=initialStates[i]+dt*y2[i]/2;
       }

          stepStates(x);
          for(i=0;i<3;i++)
            {
               y3[i]=diffstate[i];
               x[i]=initialStates[i]+dt*y3[i];
      }

           stepStates(x);
           for(i=0;i<3;i++)
            {
               y4[i]=diffstate[i];
               x[i]=initialStates[i]+(y1[i]/6 + y2[i]/3 + y3[i]/3 + y4[i]/6)* dt;
      }

    s = x[0];
    i = x[1];
    r = x[2];
}

    void SIR::printResult()
    {
        t=0;
        cout <<"t    S    I       R \n"<<endl;
    do
    {
        Runge_Kutta();
        t+=dt;
        cout<<time<<"   "<<s<<"   "<<i<<"   "<<r<<"   "<<endl;
    }while(t<time);

}
    int main(int argc, char** argv)
    {
        double bCurr = 1.0/2.0;
        double sCurr = 9999999.0/10000000.0;
        double iCurr = 1.0/10000000.0;
        double rCurr = 0.0;
        double kCurr = 1.0/3.0;
        double deltat = 0.01/((bCurr*kCurr)*sCurr);// small step size in time
        std::cout << "time  S    I    R \n" << std::endl;
        double maxtime = 10;

        SIR mySIR(bCurr, kCurr, deltat ,sCurr, iCurr ,  maxtime);
        mySIR.printResult();

    return(0);

    }

0 个答案:

没有答案