我想将 odeint 应用于初始条件数组,并返回与这些初始条件大小相同的导数。我可以循环遍历每个初始条件,但我认为 N 越高,速度会非常慢。下面的示例来自 odeint 的 docs。 sol_1 按预期工作,但 sol_2 给出错误 ValueError: Initial condition y0 must be one-dimensional.
import numpy as np
from scipy.integrate import odeint
def pend(y, t, b, c):
theta, omega = y
dydt = [omega, -b*omega - c*np.sin(theta)]
return dydt
b = 0.25
c = 5.0
t = np.linspace(0, 10, 101)
# 0D initial values, directly from docs
y0_1 = [np.pi - 0.1, 0]
sol_1 = odeint(pend, y0_1, t, args=(b, c))
# 1D initial values, directly from docs
y0_2 = [np.ones((3)) * (np.pi - 0.1), np.zeros((3))]
# Error here
sol2 = odeint(pend, y0_2, t, args=(b, c))
import numpy as np
from scipy.integrate import odeint
def pend(y, t, b, c):
theta, omega = y
dydt = [omega, -b*omega - c*np.sin(theta)]
return dydt
def pend2(y, t, b, c, N):
theta = y[:N]
omega = y[N:]
dydt = [omega, -b*omega - c*np.sin(theta)]
dydt = np.ndarray.flatten(np.array(dydt))
return dydt
b = 0.25
c = 5.0
t = np.linspace(0, 10, 101)
# 0D initial values, directly from docs
y0_1 = [np.pi - 0.1, 0]
sol_1 = odeint(pend, y0_1, t, args=(b, c))
# 1D initial values, directly from docs
theta0 = np.ones((3)) * (np.pi - 0.1)
omega0 = np.zeros((3))
y0_2 = [theta0, omega0]
# Flattened version of the inputs
y0_2f = np.ndarray.flatten(np.array(y0_2))
# Number of inputs
N = len(theta0)
# Run altered pend (pend2) with flattened inputs
sol_2 = odeint(pend2, y0_2f, t, args=(b, c, N))