solve_ivp
like this:
from scipy.integrate import solve_ivp tinit = 0 tfinal = 20 trange = [tinit,tfinal] yinit = [1,-1] dydt = lambda t, y: [y[1],-y[0]-1/10*y[1]] mysol = solve_ivp(dydt, trange, yinit) ts = mysol.t y0s = mysol.y[0] y1s = mysol.y[1]
dydt
now assumes that its 2nd argument is a list with two elements, and .
dydt
returns a list of the right-hand sides of both differential equations, i.e. it returns
.
yinit
, is now a list
solve_ivp
with the mysol.y[0]
and mysol.y[1]
statements.
import matplotlib.pyplot as plt plt.rc('font', size=16) fig, ax = plt.subplots() ax.plot(ts,y0s,linestyle='dashed',marker='o') ax.plot(ts,y1s,linestyle='dashed',marker='x') ax.set_xlabel('$t$') ax.set_ylabel('$y$') ax.legend(['$y_0$','$y_1$'])
tinit = 0 tfinal = 20 trange = [tinit,tfinal] rinit = 1 winit = -1 yinit = [rinit,winit] def dydt(t,y): r = y[0] w = y[1] drdt = w dwdt = -r - 1/10 * w return [drdt,dwdt] mysol = solve_ivp(dydt, trange, yinit) ts = mysol.t rs = mysol.y[0] ws = mysol.y[1]
dydt
evaluating the right-hand side of the differential equations
has been defined at length, rather than in the compact form of a lambda-function. This in particular
allows for the section,
r = y[0] w = y[1]
drdt = w dwdt = -r - 1/10 * w
solve_ivp
. Adopting the same code, but using the present variable names, it may look like this:
from scipy.integrate import solve_ivp import matplotlib.pyplot as plt tinit = 0 tfinal = 12 trange = [tinit,tfinal] x0 = 1 v0 = -1 yinit = [x0,v0] def dydt(t,y): x = y[0] v = y[1] dxdt = v dvdt = -x - 1/10 * v return [dxdt,dvdt] mysol = solve_ivp(dydt, trange, yinit) ts = mysol.t xs = mysol.y[0] vs = mysol.y[1] plt.rc('font', size=16) fig,ax = plt.subplots(1,1) ax.plot(ts,xs,'o',linestyle='--') ax.plot(ts,vs,'x',linestyle='--') ax.grid() ax.set_xlim([-1,13]) ax.set_xlabel('$t$') ax.set_ylabel('$x,v$') ax.legend(['$x$',r'$v=\frac{dx}{dt}$'])
Choose which booklet to go to: