Demo: Class ODESolver usage: A nonlinear ODE given by regular expression

We present a program to solve a nonlinear differential equation by the Runge-Kutta method (RK4). The differential equation is defined by a regular expression.

  • As any code using we start by including the main header file of the library. The main program starts by defining the final time and reading as argument the time step. Note that these variables are stored in the global variables theFinalTime and theTimeStep respectively.

    #include "OFELI.h"
    using namespace OFELI;
                              
    int main(int argc, char *argv[])
    {
       theFinalTime = 1.;
       theTimeStep = atof(argv[1]);

  • The ODE is defined by declaring an instance of class ODESolver. The constructor defined the numerical scheme to solve the equation. Note that we use the enum variable TimeScheme that contains all implemented schemes. Other possiblities are FORWARD_EULER, FORWARD_EULER, HEUN and AB2. Note that only explicit methods are used. Implicit methods lead to a nonlinear equation at each time step, which we avoid here.

       ODESolver ode(RK4);

  • Once the instance created, we set the initial solution, and define then the ODE by the member function setF. We note that the used variables are t and y since we attempt to solve the equation
             y'(t) = F(t,y(t))
    It is important that the initial solution is to be given before defining the equation. We eventually run the time marching procedure.

       ode.setInitial(0.);
       ode.setF("2*exp(t)-1-y");
       ode.run();

  • We can now display the ode data and the solution. We also dispolay the error for this case where the exact solution is y(t) = exp(t)-1 .

       cout << ode << endl;
       cout << "Solution:  " << ode.get() << endl;
       cout << "Error:     " << fabs(exp(theFinalTime)-1-ode.get()) < endl;
       return 0;
    }