# A graphics library
import matplotlib.pyplot as plt
# Basic numerical tools
import numpy as np
# Scipy's numerical ODE solver
from scipy.integrate import odeint
The odeint
command solves initial value problems (IVPs) of the form
The command is acually a bit more general than that in that it works with systems of equations but we'll deal with that later.
To be more concrete, suppose that we wish to solve
$$ y' = t-y, \: \: y(-1)=1, \: \text{ over } -1 \leq t \leq 1. $$We can do so as follows:
def f(y,t):
return t-y
t = np.linspace(-1,2)
y = odeint(f, 1, t).flatten()
y
We can then visualize the solution:
plt.plot(t,y)
Now suppose that we would like to know when the solution hits $y(t)=1$. We'll apply the SciPy solver called brentq
to an interpolated version of the solution. First, we import a couple more libraries:
from scipy.interpolate import interp1d
from scipy.optimize import brentq
We can now solve the problem as follows:
y_func = interp1d(t,y)
t1 = brentq(lambda t: y_func(t)-1,1,2)
t1
And visualize:
plt.plot(t,y)
plt.plot([t1,t1],[0,1.2],'k--')
plt.plot(t1,1,'ko')