A Byte of PhysicsLogo

Waves as propagating data

A wave is a disturbance whose state varies across position and time. A graph of that state is only a snapshot. For a stretched string, the physical state includes transverse displacement and velocity everywhere; a numerical model stores approximations to those fields on a grid.

Traveling-wave form

A right-moving waveform with shape function \(f\) can be written

\[y(x,t)=f(x-ct)\]

and a left-moving waveform is

\[y(x,t)=g(x+ct)\]

At a later time, the shape is translated by distance \(c\Delta t\). The medium's material does not travel that full distance with the pattern; string elements move transversely while the disturbance moves along the string.

A sinusoidal right-moving wave is

\[y(x,t)=A\cos(kx-\omega t+\phi)\]

with amplitude \(A\), wave number \(k\), angular frequency \(\omega\), and phase \(\phi\).

Wavelength, frequency, and speed

The spatial and temporal parameters obey

\[k=\frac{2\pi}{\lambda}\qquad\omega=2\pi f\]

Keeping the phase fixed and differentiating gives phase speed

\[c=\frac{\omega}{k}=\lambda f\]

Changing amplitude does not change wave speed in the ideal linear string model. Changing tension or mass density does. In a dispersive medium, \(\omega/k\) can depend on wave number and a packet may change shape.

The one-dimensional wave equation

Small transverse displacement of a uniform ideal string satisfies

\[\frac{\partial^2y}{\partial t^2}=c^2\frac{\partial^2y}{\partial x^2}\]

The time curvature of displacement is proportional to spatial curvature. A straight locally sloped segment has no transverse acceleration in this approximation; a curved segment has an imbalance of tension that accelerates it toward reduced curvature.

For string tension \(T\) and linear mass density \(\mu\),

\[c=\sqrt{\frac{T}{\mu}}\]

This assumes small slopes, uniform tension and density, negligible bending stiffness, and no dissipation.

Initial data require two fields

Because the wave equation is second order in time, specify

\[y(x,0)=y_0(x)\qquad\frac{\partial y}{\partial t}(x,0)=v_0(x)\]

A displacement snapshot alone does not tell whether a pulse moves left, moves right, or splits. The compatible initial velocity distinguishes those cases. For a pure right-moving shape,

\[v_0(x)=-c\frac{dy_0}{dx}\]

whereas the sign reverses for a pure left-moving wave.

import numpy as np

x = np.linspace(0, 1, 101)
dx, speed = x[1] - x[0], 1.0
dt = 0.5 * dx / speed
current = np.sin(np.pi * x)
velocity = np.zeros_like(x)
print("Courant number:", speed * dt / dx)

Discretize spatial curvature

On a uniform grid with spacing \(\Delta x\), approximate the second derivative at interior index \(i\) by

\[\left.\frac{\partial^2y}{\partial x^2}\right|_i\approx\frac{y_{i+1}-2y_i+y_{i-1}}{\Delta x^2}\]

Therefore grid acceleration is

\[a_i=c^2\frac{y_{i+1}-2y_i+y_{i-1}}{\Delta x^2}\]
acceleration = np.zeros_like(current)
acceleration[1:-1] = speed**2 * (current[2:] - 2 * current[1:-1] + current[:-2]) / dx**2
print("Midpoint acceleration:", acceleration[50])

Compute all accelerations from the same displacement snapshot. Updating one grid point before its neighbor creates directional order bias.

A centered time update

Applying a centered second difference in time gives

\[y_i^{n+1}=2y_i^n-y_i^{n-1}+C^2(y_{i+1}^n-2y_i^n+y_{i-1}^n)\]

where Courant number is

\[C=\frac{c\Delta t}{\Delta x}\]

For this standard one-dimensional scheme, stability requires \(C\leq1\). The equality case has special properties for ideal grid-aligned propagation, but boundaries, heterogeneous media, and other terms can impose additional limits.

courant = speed * dt / dx
assert courant <= 1
previous = current - dt * velocity + 0.5 * dt**2 * acceleration
for _ in range(100):
    following = np.zeros_like(current)
    following[1:-1] = (
        2 * current[1:-1]
        - previous[1:-1]
        + courant**2 * (current[2:] - 2 * current[1:-1] + current[:-2])
    )
    previous, current = current, following
print("Midpoint displacement after 0.5 s:", current[50])

The first time level must be initialized consistently from both displacement and velocity, often using a Taylor expansion including initial acceleration.

Boundaries determine reflections

A fixed endpoint enforces \(y=0\) and reflects a displacement pulse with inversion. An ideal free endpoint enforces zero spatial slope and reflects without displacement inversion. Periodic boundaries make the domain wrap around. An absorbing boundary tries to let outgoing waves leave with minimal reflection but is only approximate over specified frequencies and angles.

Apply the boundary rule at every required time level and include it in the energy ledger. A driven endpoint supplies energy and is not a closed boundary.

Sampling and resolvable wavelength

A grid cannot represent arbitrary short wavelengths. Nyquist sampling requires at least two samples per wavelength merely to distinguish a sinusoid, while accurate numerical derivatives usually need substantially more. Components near the grid limit travel at the wrong numerical speed and can alias.

Similarly, output sampling must resolve fast enough to capture temporal frequency. Internal time step, saved-output interval, and display refresh rate are different quantities. A slow display can skip frames without changing the physics; a slow solver step changes the solution.

Numerical dispersion

The continuous ideal string has nondispersive relation

\[\omega=ck\]

The centered discrete scheme instead obeys a trigonometric numerical relation, so short grid wavelengths have phase speed different from \(c\). A pulse containing many wave numbers can spread even when the continuous model would preserve its shape.

Refining the grid while maintaining a suitable Courant number should reduce this error for a fixed physical waveform. If spreading does not converge away, it may be physical dispersion or another model term.

Energy as a diagnostic

For an ideal string, energy density is

\[u=\frac12\mu\left(\frac{\partial y}{\partial t}\right)^2+\frac12T\left(\frac{\partial y}{\partial x}\right)^2\]

Sum a consistent discrete version over the grid. In a closed lossless system, energy should remain within the behavior expected of the chosen method. Changes should be explained by boundary work, damping, or numerical error.

Verification sequence

First evaluate an analytic sinusoid at grid points and verify wavelength, frequency, direction, and phase speed. Then test a numerical sinusoidal mode or smooth pulse. Measure arrival time at fixed probes, amplitude, phase, boundary reflection, and energy.

Repeat with half spatial spacing and an appropriately reduced time step. Compare values at the same physical positions and times. A stable line on screen is not enough: wrong wave speed, artificial damping, and grid dispersion can all look smooth.

Reliable propagating data therefore includes the continuous model, initial fields, boundary conditions, grid, update, stability limit, and convergence evidence. Rendering is only one readable view of that data.

Distinguishing particle motion from wave motion

For a transverse string wave, a material point moves mainly perpendicular to the direction in which the pattern travels. For a longitudinal sound wave, material elements oscillate mainly parallel to propagation. In both cases, the medium usually oscillates about equilibrium while energy and phase travel through it. A plotted crest is not a tagged piece of material.

This distinction affects stored data. A field sample at fixed grid position is Eulerian: it reports what happens at that location over time. A marker attached to a particular material element follows a Lagrangian trajectory. Mixing the two descriptions can create false claims about transport speed. Name whether an output follows a location, a phase feature, a wave packet, or a material marker.

Measuring propagation speed

Choose two probes separated by a known physical distance and identify the same waveform feature at each. Propagation speed is distance divided by arrival-time difference. For a sinusoid, phase ambiguity can shift arrival by an integer number of periods, so use a localized pulse, cross-correlation, or a known phase-unwrapping rule.

A grid calculation should be compared at multiple probe separations. If estimated speed depends strongly on distance, the waveform may be dispersing or the event detector may be biased. Record probe positions, interpolation, threshold, and sampling interval.

At a material discontinuity, incident, reflected, and transmitted waves can overlap. Measure each in a time window or spatial region where it is separable. The first visible sample above a threshold is sensitive to noise and output interval; fitting or interpolating a well-defined feature gives a more reproducible arrival time.

Inhomogeneous and lossy media

If tension or linear density varies with position, local wave speed changes and partial reflection occurs at gradients or interfaces. The simple constant-speed traveling form no longer describes the entire domain. Discretize the force balance in a form that treats spatially varying coefficients consistently rather than inserting a different speed into an otherwise uniform update without derivation.

Damping removes wave energy and can depend on frequency. Physical attenuation should persist under grid refinement, while numerical attenuation should decrease toward the method's continuum limit. Run an undamped reference with identical resolution to separate the two effects.

A worked Python notebook

Represent a fixed-end string in its first spatial mode on a one metre interval. The question for this calculation is precise: how does initial displacement change when we change position, while keeping the other choices fixed? The earlier sections explain the physical relationship. Here we turn one part of that relationship into a calculation that you can run, inspect, and change in Google Colab.

The initial velocity is a separate field and is set to zero in the accompanying example. Keep that sentence beside the results. A formula can return a number outside its useful range, and a plotting library will usually draw that number without asking whether the physical assumptions still hold. The selected interval is from 0 to 1 m. It gives us a specific domain to discuss instead of leaving the graph's range to a software default.

Use the notebook link above the lesson, run the setup cell, and then run the cells in order. The code below is also included there. NumPy handles the arrays of numerical values, SymPy keeps the equation symbolic, and Matplotlib draws the results. If these libraries or notebook cells are unfamiliar, start with Your first physics notebook.

State the relationship before choosing a graph

In this small example, q stands for position, expressed in m. The output is initial displacement, expressed in m. The equation below uses the numerical values in those units. Any fixed coefficients therefore carry the units needed to make the relation consistent. A value supplied in another unit must be converted before it enters this expression.

\[f(q) = \sin{\left(\pi q \right)}\]

This is a function of one changing input. It is not a statement that the physical system has only one variable. We deliberately hold the other inputs fixed so that one cause of variation is visible. Changing several inputs at once would make it harder to tell which change produced the output difference. Write down the held-fixed choices before trying a different experiment.

At 0.25 m, the expression gives 0.707107 m. This is our reference calculation. It is a prediction of the stated example, not a new measurement. Its displayed digits help us compare implementations. They should not be read as a claim that physical inputs are known to six significant figures.

import numpy as np
import sympy as sp
import matplotlib.pyplot as plt

q = sp.Symbol("q", real=True)
expression = sp.sympify("sin(pi*q)", locals={"q": q})
reference_input = 0.25
reference_output = float(expression.subs(q, reference_input))
print("Input:", reference_input, "m")
print("Predicted initial displacement:", reference_output, "m")

sp.Symbol declares a mathematical symbol. It does not assign a numerical measurement to that symbol. subs then replaces the symbol with our chosen input, and float converts the resulting symbolic number into a standard Python numerical value. Keeping these steps separate lets us inspect the equation before numerical substitution. It also prevents a later plot from becoming the only surviving record of the model.

Compare a few cases you can explain

Before drawing hundreds of points, calculate three. The lower endpoint gives 0 m. The midpoint, at 0.5 m, gives 1 m. The upper endpoint gives 0 m. Read these together with the assumptions: they describe different choices of position within the same example, with the other inputs held fixed.

These three values are a useful first check, but they do not establish the shape between them. Two endpoints can be equal even when the curve bends or oscillates in between. Likewise, a large change between endpoints does not tell us whether the relationship is linear. We need the equation and intermediate samples to answer those questions.

evaluate = sp.lambdify(q, expression, modules="numpy")
inputs = np.array([0.0, 0.5, 1.0])
outputs = np.asarray(evaluate(inputs), dtype=float)
outputs = np.broadcast_to(outputs, inputs.shape)
for input_value, output_value in zip(inputs, outputs):
    print(f"{input_value:.6g} m -> {output_value:.6g} m")
assert np.all(np.isfinite(outputs))

lambdify turns the symbolic expression into a numerical function. We explicitly select NumPy as its numerical backend so it can accept an array. The same expression now has two useful forms: one for algebra and one for calculating many cases. The assertion checks that the chosen inputs produce finite outputs. It would catch an infinity or an undefined numerical result, but a finite value can still be physically inappropriate.

Make a graph that answers the question

The horizontal axis shows position; the vertical axis shows initial displacement. Every plotted point is a prediction of the same expression. We mark the reference case separately so that a reader can connect the earlier printed value to its place on the curve. The axis labels include units because a shape without a scale cannot tell us the size of a physical effect.

input_grid = np.linspace(0.0, 1.0, 301)
output_grid = np.asarray(evaluate(input_grid), dtype=float)
output_grid = np.broadcast_to(output_grid, input_grid.shape)
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(input_grid, output_grid, label="Stated model")
ax.scatter([reference_input], [reference_output], label="Reference case", zorder=3)
ax.set_xlabel("Position (m)")
ax.set_ylabel("Initial displacement (m)")
ax.legend()
ax.grid(alpha=0.25)
fig.tight_layout()
plt.show()

Look for a sign change, a turning point, or a region where the curve becomes steep. Connect each feature to the expression rather than to the colour of the line. If the curve has a minimum or maximum, changing the input in opposite directions may have similar effects on the output near that point. If it is nearly straight over a short interval, a local linear approximation may be useful even when the complete expression is nonlinear.

Increasing the number of samples makes the line smoother and may reveal features that a coarse grid missed. It does not improve the physical inputs or enlarge the model's validity range. For quantities that can take only discrete values, use the line as a guide to the relationship and interpret only the allowed input values. A plotting function does not enforce such restrictions for you.

Measure the local sensitivity

A derivative asks a more specific question than the whole graph: how quickly does initial displacement change near the reference input? Its units are the output unit divided by the input unit. For this calculation, the derivative at 0.25 m is 2.22144 in those ratio units. Locally, the output increases as the input increases. This statement is local; the sign or size of the slope can be different elsewhere on the curve.

\[f'(q) = \pi \cos{\left(\pi q \right)}\]

For a small input change, multiply the derivative by that change to estimate the output change. Then compare that estimate with a fresh evaluation of the full expression. The distinction between these two calculations matters: the derivative gives a tangent approximation, while substitution evaluates the chosen expression at the new point.

slope_expression = sp.diff(expression, q)
slope_at_reference = float(slope_expression.subs(q, reference_input))
changed_input = 0.255
linear_prediction = reference_output + slope_at_reference * (
    changed_input - reference_input
)
full_prediction = float(evaluate(changed_input))
print("Symbolic derivative:", slope_expression)
print("Tangent prediction:", linear_prediction, "m")
print("Full expression:", full_prediction, "m")
print("Approximation difference:", full_prediction - linear_prediction, "m")

Here the changed input is 0.255 m. The tangent estimate is 0.718214 m, while the full expression gives 0.718126 m. If the two values are close, it means the chosen input change is small enough for this local approximation at this point. It does not mean the entire model is linear. If the slope is zero, a quadratic or higher-order term may supply the leading change instead.

This is also the beginning of uncertainty propagation. If the input has a small stated standard uncertainty, the magnitude of the slope times that uncertainty estimates one contribution to output uncertainty. Do not automatically use the same rule for a wide interval, a discontinuity, a turning point with zero first derivative, or several correlated uncertain inputs. Those situations need more of the model than one slope.

Check the derivative with numerical differences

We can estimate the same slope from values on either side of the reference point. Subtract the lower output from the upper output and divide by twice the input step. Parentheses are essential: the entire output difference must be divided by the entire input interval. Without them, Python can execute a different mathematical expression while still producing a plausible number.

The calculation below uses three decreasing step sizes. Each estimate is compared with the symbolic derivative, so the reference is independent of the numerical difference formula. Near an endpoint, it is acceptable here to evaluate a small extension only because the displayed mathematical expression is smooth there; such a check does not assert that extrapolated values describe additional physical cases.

input_span = 1.0
for fraction in [1e-2, 1e-3, 1e-4]:
    step = input_span * fraction
    upper = float(evaluate(reference_input + step))
    lower = float(evaluate(reference_input - step))
    numerical_slope = (upper - lower) / (2 * step)
    difference = numerical_slope - slope_at_reference
    print(f"step={step:.6g}: slope={numerical_slope:.6g}, difference={difference:.6g}")

For a smooth function, reducing the step often reduces the approximation error at first. Very small steps can eventually make subtraction of nearly equal floating-point values less reliable. Therefore “smaller” is not an unlimited guarantee of “better.” Compare the observed behaviour over a useful range of steps instead of choosing the smallest number the computer can represent.

An absolute slope difference is useful when the expected slope is near zero. A relative difference would divide by a very small reference and could look enormous even when the absolute discrepancy is tiny. Away from zero, a relative difference can help compare quantities with very different scales. The tolerance should reflect the question and the numerical method, rather than a universal decimal threshold copied into every test.

Change the example and preserve the reasoning

Make one copy of the reference calculation before editing it. Choose a second value of position inside the stated interval, predict whether initial displacement will rise or fall, and then evaluate the expression. Place the prediction and the result in a text cell. If they disagree, identify whether the mistake was in the sign, the unit conversion, the algebra, or the assumption about how the curve behaves.

Next choose a shorter plotting interval around the reference point. Compare the local curve with its tangent approximation. Then widen the interval again. The difference shows why a useful local estimate need not describe the whole range. Keep the axis labels and numerical scale visible when comparing the plots; automatic axis limits can make two different effects appear equally large.

Finally, return to the physical limit stated at the start: The initial velocity is a separate field and is set to zero in the accompanying example. Describe one change to the setup that would violate that limit. State what new input, equation, or observation would be needed before trusting an answer in the changed situation. This last step connects the Python experiment to the physics instead of treating successful execution as the only criterion for a useful result.

Before saving, restart the runtime and run all cells in order. A result that depends on an earlier, now-deleted input cell is not reproducible from the saved notebook. Keep unrounded values for later calculations, round only the reported output, and label any new data as measured, assumed, or generated. The graph and printed values should remain traceable to the same expression and the same choices of inputs.

Recover the output change by integrating the slope

There is another way to check that the expression and its derivative describe the same relationship. Add up the small output changes predicted by the slope across the chosen input interval. In the continuous limit, this integral equals the output at the upper endpoint minus the output at the lower endpoint. The result has units of m: the input unit in the integration cancels the input unit in the denominator of the slope.

This statement is about the mathematics of this particular relationship. It does not assign a new physical meaning to an arbitrary area under a graph. For example, an area under force versus distance represents work, while an area under a different pair of quantities may represent something else or have no standard name. Always carry the axis units through the calculation before naming an integral.

slope_function = sp.lambdify(q, slope_expression, modules="numpy")
endpoint_change = float(evaluate(1.0) - evaluate(0.0))
for points in [101, 201, 401]:
    grid = np.linspace(0.0, 1.0, points)
    slopes = np.asarray(slope_function(grid), dtype=float)
    slopes = np.broadcast_to(slopes, grid.shape)
    integrated_change = np.trapezoid(slopes, grid)
    print(
        points,
        "integrated change:",
        integrated_change,
        "endpoint change:",
        endpoint_change,
    )

The trapezoidal rule joins neighbouring slope samples with straight segments and adds their signed areas. A negative contribution remains negative; replacing every slope by its magnitude would calculate a different quantity. Increasing the sample count provides a practical refinement check. If the values do not settle toward the endpoint difference, first inspect the interval, singularities, and array ordering.

Do not conclude that two agreeing calculations prove the model is physically complete. Both use the same selected relationship, so an omitted effect would be omitted from both. Their agreement is evidence that the numerical tools implement that relationship consistently. Comparing with an independent experiment or a more appropriate physical model is a separate test.

Keep this comparison in the notebook when you change the expression. It is particularly useful after adding a coefficient, changing a sign convention, or converting an input unit. A code cell that produces a smooth graph can conceal these mistakes; a second calculation of the same output change gives you another place to notice them.

Sources


Share to: