Skip to content

Instantly share code, notes, and snippets.

@mick001
Last active August 28, 2015 18:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mick001/18d8363da4a7f78d31d7 to your computer and use it in GitHub Desktop.
Save mick001/18d8363da4a7f78d31d7 to your computer and use it in GitHub Desktop.
The wave equation: a Python implementation. Full article at: http://www.firsttimeprogrammer.blogspot.com/2015/07/the-wave-equation-2d-and-3d.html
import numpy as np
from numpy import pi
import matplotlib.pyplot as plt
import matplotlib.animation as animation
plt.style.use('dark_background')
fig = plt.figure()
fig.set_dpi(100)
ax1 = fig.add_subplot(1,1,1)
#Wave speed
c = 1
#x axis
x0 = np.linspace(-pi,pi,10000)
#Initial time
t0 = 0
#Time increment
dt = 0.05
#Wave equation solution
def u(x,t):
return 0.5*(np.sin(x+c*t) + np.sin(x-c*t))
a = []
for i in range(500):
value = u(x0,t0)
t0 = t0 + dt
a.append(value)
k = 0
def animate(i):
global k
x = a[k]
k += 1
ax1.clear()
plt.plot(x0,x,color='cyan')
plt.grid(True)
plt.ylim([-2,2])
plt.xlim([-pi,pi])
anim = animation.FuncAnimation(fig,animate,frames=360,interval=20)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment