Skip to content
scipython.com

The two-dimensional wave equation

Posted on

The wave equation is a second-order linear partial differential equation that describes non-dispersive waves (those whose speed does not depend on their wavelength), such as sound, light and the small vibrations of a stretched membrane. This post introduces a finite-difference solution of its two-dimensional form, with reflecting and absorbing boundary conditions, and uses it to animate the waves from an oscillating source, from raindrops and from a double slit.

The two-dimensional wave equation,

\[\frac{\partial^2 u}{\partial t^2} = c^2\left( \frac{\partial^2 u}{\partial x^2} + \frac{\partial^2 u}{\partial y^2} \right) = c^2\nabla^2 u,\]

describes small displacements, \(u(x, y, t)\), of a surface on which waves travel at the same speed, \(c\), in every direction and at every wavelength. The classic example is a stretched membrane such as a drumhead, whose normal modes are the subject of the example Drum vibrations with Bessel functions. Waves on water obey it only where the water is shallow compared with their wavelength, in which case \(c = \sqrt{gH}\) for a depth \(H\); on deeper water, waves are dispersive (their speed depends on their wavelength), with consequences described in the post on the Kelvin wake pattern.

Finite-difference scheme

To solve the wave equation numerically, the displacement is calculated only at the points of a square grid, with spacing \(h\), and at times separated by a time step, \(\Delta t\):

\[u_{i,j}^{(n)} = u(ih, jh, n\Delta t).\]

The derivatives are then approximated by finite differences between the displacements at neighbouring points. The second derivative of a function \(f(x)\) is the difference between its first derivatives at \(x + h/2\) and \(x - h/2\), divided by \(h\); approximating each of these by the difference between the values of \(f\) on either side of it, divided by \(h\) (a central difference), gives

\[\frac{\mathrm{d}^2 f}{\mathrm{d}x^2} \approx \frac{1}{h}\left[\frac{f(x+h) - f(x)}{h} - \frac{f(x) - f(x-h)}{h}\right] = \frac{f(x+h) - 2f(x) + f(x-h)}{h^2},\]

with an error proportional to \(h^2\). The sum of this approximation to \(\partial^2 u/\partial x^2\) and the corresponding one to \(\partial^2 u/\partial y^2\) is the five-point stencil for the Laplacian:

\[\nabla^2 u \approx \frac{u_{i+1,j}^{(n)} + u_{i-1,j}^{(n)} + u_{i,j+1}^{(n)} + u_{i,j-1}^{(n)} - 4u_{i,j}^{(n)}}{h^2}.\]

With the same approximation to the second derivative with respect to time, the wave equation becomes

\[\frac{u_{i,j}^{(n+1)} - 2u_{i,j}^{(n)} + u_{i,j}^{(n-1)}}{\Delta t^2} = c^2\,\frac{u_{i+1,j}^{(n)} + u_{i-1,j}^{(n)} + u_{i,j+1}^{(n)} + u_{i,j-1}^{(n)} - 4u_{i,j}^{(n)}}{h^2},\]

which can be solved for the displacement at each point at the next time step:

\[u_{i,j}^{(n+1)} = 2u_{i,j}^{(n)} - u_{i,j}^{(n-1)} + \alpha^2\left( u_{i+1,j}^{(n)} + u_{i-1,j}^{(n)} + u_{i,j+1}^{(n)} + u_{i,j-1}^{(n)} - 4u_{i,j}^{(n)} \right). \tag{1}\]

Here, \(\alpha = c\Delta t/h\) is the Courant number: the distance a wave travels in one time step, in units of the grid spacing. Each time step needs the displacements at the two before it, so the simulation keeps those at three time steps: \(n-1\), \(n\) and \(n+1\). The same finite differences are applied to the diffusion equation in the example The two-dimensional diffusion equation.

Stability

The Courant number cannot be chosen freely: the scheme is stable only if

\[\alpha = \frac{c\Delta t}{h} \le \frac{1}{\sqrt{2}}.\]

This is the two-dimensional form of the Courant–Friedrichs–Lewy (CFL) condition [R. Courant, K. Friedrichs and H. Lewy, Math. Ann. 100, 32–74 (1928), doi:10.1007/BF01448839], which has a geometrical interpretation. After \(n\) time steps, the displacement that equation (1) gives at a grid point depends only on the initial displacements within \(n\) steps between nearest neighbours of it: a square, rotated by 45°, whose corners are \(nh\) away. The true solution depends on the initial displacements within a circle of radius \(cn\Delta t\), which fits inside this square only if \(cn\Delta t \le nh/\sqrt{2}\); otherwise, the numerical solution cannot depend on everything that the true one does. A von Neumann stability analysis, which follows each Fourier component of the displacement separately, shows that the condition is also sufficient: the scheme is stable if, for every wavevector \((k_x, k_y)\) that the grid can represent,

\[\alpha^2\left[\sin^2\left(\frac{k_xh}{2}\right) + \sin^2\left(\frac{k_yh}{2}\right)\right] \le 1.\]
Show derivationHide derivation

Equation (1) is linear, so it advances each Fourier component of the displacement independently, multiplying it by an amplification factor, \(G\), at each time step:

\[u_{i,j}^{(n)} = G^n \cos(k_x ih)\cos(k_y jh).\]

Since \(\cos[k_x(i+1)h] + \cos[k_x(i-1)h] = 2\cos(k_xh)\cos(k_xih)\), and similarly for \(y\), substituting this into equation (1) and dividing by \(G^{n-1}\cos(k_xih)\cos(k_yjh)\) gives

\[G^2 = 2G - 1 + 2\alpha^2\left[\cos(k_xh) + \cos(k_yh) - 2\right]G = 2(1 - 2\alpha^2 s)G - 1,\]

where we have used the identity \(1 - \cos\theta = 2\sin^2(\theta/2)\) and written \(s = \sin^2(k_xh/2) + \sin^2(k_yh/2)\). The product of the two roots of this quadratic equation is 1. If \(|1 - 2\alpha^2 s| \le 1\), they are complex conjugates with \(|G| = 1\), and the component oscillates with a constant amplitude; otherwise, they are real, one of them has \(|G| > 1\), and the component grows exponentially. Since \(s \ge 0\), the condition \(|1 - 2\alpha^2 s| \le 1\) is \(\alpha^2 s \le 1\).

The left-hand side is largest for the chequerboard pattern, in which each point has the opposite sign to its four neighbours (\(k_xh = k_yh = \pi\)), for which it is \(2\alpha^2\). If \(\alpha > 1/\sqrt{2}\), this pattern grows at every time step, starting from rounding errors if nothing else, and swamps the solution: with \(\alpha = 0.71\), it grows by a factor of 1.198 at each time step, and the displacement of a pulse of unit height exceeds 10 after 245 time steps. The class below therefore refuses a Courant number greater than \(1/\sqrt{2}\).

Boundary conditions

At the edges of the grid, the five-point stencil lacks a neighbour, and a boundary condition is needed instead. The simplest is to hold the displacement there at zero:

\[u_{0,j}^{(n)} = u_{N_x,j}^{(n)} = u_{i,0}^{(n)} = u_{i,N_y}^{(n)} = 0,\]

where \(N_x\) and \(N_y\) are the indices of the last points in the \(x\) and \(y\) directions. This Dirichlet boundary condition describes a membrane clamped at its edges, from which waves are reflected, inverted, so that none of their energy leaves the grid.

To simulate waves on an unbounded surface, the edges must instead absorb the waves that reach them. No local condition (one that involves only neighbouring points and recent time steps) can do this exactly for waves arriving from every direction, but there are good approximations, of which a widely used one is due to Mur [G. Mur, IEEE Trans. Electromagn. Compat. EMC-23, 377–382 (1981), doi:10.1109/TEMC.1981.303970]. It is a discretisation of the first-order condition of Engquist and Majda [B. Engquist and A. Majda, Math. Comput. 31, 629–651 (1977), doi:10.1090/S0025-5718-1977-0436612-4], whose origin is clearest in one dimension, in which the wave equation can be factorised:

\[\frac{\partial^2 u}{\partial t^2} - c^2\frac{\partial^2 u}{\partial x^2} = \left( \frac{\partial}{\partial t} - c\frac{\partial}{\partial x}\right)\left( \frac{\partial}{\partial t} + c\frac{\partial}{\partial x}\right)u = 0.\]

Each factor gives a one-way wave equation, whose solutions travel in one direction only:

\[\begin{aligned} \frac{\partial u}{\partial t} - c\frac{\partial u}{\partial x} &= 0 \quad\Rightarrow\quad u = f(x + ct),\\ \frac{\partial u}{\partial t} + c\frac{\partial u}{\partial x} &= 0 \quad\Rightarrow\quad u = g(x - ct), \end{aligned}\]

for any functions \(f\) and \(g\), which travel in the \(-x\) and \(+x\) directions respectively. Imposing the first equation at the boundary \(x = 0\) allows only waves travelling out of the grid, in the \(-x\) direction, and so nothing is reflected back into it; the second equation does the same at the opposite boundary, \(x = N_xh\). In two dimensions, the same conditions are imposed at each edge, with \(y\) in place of \(x\) at the edges \(y = 0\) and \(y = N_yh\).

The first equation is discretised to the same accuracy as equation (1) by evaluating both of its derivatives at the same point, half-way between grid points in both space and time: \(x = h/2\) and \(t = (n + \frac{1}{2})\Delta t\). The result gives the displacement on the boundary at the next time step:

\[u_{0,j}^{(n+1)} = u_{1,j}^{(n)} - \frac{1-\alpha}{1+\alpha}\left(u_{1,j}^{(n+1)} - u_{0,j}^{(n)}\right)\]
Show derivationHide derivation

The time derivative at \(x = h/2\) is the mean of the central differences at \(i = 0\) and \(i = 1\), and the space derivative at \(t = (n + \frac{1}{2})\Delta t\) is the mean of those at time steps \(n\) and \(n+1\):

\[\frac{1}{2}\left( \frac{u_{1,j}^{(n+1)} - u_{1,j}^{(n)}}{\Delta t} + \frac{u_{0,j}^{(n+1)} - u_{0,j}^{(n)}}{\Delta t}\right) - \frac{c}{2}\left( \frac{u_{1,j}^{(n+1)} - u_{0,j}^{(n+1)}}{h} + \frac{u_{1,j}^{(n)} - u_{0,j}^{(n)}}{h} \right) = 0.\]

Multiplying by \(2\Delta t\) and collecting the terms in each displacement gives

\[(1+\alpha)\,u_{0,j}^{(n+1)} + (1-\alpha)\,u_{1,j}^{(n+1)} - (1+\alpha)\,u_{1,j}^{(n)} - (1-\alpha)\,u_{0,j}^{(n)} = 0,\]

which, divided by \(1 + \alpha\), can be rearranged into the result.

The displacement just inside the boundary, \(u_{1,j}^{(n+1)}\), is given by equation (1), and so the boundary is updated after the interior of the grid. The condition at the opposite boundary is the mirror image of this one:

\[u_{N_x,j}^{(n+1)} = u_{N_x-1,j}^{(n)} - \frac{1-\alpha}{1+\alpha}\left(u_{N_x-1,j}^{(n+1)} - u_{N_x,j}^{(n)}\right).\]

A short warning: the one-way equations are exact only for waves that meet the boundary head-on. A plane wave arriving at an angle \(\theta\) to the normal is partly reflected, with an amplitude reflection coefficient of

\[R = \frac{1 - \cos\theta}{1 + \cos\theta},\]

which is 0.17 at 45° and 0.33 at 60°, and approaches 1 at grazing incidence; the class below reflects pulses by about these amounts (0.16 at 45° and 0.36 at 60°). Engquist and Majda's second-order condition, for which \(R\) is squared, and absorbing layers around the grid, such as the perfectly matched layer, reflect less, but are more complicated to implement.

Implementation

The class WaveEqn2D below implements this scheme, with either boundary condition. It can also hold the displacement at zero at points inside the grid, which then reflect waves like the Dirichlet boundary: these obstacles make the wall in the double slit below. The displacements at the three time steps are held in three arrays, u_prev, u and u_next, indexed by \(j\) and then \(i\) (\(y\) and then \(x\)), the order in which Matplotlib's imshow draws an array. After each time step, the arrays are relabelled rather than copied: the array that held time step \(n-1\) is no longer needed, and is reused for the next \(n+1\). With the Mur condition, the corners of the grid take their values from the points next to them on the left and right edges. The programs below import the class from a file named wave_eqn2d.py.

wave_eqn2d.py
"""A finite-difference solution of the two-dimensional wave equation, with
reflecting (Dirichlet) or absorbing (Mur) boundary conditions."""

import numpy as np


class WaveEqn2D:
    """The wave equation on a grid of nx by ny points."""

    def __init__(self, nx=200, ny=200, c=0.5, h=1, dt=1, use_mur_abc=True,
                 obstacle=None):
        """Initialise the simulation.

        nx and ny are the numbers of grid points in the x and y directions;
        c is the wave speed; h is the grid spacing and dt the time step.
        If use_mur_abc is True, the Mur absorbing boundary condition is used at
        the edges of the grid; if False, the Dirichlet (reflecting) boundary
        condition, u = 0. obstacle, if given, is a boolean array of shape
        (ny, nx) that is True at the points held at u = 0, which reflect waves.

        """
        self.nx, self.ny = nx, ny
        self.c, self.h, self.dt = c, h, dt
        # The Courant number, which must not exceed 1/sqrt(2).
        self.alpha = c * dt / h
        if self.alpha > 1 / np.sqrt(2):
            raise ValueError(f"c * dt / h = {self.alpha:.3g} exceeds the"
                             " stability limit, 1/sqrt(2)")
        self.use_mur_abc = use_mur_abc
        self.obstacle = obstacle
        # The displacement at time steps n-1, n and n+1, indexed [j, i]: that
        # is, by y and then by x.
        self.u_prev, self.u, self.u_next = np.zeros((3, ny, nx))
        self.t = 0

    def update(self):
        """Advance the simulation by one time step."""
        u_prev, u, u_next = self.u_prev, self.u, self.u_next

        # The interior points, from the five-point stencil.
        u_next[1:-1, 1:-1] = (2 * u[1:-1, 1:-1] - u_prev[1:-1, 1:-1]
                              + self.alpha**2 * (u[:-2, 1:-1] + u[2:, 1:-1]
                                                 + u[1:-1, :-2] + u[1:-1, 2:]
                                                 - 4 * u[1:-1, 1:-1]))

        if self.use_mur_abc:
            # The Mur absorbing boundary condition: each edge point is found
            # from its neighbour just inside the grid. The columns are done
            # first, so that the rows include the corners, which take their
            # values from the points next to them on the columns.
            kappa = (1 - self.alpha) / (1 + self.alpha)
            for edge, inner in ((np.s_[1:-1, 0], np.s_[1:-1, 1]),
                                (np.s_[1:-1, -1], np.s_[1:-1, -2]),
                                (np.s_[0, :], np.s_[1, :]),
                                (np.s_[-1, :], np.s_[-2, :])):
                u_next[edge] = u[inner] - kappa * (u_next[inner] - u[edge])
        else:
            # The Dirichlet boundary condition.
            u_next[0, :] = u_next[-1, :] = u_next[:, 0] = u_next[:, -1] = 0

        if self.obstacle is not None:
            u_next[self.obstacle] = 0

        # Time step n+1 becomes n, and n becomes n-1; the array that held n-1
        # is reused for the next n+1.
        self.u_prev, self.u, self.u_next = u, u_next, u_prev
        self.t += self.dt

Oscillating source

The first program holds the displacement at the centre of a grid of 160 × 160 points at \(A\sin\omega t\), with a period, \(T = 2\pi/\omega\), of 32 time steps. With the default values \(c = 0.5\) and \(h = \Delta t = 1\), for which \(\alpha = 0.5\), the wavelength, \(cT\), is 16 grid spacings. The program runs two simulations side by side, with the Dirichlet and Mur boundary conditions. The displacement is drawn on a diverging colour map, symmetric about zero, so that crests (red) and troughs (blue) are equally visible; it is clipped at \(\pm 0.15A\), since the amplitude near the source is much larger than elsewhere.

sine_source.py
"""Waves from an oscillating point source at the centre of the grid, with the
Dirichlet and Mur boundary conditions side by side."""

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation

from wave_eqn2d import WaveEqn2D

nx = ny = 160
# The amplitude and period (in time steps) of the source: with c = 0.5, the
# wavelength is 16 grid spacings.
A, T = 1, 32
omega = 2 * np.pi / T
# The colour map is clipped at +/- vmax, since the amplitude is much larger
# near the source than elsewhere.
vmax = 0.15 * A
steps_per_frame, nframes = 4, 120


def step(sim):
    """Hold the displacement at the centre at A sin(omega t) and advance the
    simulation by one time step."""
    sim.u[ny // 2, nx // 2] = A * np.sin(omega * sim.t)
    sim.update()


if __name__ == "__main__":
    sims = [WaveEqn2D(nx, ny, c=0.5, use_mur_abc=False),
            WaveEqn2D(nx, ny, c=0.5, use_mur_abc=True)]
    fig, axes = plt.subplots(1, 2, figsize=(10, 5.4), layout="constrained")
    images = []
    for ax, sim, title in zip(axes, sims, ("Dirichlet", "Mur")):
        images.append(ax.imshow(sim.u, cmap="RdBu_r", vmin=-vmax, vmax=vmax))
        ax.set_title(title)
        ax.set_xticks([])
        ax.set_yticks([])

    def animate(frame):
        """Advance both simulations and draw their displacements."""
        for sim, image in zip(sims, images):
            for _ in range(steps_per_frame):
                step(sim)
            image.set_data(sim.u)
        return images

    # interval is the time between frames, in milliseconds.
    anim = FuncAnimation(fig, animate, frames=nframes, interval=40, blit=True,
                         repeat=False)
    plt.show()
Two square panels of waves spreading from a point at the centre, as alternating red and blue rings. On the left, labelled Dirichlet (reflecting), the rings are reflected from the edges and break up into a chequered pattern of interference; on the right, labelled Mur (absorbing), the rings pass out through the edges and stay circular.
Waves from an oscillating point source, with the Dirichlet (left) and Mur (right) boundary conditions. Crests are red and troughs blue.

With the Dirichlet condition, the waves are reflected from the edges and interfere with those still arriving from the source, and the pattern becomes ever more complicated, since none of the waves' energy can leave. With the Mur condition, the waves leave the grid with little trace: the reflections near the corners, where the waves meet the edges obliquely, are too faint to see on this colour scale.

Raindrops

The second program drops raindrops at random on a pond: at each time step, with a probability of 0.04, it adds a drop with a Gaussian profile, \(\exp(-r^2/w^2)\) with \(w = 3\) grid spacings, at a random point. The drop is added to the displacements at both the current and previous time steps, so that it starts at rest. Its profile is calculated out to \(3w\) from its centre, where it has fallen to about \(10^{-4}\) of its height, since cutting it off sooner would leave a step at its edge; a step, or a narrower drop, contains wavelengths too short for the grid to represent accurately, which lag behind the ring as a train of ripples. The Mur condition lets the ripples leave the pond as though it were much larger. A short warning: real raindrops make ripples whose wavelengths are short compared with the depth of the water, which are dispersive, and so this is an impression of the effect rather than a simulation of it.

raindrops.py
"""Raindrops falling at random on a pond, each an initial displacement with a
Gaussian profile."""

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation

from wave_eqn2d import WaveEqn2D

nx = ny = 200
# The probability of a drop at each time step, and the height and width, w,
# of each drop's profile, exp(-r^2 / w^2).
drop_probability, drop_height, drop_width = 0.04, 1, 3
# The profile is calculated out to 3w from its centre, where it has fallen to
# about 1e-4 of its height: a square of 2m + 1 grid points.
m = 3 * drop_width
x = np.arange(-m, m + 1)
X, Y = np.meshgrid(x, x)
drop = drop_height * np.exp(-(X**2 + Y**2) / drop_width**2)
vmax = 0.2 * drop_height
steps_per_frame, nframes = 3, 150


def step(sim, rng):
    """Perhaps add a drop at a random position, then advance the simulation by
    one time step."""
    if rng.random() < drop_probability:
        i, j = rng.integers(m + 1, nx - m - 1), rng.integers(m + 1, ny - m - 1)
        region = np.s_[j - m:j + m + 1, i - m:i + m + 1]
        # Adding the drop at both the current and previous time steps means
        # that it starts at rest.
        sim.u[region] += drop
        sim.u_prev[region] += drop
    sim.update()


if __name__ == "__main__":
    rng = np.random.default_rng()
    sim = WaveEqn2D(nx, ny, c=0.5, use_mur_abc=True)
    fig, ax = plt.subplots(figsize=(6, 6), layout="constrained")
    ax.axis("off")
    image = ax.imshow(sim.u, cmap="Blues_r", vmin=-vmax, vmax=vmax)

    def animate(frame):
        """Advance the simulation and draw its displacement."""
        for _ in range(steps_per_frame):
            step(sim, rng)
        image.set_data(sim.u)
        return (image,)

    anim = FuncAnimation(fig, animate, frames=nframes, interval=40, blit=True,
                         repeat=False)
    plt.show()
Expanding rings, pale at their crests and dark in their troughs, spreading and crossing on a blue surface as new drops land at random points.
Raindrops falling at random on a pond with absorbing (Mur) edges.

Double slit

Obstacles inside the grid make it possible to simulate diffraction (the spreading of waves through an aperture) and interference. The third program sends a plane wave with a wavelength, \(\lambda\), of 16 grid spacings at a wall with two slits, each 8 grid spacings wide and \(d = 64\) apart, centre to centre.

The plane wave is not made by holding the displacement along a line, as for the point source above, since the waves reflected from the wall would then be reflected again from the line, and would resonate between them. Instead, at each time step the program adds \(2\alpha[W(t + \Delta t) - W(t)]\) to the displacement along the line \(x = 20h\), which launches plane waves with the displacement \(W(t) = A\sin\omega t\) in both directions, but lets the waves reflected from the wall pass through it, to be absorbed by the edge behind it. This is a soft source, unlike the hard source above. The factor of \(2\alpha\) arises because adding \(\delta\) to the displacement at one time step gives the line a velocity \(\delta/\Delta t\), an impulse that, in one dimension, sets off a step of height \(\delta/(2\alpha)\) in each direction; on the grid, the amplitude of the plane waves is 2% larger than \(A\). The source's amplitude falls smoothly to zero over 50 grid points at each end, so that the plane wave does not run along the top and bottom edges, at the grazing incidence at which the Mur condition reflects strongly.

double_slit.py
"""A plane wave diffracted by two slits in a wall."""

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation

from wave_eqn2d import WaveEqn2D

nx, ny = 360, 200
# The amplitude and period (in time steps) of the plane wave: with c = 0.5,
# the wavelength is 16 grid spacings.
A, T = 1, 32
omega = 2 * np.pi / T
# The positions of the source line and the wall, the wall's thickness, and the
# width and separation (centre to centre) of the slits, in grid spacings.
xs, xw, wall_thickness = 20, 70, 3
slit_width, slit_separation = 8, 64
vmax = 0.5 * A
steps_per_frame, nframes = 4, 400

wall = np.zeros((ny, nx), dtype=bool)
wall[:, xw:xw + wall_thickness] = True
for yc in (ny - slit_separation) // 2, (ny + slit_separation) // 2:
    wall[yc - slit_width // 2:yc + slit_width // 2, xw:xw + wall_thickness] = False

# The source's amplitude falls smoothly to zero over 50 grid points at each
# end, so that the plane wave does not run along the top and bottom edges.
y = np.arange(ny)
profile = np.sin(np.pi / 2 * np.clip(np.minimum(y, ny - 1 - y) / 50, 0, 1))**2


def W(t):
    """The displacement of the plane wave at the source line at time t."""
    return A * np.sin(omega * t)


def step(sim):
    """Add the soft source's increment along the line x = xs, then advance
    the simulation by one time step."""
    sim.u[:, xs] += 2 * sim.alpha * (W(sim.t + sim.dt) - W(sim.t)) * profile
    sim.update()


if __name__ == "__main__":
    sim = WaveEqn2D(nx, ny, c=0.5, use_mur_abc=True, obstacle=wall)
    fig, ax = plt.subplots(figsize=(9, 5.4), layout="constrained")
    ax.axis("off")
    image = ax.imshow(sim.u, cmap="RdBu_r", vmin=-vmax, vmax=vmax)
    # The wall, in black, drawn over the displacement in each frame.
    wall_image = ax.imshow(np.ma.masked_where(~wall, wall), cmap="gray_r",
                           vmin=0, vmax=1)

    def animate(frame):
        """Advance the simulation and draw its displacement."""
        for _ in range(steps_per_frame):
            step(sim)
        image.set_data(sim.u)
        return image, wall_image

    anim = FuncAnimation(fig, animate, frames=nframes, interval=40, blit=True,
                         repeat=False)
    plt.show()
On the left, a plane wave of vertical red and blue stripes meets a black vertical wall with two small gaps. To the right of the wall, semicircular waves spread from each gap and overlap, forming a fan of bands of strong waves separated by faint lines along which the displacement stays close to zero.
A plane wave diffracted by two slits: one period of the waves once they have filled the grid, which repeats. Crests are red and troughs blue.

To the left of the wall, the plane wave and its reflection form a standing wave of about twice its amplitude, which saturates the colour map. Beyond the wall, the waves spreading from the two slits interfere. Along directions at an angle \(\theta\) to the axis for which the paths from the two slits differ by a whole number of wavelengths, \(d\sin\theta = m\lambda\), their crests coincide; between these, along the nodal lines where \(d\sin\theta = (m + \frac{1}{2})\lambda\), a crest from one slit meets a trough from the other, and the displacement stays close to zero. With \(d = 4\lambda\), the nodal lines are at 7.2°, 22.0° and 38.7° on either side of the axis. In the simulation, the mean of \(u^2\) over time on an arc 150 grid spacings from the slits has its minima at 7.6°, 22.5° and 39.8°: slightly further from the axis, as expected at a distance less than \(d^2/\lambda = 256\) grid spacings, beyond which the paths from the two slits are effectively parallel.

Comments

Leave a comment

Optional, and never shown: only the moderator sees it.

Comments are written in Markdown (code between ``` lines) and appear once approved. Your name and comment are published; your email address, if you give one, is seen only by the moderator.