在多维数组上使用 odeint

问题描述 投票:0回答:1

我想将 odeint 应用于初始条件数组,并返回与这些初始条件大小相同的导数。我可以循环遍历每个初始条件,但我认为 N 越高,速度会非常慢。下面的示例来自 odeint 的 docs。 sol_1 按预期工作,但 sol_2 给出错误 ValueError: Initial condition y0 must be one-dimensional.


有没有人有一个聪明的解决方案来让 sol_2 运行而不只是循环每个初始条件?谢谢。

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))
    
python numpy scipy differential-equations odeint
1个回答
0
投票
根据 hpaulj 的评论,我想出了一个解决方案。它不是很漂亮,因为我传递了 N,但它确实有效,而且几乎肯定比循环更好。这也应该适用于 N 维输入,只需要在最后重塑回原始形状。

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))
    
© www.soinside.com 2019 - 2024. All rights reserved.