Search code examples
odegsldifferential-equations

gsl gnu solving first order ordinary differential equation


I visited the gnu gsl website and i dont find the example there to solve a differential equation to be intuitive at all (especially because it is using 2nd order differential equation). https://www.gnu.org/software/gsl/manual/html_node/ODE-Example-programs.html#ODE-Example-programs Can somebody guide about where to find a descriptive guide to how solve a very simple first order differetial equation.

For example, supoose my function is y'=x+2y (or any such function) then how do i write code in gsl to solve it with a given fixed step size and initial condition.


Solution

  • For y'=f(x,y)=x+2y the arrays have all dimension 1, which normally is something to avoid, but here it is instructional. For the explicit solvers, i.e., those not containing imp in the name, you do not need the Jacobian:

    #include <stdio.h>
    #include <gsl/gsl_errno.h>
    #include <gsl/gsl_matrix.h>
    #include <gsl/gsl_odeiv2.h>
    
    int odefunc (double x, const double y[], double f[], void *params)
    {
        f[0] = x+2*y[0];   
        return GSL_SUCCESS;
    }
    
    
    int * jac;
    
    int main ()
    {
        int dim = 1;
        gsl_odeiv2_system sys = {odefunc, NULL, dim, NULL};
    
        gsl_odeiv2_driver * d = gsl_odeiv2_driver_alloc_y_new (&sys, gsl_odeiv2_step_rkf45, 1e-6, 1e-6, 0.0);
        int i;
        double x0 = 0.0,  xf = 100.0; /* start and end of integration interval */
        double x = x0;
        double y[1] = { 1.0  };  /* initial value */
    
        for (i = 1; i <= 100; i++)
        {
            double xi = x0 + i * (xf-x0) / 100.0;
            int status = gsl_odeiv2_driver_apply (d, &x, xi, y);
    
            if (status != GSL_SUCCESS)
            {
                printf ("error, return value=%d\n", status);
                break;
            }
    
            printf ("%.8e %.8e\n", x, y[0]);
        }
    
        gsl_odeiv2_driver_free (d);
        return 0;
    }
    

    You may want to look up the book "Introduction to Computational Modeling Using C and Open-Source Tools" by Jose M. Garrido.