from scipy.integrate import solve_ivp
def ydot(t,y): return [y[1], y[0]+2*np.exp(t)/3.]
def F(s):
a, b, yb = 0., 1., np.exp(1)/3.
sol = solve_ivp(ydot,[a,b],[0.,s],method='RK45')
return sol.y[0,-1]-yb
By trial and error, we find that \(F(0.2) = -0.1567\) and \(F(0.4) = 0.0783\). The interval \(0.2< s< 0.4\)
is a bracketing interval, and we can apply brentq (or the Bisection Method) to find a
root of \(F\). The commands
from scipy.optimize import brentq sstar = brentq(F,0.2,0.4)calculate \(s\). The result is \(s= 0.33333\). Finally,RK45 can be used to plot the solution:
sol = solve_ivp(ydot,[0,1],[0.,sstar],method='RK45',t_eval=np.linspace(0, 1, 20))
plt.plot(sol.t,sol.y[0])
plt.grid(True)
plt.xlabel('t')
plt.ylabel('y')
plt.show()
1 (b) As a first-order system, the differential equation is
\begin{eqnarray*}
y_0' &=& y_1\\
y_1' &=& (2+4t^2)y_0
\end{eqnarray*}
Write function files for the differential equation and \(F\) as in part (a). Note that \(F(-1)F(2)< 0\),
so there is a root \(s\) in \([-1,2]\). The Bisection Method converges to \(s=0\).
The solution is plotted below.
3 (b) Proceed as in Computer Problem 1. Note that \(F(-1)F(1)< 0\). Solving for \(s\) converges to \(s=0\). The solution is plotted below.
def ydot(t,y): return [-1./y[1], 2/y[0]]
def F(s):
a, b, yb = 1., 2., 4.
sol = solve_ivp(ydot,[a,b],[1.,s],method='RK45',rtol=1e-12)
return sol.y[1,-1]-yb
and a function file F.m to represent the shooting method problem, as in (7.5).
By trial and error, we find that \(F(1)F(3)\neq 0\). The interval \((1,3)\)
is a bracketing interval, and
either the Bisection Method or brentq>can be applied to converge to the root \(s=y_2(0)=1\).
Then RK45 can be used to plot the solution:
sstar=brentq(F,1,3)
sol = solve_ivp(ydot,[1.,2.],[1.,sstar],method='RK45',t_eval=np.linspace(1, 2, 20))
plt.plot(sol.t,sol.y[0],sol.t,sol.y[1])
plt.grid(True)
plt.xlabel('t')
plt.ylabel('y')
plt.show()
The solutions \(y_1(t)\) and \(y_2(t)\) are plotted below.
5 (b) Similar to part (a). There will be convergence to the root \(s=y_2(0)=1/3\), and the solutions \(y_1(t)\) and \(y_2(t)\) are plotted below.