python - 通过 odeint 函数求解 ODE 时如何将数组作为参数传递(在 Python 中)

标签 python ode

我的 ODE 为 Mx''+Lx'+f(x)=0,其中 f(x) 是多项式函数。请查看我的完整代码,其中我在名为“diff”的函数中定义了微分方程。然后我使用调用“diff”的“odeint”以及必要的参数来求解微分方程。

现在我考虑 f(x)=ax。这里我必须传递总共三个参数 (M,L,a) 作为 'diff' 函数的参数。事实上,如果我这样写,代码就可以工作:(查看完整代码)

 sol = odeint(diff, y0, t, args=(M,L, a))

但是当 f(x) 是 x 的 10 次幂的多项式时,参数列表就会变得太长。因此我想将所有参数放在一个数组中,然后将该数组作为参数传递。我这样试过:

def diff(y, t, inertia):
    M=inertia[0]
    L=inertia[1]
    a=inertia[2]

    x,v = y
    dydt = [v, (-L*v - a*x)/M]
    return dydt

M=5
L = 0.5
a = 5.0
Inertia=(M,L,a)

sol = odeint(diff, y0, t, args=Inertia)

但是这种方法行不通。它说'TypeError: diff() takes 3 positional arguments but 5 were given'。

我怎样才能使这种方法起作用,或者如何将参数列表作为参数发送?

完整代码:

import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt



def diff(y, t, M, L, a):   
    x,v = y
    dydt = [v, (-L*v - a*x)/M]
    return dydt

M=5
L = 0.5
a = 5.0

#Inertia=(M,L,a)
#But I cant pass the 'Inertia' as an argument 


y0 = [- 0.1, 0.0]
t = np.linspace(0, 10, 101)
sol = odeint(diff, y0, t, args=(M,L, a))



plt.plot(t, sol[:, 0], 'b', label='x(t)')
plt.plot(t, sol[:, 1], 'g', label='v(t)')
plt.legend(loc='best')
plt.show()

最佳答案

Inertia 在这种情况下是一个元组。 odeint 需要一个参数元组作为其 args 参数,因此 Inertia 被解包并且 diff 的参数变为 y0, t, M , L, a。为了避免这种情况,您应该将 Inertia 打包到另一个元组中,使 Inertia 成为一个参数,如下所示:

sol = odeint(diff, y0, t, args=(Inertia,))

注意 Inertia 之后的 ,。这使它成为一个元组 ((a) == a, (a,) == tuple(a))

关于python - 通过 odeint 函数求解 ODE 时如何将数组作为参数传递(在 Python 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47836772/

相关文章:

python - np.array arr.itemsize 与 sys.getsizeof(arr[0])

Python unix套接字服务器多次从客户端接收相同的数据

python - 使用 `ode` 方法的 scipy 的 'vode' 求解器给出一个空数组结果

python - 相空间中的轨迹 - 溢出错误 : (34, 'Result too large' )

python - 如何更改pyplot轴的增量

python - 使用python的线性支持向量机中的软边距

python - 按时间排序列表中的文件,无法在列表中找到文件

julia - Julia 微分方程.jl速度

ode - Dymola DAE 求解器

modeling - OpenModelica (v1.13.0) : FMU export is broken - static. 日志:没有这样的文件或目录