python 对于轴0和大小为2的耦合摆微分方程,索引2是越界的

a5g8bdjr  于 2023-04-19  发布在  Python
关注(0)|答案(1)|浏览(97)

我是一个编程新手,必须在我的一个课程中编写一些模型。在这种情况下,我必须对耦合摆建模,这是一个二阶微分方程系统。

正如在课堂上看到的,我将方程简化为4个一阶微分方程的系统,并尝试在我的代码中实现它们并使用solve_ivp求解它们。下面是我编写的代码:

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]

运行代码时,出现以下错误:

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

我似乎不明白是什么导致了这个问题。

dbf7pr2w

dbf7pr2w1#

出现此问题的原因是以下代码行:

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

state0包含以下size2的列表:

[0.7853981633974483, 0.2]

然后,使用state0调用integrate.solve_ivp

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

der_state函数中,state变量(即state0)应该有多于两个项:

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

这就是为什么你得到以下错误:

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

相关问题