Numerical Solution of the Wave Equation: Finite Difference Method (FDM)
📂Numerical AnalysisNumerical Solution of the Wave Equation: Finite Difference Method (FDM)
Method
Assume we are given the following one-dimensional wave equation.
∂t2∂2u=c2∂x2∂2u,0≤x≤1,t≥0(1)
Our goal is to approximate the above solution using a finite number of points. Let’s discretize the spacetime domain as follows.
{(ℓΔx,nΔt):ℓ=0,1,…,d+1, n≥0} where Δx=d+11
We denote the approximation of u(ℓΔx,nΔt) as uℓn. Note that the superscript n is not a power but an index for time. The left-hand and right-hand sides of (1) are approximated as follows. Reference.
∂x2∂2u(x,t)=(Δx)21[u(x−Δx,t)−2u(x,t)+u(x+Δx,t)]+O((Δx)2)
∂t2∂2u(x,t)=(Δt)21[u(x,t−Δt)−2u(x,t)+u(x,t+Δt)]+O((Δt)2)
Now, let us denote μ=ΔxΔt. By substituting both expressions into (1) and rearranging, we obtain the following.
u(x,t−Δt)−2u(x,t)+u(x,t+Δt)≈μ2[u(x−Δx,t)−2u(x,t)+u(x+Δx,t)]
⟹u(x,t+Δt)≈2u(x,t)−u(x,t−Δt)+μ2[u(x−Δx,t)−2u(x,t)+u(x+Δx,t)]
⟹u(x,t+Δt)≈2(1−μ2)u(x,t)−u(x,t−Δt)+μ2[u(x−Δx,t)+u(x+Δx,t)]
⟹uℓn+1=μ2uℓ+1n+2(1−μ2)uℓn+μ2uℓ−1n−uℓn−1,ℓ=1,…,d, n=0,1,…(2)
Here, the ratio of the spatial interval to the temporal interval, μ=ΔxΔt, is a crucial constant known as the Courant number, which determines the convergence of (2).
Explanation
The above method converges when μ≤1.

Code
Setting the boundary conditions to 0 and performing the calculations yields the following result.

using Plots
x = LinRange(-1, 1, 300)
Δx = x[2] - x[1]
t = LinRange(0, 4, 600)
Δt = t[2] - t[1]
μ = Δt / Δx
U = zeros(length(x), length(t))
U[:, 1] = exp.(-30 * x.^2)
U[:, 2] = exp.(-30 * x.^2)
for i ∈ 3:length(t)
U[2:end-1, i] = (μ^2)*U[3:end, i-1] + 2(1-μ^2)*U[2:end-1, i-1] + (μ^2)*U[1:end-2, i-1] - U[2:end-1, i-2]
end
heatmap(U)
anim = @animate for i ∈ 1:length(t)
plot(x, U[:, i], xlims=(-1, 1), ylims=(-2,2), legend=false)
end
gif(anim, fps=50)