Search code examples
c++boostodeint

Second order differential equation using C++ Boost odeint library


Using boost c++ odeint library, is it possible to solve a second order differential equation defined as follows ?

m*x''[i] + x'[i] = K*\sum{j=1,N} sin(x[j] - x[i]), where i = 1,2,3..N.
m = 1, K = 1

where initial value of x is an vector or array of N uniformly generated random numbers between 0 to 2*pi. I want to integrate above equation using runge_kutta stepper of odeint ?

I can solve it by writing above eqn. in two first order differential equations, but then in that case how the odeint stepper's would be written or modified ?


Solution

  • Just transform your equations to a first order ODE and use a state type of length 2 N. The first N entries now handle only the x[i] while the second N entries refer to the velocities x'[i]

    void ode( state_type const& x , state_type &dxdt , double t )
    {
        for( size_t i=0 ; i<N ; ++i )
        {
            double sum = 0.0;
            // calculate sum
            dxdt[i] = x[i+N];
            dxdt[i+N] = K * sum;
        }
    }
    

    A complete example might look like

    size_t N = 512;
    typedef std::vector< double > state_type;
    state_type x( 2 * N );
    // initialize x
    double t_start = 0.0 , t_end = 10.0 , dt = 0.01;
    odeint::integrate( ode , x , t_start , t_end , dt );