JM Zhou
JM Zhou

Reputation: 115

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

How to pass an array to scipy.integate.solve_ivp function? Now the u=1.0, what I wanted is u=np.random.uniform(-1, 1, 1000).

The scipy version is 1.4.1

The code is:

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, ))

Any help would be appreciated!

Don't forget the comma in arg=(u, ), or you will have an error odepack.error: Extra arguments must be in a tuple. Thanks @Bear Brown for solving this problem.

Upvotes: 0

Views: 2505

Answers (1)

JM Zhou
JM Zhou

Reputation: 115

I think this may be worked.

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, ))

Here is a better solution. Thanks @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, ))

Upvotes: 2

Related Questions