Skip to content

Instantly share code, notes, and snippets.

@kailaix
Last active July 28, 2022 11:05
Show Gist options
  • Save kailaix/9aea843188e1634fc972f2351c2f7565 to your computer and use it in GitHub Desktop.
Save kailaix/9aea843188e1634fc972f2351c2f7565 to your computer and use it in GitHub Desktop.
Example of 1D Wave Equation with Absorbing Boundary Condition
# solve 1D wave equation with ABC
using PyPlot
using Plots
using LinearAlgebra
N = 100
x = LinRange(-1.,1.,N+1)
Δx = x[2]-x[1]
NT = 200
Δt = 2.0/NT
U = zeros(N+1, NT+2)
U[:,1] = exp.(-10x.^2)
U[:,2] = exp.(-10x.^2)
cfun = x->1.
c = cfun.(x)
for i = 1:NT
U[2:end-1,i+2] = 2*U[2:end-1, i+1] - U[2:end-1, i] + (Δt/Δx)^2 * c[2:end-1] .* (
U[3:end, i+1] + U[1:end-2,i+1] - 2U[2:end-1,i+1]
)
r = cfun(x[end]-Δx/2)*Δt/Δx
U[end, i+2] = U[end-1, i+1] + (r-1)/(r+1)*(U[end-1,i+2]-U[end,i+1])
r = cfun(x[1]+Δx/2)*Δt/Δx
U[1, i+2] = U[2, i+1] - (1-r)/(1+r)*(U[2,i+2] - U[1, i+1])
end
@gif for i = 2:2:NT+2
Plots.plot(x, U[:,i],ylims=(0.0,0.8), label="wave at t=$(round((i-2)*Δt, digits=2))")
end
@kailaix
Copy link
Author

kailaix commented Dec 23, 2018

This example shows a simple finite difference scheme for 1D wave equation with obsorbing boundary condition. In a future gist, we will try to solve the inverse problem: given u(x,t=0) and u(x,t=1), we want to recover c(x).

Reference: 1D FDTD

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment