Alexandru
Alexandru

Reputation: 1

index 2 is out of bounds for axis 0 with size 2 coupled pendulum differential equations

I am fairly new to coding, and have to code some models in one of my classes. In this case, I have to model a coupled pendulum, which is a system of second order differential equations.

Here are the two equations

As viewed in class, I simplified the equations to a system of 4 first order differential equations, and tried implementing them in my code and solving them using solve_ivp. Here is the code I wrote:

import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as integrate
import matplotlib.animation as animation

%matplotlib inline

g = 9.8
L = 2 #length of the pendulum in meters
k = 3
m1 = 2
m2 = 2

s = (20,20)
state = np.zeros(s)

def der_state(t, state):
        """compute the derivative of the given state"""
        der = np.zeros_like(state)
        der[0] = state[1]
        der[1] = (-(g/L)*np.sin(state[0]))-((k/m1)*((np.sin(state[0])-(np.sin(state[2])))))
        der[2] = state[3]
        der[3] = (-(g/L)*np.sin(state[0]))-((k/m2)*((np.sin(state[2])-(np.sin(state[1])))))
        return der

tf = 25 #simulation for tf seconds
n = 1000 #number of evaluation points
dt = tf/n
T = np.linspace(0.0, tf, n+1)

state0 = ([np.pi/4, 0.2]) #this is the initial state

sol = integrate.solve_ivp(der_state, (0, tf), state0, t_eval=T)
ang_pos = sol.y[0]

When running the code, the following error shows up:

      3         der = np.zeros_like(state)
      4         der[0] = state[1]
----> 5         der[1] = (-(g/L)*np.sin(state[0]))-((k/m1)*((np.sin(state[0])-(np.sin(state[2])))))
      6         der[2] = state[3]
      7         der[3] = (-(g/L)*np.sin(state[0]))-((k/m2)*((np.sin(state[2])-(np.sin(state[1])))))

IndexError: index 2 is out of bounds for axis 0 with size 2

I do not seem to understand what is causing this issue.

Upvotes: 0

Views: 41

Answers (1)

Marcelo Paco
Marcelo Paco

Reputation: 2934

The issue happens because of the following line of code:

state0 = ([np.pi/4, 0.2])

state0 holds the following list of size 2:

[0.7853981633974483, 0.2]

You then call integrate.solve_ivp with state0:

sol = integrate.solve_ivp(der_state, (0, tf), state0, t_eval=T)

Within the der_state function, the state variable - which is state0 - is expected to have more than two items in it:

der[1] = (-(g/L)*np.sin(state[0]))-((k/m1)*((np.sin(state[0])-(np.sin(state[2]))))) # Indexing 3 item in state
der[2] = state[3] # Indexing 4 item in state
der[3] = (-(g/L)*np.sin(state[0]))-((k/m2)*((np.sin(state[2])-(np.sin(state[1]))))) # Indexing 3 and 2 item in state

That is why you get the following error:

IndexError: index 2 is out of bounds for axis 0 with size 2

Upvotes: 2

Related Questions