如何使用 args 将数组传递给 scipy.integrate.solve_ivp?

How to pass an array to scipy.integrate.solve_ivp using args?

如何将数组传递给 scipy.integate.solve_ivp 函数?现在u=1.0,我要的是u=np.random.uniform(-1, 1, 1000).

scipy版本为1.4.1

密码是:

import numpy as np
from scipy.integrate import solve_ivp

def func(t, x, u):
    dydt = (-x + u) / 5
    return dydt

y0 = 0
t_span = [0, 10]  
t_eval = np.linspace(0, 10, 1000)
u = 1.0

sol = solve_ivp(func, t_span=t, y0=y0, t_eval=t_eval, args=(u, ))

如有任何帮助,我们将不胜感激!

不要忘记arg=(u, )中的逗号,否则会出现错误odepack.error: Extra arguments must be in a tuple。感谢@Bear Brown 解决了这个问题。

我认为这可能有效。

import numpy as np
from scipy.integrate import solve_ivp

def func(t, x, u):
    dydt = (-x + u(t)) / 5
    return dydt

y0 = 0
t_span = [0, 10]  
t_eval = np.linspace(0, 10, 1000)
u = lambda t: np.random.uniform(-1, 1, 1000)

sol = solve_ivp(func, t_span=t, y0=y0, t_eval=t_eval, args=(u, ))

这是一个更好的解决方案。谢谢@Lutz Lehmann

import numpy as np
from scipy.integrate import solve_ivp
from scipy.interpolate import interp1d

def func(t, x, u):
    dydt = (-x + u(t)) / 5
    return dydt

y0 = 0
t_span = [0, 10]  
t_eval = np.linspace(0, 10, 1000)
u_value = np.random.uniform(-1, 1, 1000)
u = interp1d(x=t_eval, y=u_value)

sol = solve_ivp(func, t_span=t, y0=y0, t_eval=t_eval, args=(u, ))