Shooting Method¶
Copyright (C) 2020 Andreas Kloeckner
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import numpy as np
import matplotlib.pyplot as pt
def rk4_step(y, t, h, f):
k1 = f(t, y)
k2 = f(t+h/2, y + h/2*k1)
k3 = f(t+h/2, y + h/2*k2)
k4 = f(t+h, y + h*k3)
return y + h/6*(k1 + 2*k2 + 2*k3 + k4)
Want to solve:
$$w''(t)=\frac 32w^2$$
with $w(0)=4$ and $w(1)=1$. (Example due to Stoer and Bulirsch)
def f(t, y):
w, w_prime = y
return np.array([w_prime, 3/2*w**2])
The following function carries out the shooting method for a given $w'(0)$ using RK4:
def shoot(w_prime):
times = [0]
y_values = [np.array([4, w_prime])]
h = 1/2**7
t_end = 1
while times[-1] < t_end:
y_values.append(rk4_step(y_values[-1], times[-1], h, f))
times.append(times[-1]+h)
y_values = np.array(y_values)
# actually floating-point-equal due to power-of-2 h
assert times[-1] == t_end
print("w'(0) = %g -> w(1)= %.5g" % (w_prime, y_values[-1,0]))
pt.plot(times, y_values[:, 0], label="$w'(0)=%.2g$" % w_prime)
Call shoot
to see if you can solve the boundary value problem.
Start with $w'(0)=0$.
(You may call pt.legend
to take advantage of automatic labeling.)
shoot(0)
shoot(-5)
shoot(-7)
pt.grid()
pt.legend(loc="best")
w'(0) = 0 -> w(1)= 87.08 w'(0) = -5 -> w(1)= 12.058 w'(0) = -7 -> w(1)= 3.6442
<matplotlib.legend.Legend at 0x7ff0e4d85240>
See if you can find another solution to the boundary value problem by starting with $w'(0)=-30$.
(You may call pt.legend
to take advantage of automatic labeling.)
shoot(-30)
shoot(-33)
shoot(-36)
pt.grid()
pt.legend(loc="best")
w'(0) = -30 -> w(1)= -1.4668 w'(0) = -33 -> w(1)= -0.22938 w'(0) = -36 -> w(1)= 1.062
<matplotlib.legend.Legend at 0x7ff0e5138c50>