tinit = 0 tfinal = 3 trange = [tinit,tfinal]
yinit = [1]
import numpy as np dydt = lambda t, y: 0.9 * y**2 * np.cos(t)
solve_ivp
from scipy.integrate
and call
it like this:
from scipy.integrate import solve_ivp mysol = solve_ivp(dydt, trange, yinit) ts = mysol.t ys = mysol.y[0]
solve_ivp
:
dydt
is the function that implements the differential equation
trange
is a list with the starting and ending -values for which the differential equation
should be solved. Importantly, the first element of trange
has to conform with that of the initial values.
yinit
is a list with the -value dictated by the initial values.
ts = mysol.t
and ys = mysol.y[0]
following the call of solve_ivp
select from the output of the function,
the and values for which the differential equation was actually solved.
import matplotlib.pyplot as plt plt.rc('font', size=16) fig,ax = plt.subplots(1,1) ax.plot(ts,ys,'o',linestyle='--') ax.grid() ax.set_ylim([0,11]) ax.set_xlabel('$t$') ax.set_ylabel('$y$')
solve_ivp
to solve a differential equation, the user may
specify for which -values, the solution is sought. That is done by adding
a keyword-argument t_eval
with a Python list (or NumPy array)
containing the values:
ts = np.linspace(tinit, tfinal, 100) mysol = solve_ivp(dydt, trange, yinit, t_eval=ts) ts = mysol.t ys = mysol.y[0] ax.plot(ts,ys) fig
solve_ivp
, that the integration now takes place from large
values to smaller ones. Only, it is important that the first -value given conforms with that of
the initial value condition. Thus, the trange
and yinit
must be changed into:
tinit = 9 tfinal = 4 trange = (tinit,tfinal) yinit = [5/4]
solve_ivp
can be made and the result be plotted:
mysol = solve_ivp(dydt, trange, yinit) ts = mysol.t ys = mysol.y[0] ax.plot(ts,ys,'o',linestyle='--') ax.set_xlim([-1,10]) fig
trange
is defined so that the first
value is the one conforming with the new initial values.
tinit = 0 tfinal = np.pi trange = [tinit,tfinal] yinit = [1] mysol = solve_ivp(dydt, trange, yinit) ys = mysol.y[0] # now print the final value for y, corresponding to y(tfinal) = y(t = pi) ys[-1]
1.0107395513007404
solve_ivp
while solving the differential
equation.
mysol = solve_ivp(dydt, trange, yinit, max_step=1e-1) ys = mysol.y[0] ys[-1]
1.0000016575704107
np.logspace
:
np.logspace(0,-4,5)
array([1.e+00, 1.e-01, 1.e-02, 1.e-03, 1.e-04])
max_step
-values and -values in
this way:
res = [(max_step, solve_ivp(dydt,trange,yinit,max_step=max_step).y[0][-1]) \ for max_step in np.logspace(0,-4,5)] res
res = [] for max_step in np.logspace(0,-4,5): mysol = solve_ivp(dydt, trange, yinit, max_step=max_step) ys = mysol.y[0] res.append((max_step, ys[-1])) res
[(1.0, 1.0107395513007404), (0.1, 1.0000016575704107), (0.01, 1.0000000000079718), (0.001, 0.9999999999999999), (0.0001, 0.9999999999999947)]
max_step
.
solve_ivp
.
These include the relative tolerance, rtol
,
and the absolute tolerance, atol
. You may find
more information
here.
Choose which booklet to go to: