The aim of the Lab is to derive an explicit finite difference method for solving an initial value problem of the heat equation in a bounded domain.
Let us consider the following problem: find $u$ such that \begin{gather}\frac{\partial u}{\partial t}(x,t)=\frac{1}{4}\frac{\partial^2 u}{\partial x^2}(x,t),\ x\in [-1,1],\ t\in (0,0.5]\\ u(-1,t)=1, u(1,t)=0,\ t\in (0,0.5]\\ u(x,0)=u_0(x),\ x\in [-1,1] \end{gather} where $u_0$ is a given function.
The procedure for deriving a finite difference approximation for the problem above consists of the following steps.
Please find $a,b,c$ such that the we have $$U_{i,k+1}=a\,U_{i-1,k}+b\,U_{ik}+c\,U_{i+1,k}$$ and give a complete description of the method (how the matrix $U$ should be filled)
Write a function that for given values of $m$ and $n$ and for given function $u_0$ returns the values $U_{im},\ i=0,\ldots,n$ of the approximate solution obtained by explicit finite difference method. Test the correctness of your function in the case $m=100,n=10$ and $u_0(x)=\sin(\pi x)+\frac{1-x}{2}$, when the exact solution is $u(x,t)=e^{-\pi^2 t/4}\sin(\pi x)+\frac{1-x}{2}$. Hint: $\pi$ in python is np.pi
Solution
import numpy as np
def lab8solver(m,n,u0):
xmin=??
xmax=??
T=???
delta_t=??
delta_x=?
#define values of x_i
x=??
#define matrix U with dimension (n+1)x(m+1)
U=??
#fill in the initial condition
#use boundary conditions
#the coefficients a,b,c in the formula for U[i,k+1]
#do not depend on time, so compute before starting a time cycle
a=
b=
c=
#compute all other values
return U[:,m]
#define u0
def u0(x):
return ??
m=100
n=10
approx_sol=lab8solver(m,n,u0)
print(approx_sol[:4])
#compare answers with values of exact solution
The total error caused by replacing exact derivatives with finite difference approximations is $O(\Delta t+\Delta x^2)$, which usually implies that the error of the approximate solution is of the same order. This means, that if we increase $m$ four times and $n$ two times, then the total error should be reduced approximately four times. Verify the convergence rate by computing the errors in the settings of the previous exercise for $m=4,16,64,256,1024$ and $n=2,4,8,16,32$.
#compute the errors and ratios of the consequtive errors
It turns out that explicit methods may be unstable for certain choices of parameters $m$ and $n$. This means, that if $m$ and $n$ do not satisfy certain condition, the approximate solution may have arbitrarily large errors even when we let $m$ and $n$ to go to infinity. The sufficient condition of stability is that the coefficients $a$, $b$ and $c$ are all nonnegative. Repeat the computations of the previous exercise for $m=2,8,32,128$ and $n=10,20,40,80$ and compute the errors. Are the values of the approximate solution converging to the correct values? Find also the values of $a$, $b$ and $c$. Is the stability condition satisfied?
#comute the errors and ratios of errors
#compute a,b,c for each of the computation, print the values