A Notebook to compute solutions of the wave equation using a centered difference approximation for both the space and time derivatives.

Clear[u];Clear[A];Clear[B];Clear[a];Clear[b]

Start by clearing variables and setting initial conditions.

f[x_]=If[(1/4)<x<(1/2),3000*(x-(1/4))^2*((1/2)-x)^2,0]

Plot[f[x],{x,0,1},PlotRange->{0,1}]

g[x_]=0

Now fix the boundary conditions.

Do[u[m,0]:=0,{m,-1,500}]

Do[u[m,40]:=0,{m,-1,500}]

Set the size of the parameter s.

Choose the size of the time step.

dx=(1.0/40)

0.03

dt=(1.0/600)

s=(dt/dx)

For[j=1,j<40,j++,u[-1,j]=-dt*g[j*dx]+(1-s)*f[j*dx]+(s/2)*(f[(j-1)*dx]+f[(j+1)*dx])]

For[j=1,j<40,j++,u[0,j]=f[j*dx]]

Do[Do[u[n+1,j]=2*(1-s)*u[n,j]+s*(u[n,j+1]+u[n,j-1])-u[n-1,j],{j,1,39}],{n,0,500}]

Do[Do[U[n]=Table[u[n,j],{j,0,40}],{n,0,500}]]

Do[G[j]=ListPlot[U[j],Joined->True,PlotRange->{-3,3}],{j,0,500,4}]

Animate[G[j], {j,0,500,4}]