Skip to content

Instantly share code, notes, and snippets.

@Haroperi
Last active December 14, 2015 12:49
Show Gist options
  • Save Haroperi/5089247 to your computer and use it in GitHub Desktop.
Save Haroperi/5089247 to your computer and use it in GitHub Desktop.
FDTD algorithm in Ruby
include Math
require 'pp'
X = 10
T = 4
PI = 3.14
dt = 1
dx = 1
# HW4 prob.2
#V = 0.8
#psi = [
# [0, 0, Math.sin(PI/4), sin(2*PI/4), sin(3*PI/4), 0, 0, 0, 0, 0, 0],
# [0, 0, Math.sin((1-0.8)*PI/4), sin((2-0.8)*PI/4), sin((3-0.8)*PI/4), sin((4-0.8)*PI/4), sin((5-0.8)*PI/4), 0, 0, 0, 0],
#]
#def s(x,t); 0; end
# HW6 problem3
V = 0.5
psi = [ [0]*X ]
def s(x,t)
if x == 5 && t == 0
1
else
0
end
end
(psi.size-1).upto(T-1) { |t|
psi[t+1] = []
0.upto(X-1) { |x|
right = x == X-1 ? 0 : psi[t][x+1]
left = x == 0 ? 0 : psi[t][x-1]
old = t == 0 ? 0 : psi[t-1][x]
psi[t+1][x] = -old + 2*psi[t][x] + V*V*dt*dt/dx/dx * (left + right - 2*psi[t][x]) + dt*dt*s(x,t)
}
}
pp psi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment