%matplotlib inline
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
Here you will set up the problem for $$ u_t + c u_x = 0$$ with periodic BC on the interval [0,1]
a = 1.0
T = 4.0 / a # end time
dx will be the grid spacing in the $x$-direction
x will be the grid coordinates
xx will be really fine grid coordinates
nx = 90
k = 10
x = np.linspace(0, 2*np.pi, nx, endpoint=False)
dx = x[1] - x[0]
xx = np.linspace(0, 2*np.pi, 1000, endpoint=False)
Now define an initial condition
def f(x):
u = np.sin(k * x)
return u
plt.plot(xx, f(xx), lw=3, clip_on=False)
Now we need a time step. Let $$ \Delta t = \Delta x \frac{\lambda}{a}$$
So we need a parameter $\lambda$
What happens when $\lambda>1.0$?
When the `method` changes to FTCS, what is the impact of $\lambda$?
lmbda = 0.6
dt = dx * lmbda / a
nt = int(T/dt)
print('T = %g' % T)
print('tsteps = %d' % nt)
print(' dx = %g' % dx)
print(' dt = %g' % dt)
print('lambda = %g' % lmbda)
Now make an index list, called $J$, so that we can access $J+1$ and $J-1$ easily
J = np.arange(0, nx) # all vertices
Jm1 = np.roll(J, 1)
Jp1 = np.roll(J, -1)
For ipython notebooks be sure to use clear_output. Alternatively, animation
from matplotlib
may be useful.
method = 'FTBS'
plotit = True
uFTBS = f(x)
uLW = f(x)
if plotit:
fig = plt.figure(figsize=(10,10))
ax = fig.add_subplot(111)
ax.set_title('u vs x')
for n in range(0, nt):
uFTBS[J] = uFTBS[J] - lmbda * (uFTBS[J] - uFTBS[Jm1]) # FTBS
uLW[J] = uLW[J] - lmbda * (1.0 / 2.0) * (uLW[Jp1] - uLW[Jm1]) \
+ (lmbda**2 / 2.0) * (uLW[Jp1] - 2 * uLW[J] + uLW[Jm1])
uex = f((xx - c * (n+1) * dt) % 1.0)
if plotit:
ax.plot(x, uFTBS, '-', lw=3, clip_on=False, label=method)
ax.plot(x, uLW, '-', lw=3, clip_on=False, label=method)
ax.plot(xx, uex, 'k-', lw=3, clip_on=False, label='exact')
ax.legend(frameon=False)
plt.show()