A Byte of PhysicsLogo

Fourier transform

A Fourier series describes a periodic function with discrete harmonics. A Fourier transform extends the same idea to a nonperiodic function: instead of a countable list of harmonics, it uses a continuous range of frequencies or wave numbers. Measurements and computer arrays are finite, so practical work also needs the discrete Fourier transform and a careful map from its indices to physical frequencies.

Continuous transform pair

For a time signal \(x(t)\), one frequency-in-hertz convention is

\[X(f)=\int_{-\infty}^{\infty}x(t)e^{-i2\pi ft}\,dt\]

with inverse

\[x(t)=\int_{-\infty}^{\infty}X(f)e^{i2\pi ft}\,df\]

The exponential compares the signal with a sinusoid of frequency \(f\). The magnitude \(|X(f)|\) records strength, while the complex argument records phase. If \(x\) has units \(U\), then this convention makes \(X\) have units \(U\,\mathrm{s}\) because the integral includes \(dt\).

Another common convention uses angular frequency \(\omega=2\pi f\):

\[X(\omega)=\int_{-\infty}^{\infty}x(t)e^{-i\omega t}\,dt,\qquad x(t)=\frac{1}{2\pi}\int_{-\infty}^{\infty}X(\omega)e^{i\omega t}\,d\omega\]

Both are correct. Factors of \(2\pi\) move because the integration variable changed. Comparing formulas without first aligning their conventions creates apparent disagreements.

Transforming in space

For waves, position and wave number are often the transform variables:

\[\widetilde{\psi}(k)=\int_{-\infty}^{\infty}\psi(x)e^{-ikx}\,dx,\qquad \psi(x)=\frac{1}{2\pi}\int_{-\infty}^{\infty}\widetilde{\psi}(k)e^{ikx}\,dk\]

Here \(k\) has units of radians per length. Each component evolves according to a dispersion relation \(\omega(k)\). In a linear, translation-invariant system, the field can be propagated by multiplying each component by its phase factor:

\[\widetilde{\psi}(k,t)=\widetilde{\psi}(k,0)e^{-i\omega(k)t}\]

Then the inverse transform reconstructs the field. A nondispersive relation moves the packet without changing its ideal shape; a nonlinear relation in \(k\) generally changes relative phases and reshapes it.

The discrete Fourier transform

Suppose a measurement contains \(N\) uniform samples \(x_n\) separated by \(\Delta t\). A common DFT convention is

\[X_k=\sum_{n=0}^{N-1}x_n e^{-i2\pi kn/N},\qquad k=0,1,\ldots,N-1\]

and

\[x_n=\frac{1}{N}\sum_{k=0}^{N-1}X_k e^{i2\pi kn/N}\]

This DFT treats the finite sample array as one period of a periodic sequence. Its sample rate and bin spacing are

\[f_s=\frac{1}{\Delta t},\qquad \Delta f=\frac{f_s}{N}=\frac{1}{N\Delta t}\]

The record duration is \(N\Delta t\) if each of the \(N\) samples represents one uniform interval. Do not use \((N-1)\Delta t\) as the periodic record length when mapping DFT bins: that is only the time from the first sample to the final sample location.

For low nonnegative indices, \(f_k=kf_s/N\). Indices above the positive-frequency half conventionally wrap to \(f_k=(k-N)f_s/N\). For real inputs,

\[X_{N-k}=X_k^*\]

subject to the special self-conjugate DC bin and, for even \(N\), the Nyquist bin.

Direct DFT Python

import numpy as np

samples = np.array([1.0, 0.0, -1.0, 0.0])
N = len(samples)
spectrum = np.zeros(N, dtype=complex)
for frequency_index in range(N):
    for sample_index in range(N):
        phase = -2 * np.pi * frequency_index * sample_index / N
        spectrum[frequency_index] += samples[sample_index] * np.exp(1j * phase)
assert np.allclose(spectrum, np.fft.fft(samples))
print(spectrum)

This direct algorithm performs order \(N^2\) work. A fast Fourier transform commonly reduces this to order \(N\log N\). Use identical fixtures for both implementations.

Amplitude scaling and one-sided spectra

Under the stated forward convention, a constant array with value \(C\) has \(X_0=NC\). A cosine exactly aligned to a non-DC, non-Nyquist bin has two coefficients whose magnitudes are each \(NA/2\), where \(A\) is its peak amplitude.

A one-sided amplitude spectrum for a real signal often divides magnitudes by \(N\) and doubles positive frequencies whose negative partners were omitted. DC and the even-length Nyquist bin are not doubled. This rule depends on the exact transform and window normalization. Publishing a magnitude plot without those details makes its vertical scale ambiguous.

Aliasing and leakage

Uniform sampling cannot distinguish frequencies separated by integer multiples of the sample rate. Content above

\[f_{\mathrm{Nyquist}}=\frac{f_s}{2}\]

can appear at a lower alias frequency. Preventing aliasing requires limiting the analog input bandwidth before sampling, not merely deleting high DFT bins afterward.

Spectral leakage has a different cause. The DFT assumes the finite record repeats. If its end does not join smoothly to its beginning, that periodic continuation contains a jump and therefore broad frequency content. A sinusoid whose record contains a noninteger number of cycles spreads across bins.

Windowing tapers the record to reduce the artificial edge jump. It trades lower distant leakage for a wider main peak and changes amplitude calibration. Record the window, coherent gain, and effective noise bandwidth when quantitative results require them.

Convolution becomes multiplication

One reason transforms are so useful is the convolution theorem. For continuous signals,

\[\mathcal F\{x*h\}=X(f)H(f)\]

A linear time-invariant filter that convolves an input with impulse response \(h(t)\) therefore multiplies each frequency component by a transfer function \(H(f)\). Its magnitude changes component amplitudes and its phase changes component timing.

For finite DFT arrays, direct multiplication corresponds to circular convolution. Linear convolution requires zero-padding enough to prevent the wrapped tail from overlapping the beginning. Forgetting this distinction is a common source of mysterious edge artifacts.

Width in one representation limits width in the other

A narrow pulse needs a wide range of frequencies; a nearly monochromatic signal extends for a long time. With widths defined consistently, Fourier pairs satisfy an uncertainty relation. For angular frequency and standard deviations,

\[\sigma_t\sigma_\omega\ge\frac12\]

This is a mathematical property of Fourier transforms, not necessarily a statement about quantum measurement. A Gaussian reaches the minimum under the usual conventions. Other width definitions produce different numerical constants, so a claim about “bandwidth times duration” must define how both widths are measured.

Verification fixtures

Use inputs whose transforms are known. A constant populates DC. A single-sample impulse has equal magnitude in every bin. A bin-aligned real sine or cosine produces a conjugate pair. A shifted impulse keeps its flat magnitude but develops a linear phase pattern, showing why phase cannot be discarded.

reconstructed = np.fft.ifft(spectrum)
assert np.allclose(reconstructed.real, samples)
assert np.max(abs(reconstructed.imag)) < 1e-12
print("Round-trip error:", np.max(abs(reconstructed - samples)))

Check Parseval's relation for the chosen normalization, conjugate symmetry for real data, and physical bin mapping using a known sample rate. Then use an off-bin sinusoid to test leakage and an above-Nyquist input to test the predicted alias. Round-trip success proves the transform pair is internally consistent; the analytic fixtures test whether its conventions match the labels.

The DFT assumes uniform samples and a periodic finite record. Missing or irregular times, sensor jitter, clipping, noise, nonstationary content, and finite precision require additional methods or error models. A spectrum is an alternate representation of the available record, not access to frequencies the measurement never resolved.

A worked Python notebook

Use the analytic Fourier transform of a unit-width Gaussian as a smooth reference. The question for this calculation is precise: how does Gaussian transform amplitude change when we change angular frequency, 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 transform convention uses the negative exponential and no forward normalisation factor. 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 -4 to 4 scaled inverse-time units. 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 angular frequency, expressed in scaled inverse-time units. The output is Gaussian transform amplitude, expressed in scaled amplitude units. 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) = \sqrt{2} \sqrt{\pi} e^{- \frac{q^{2}}{2}}\]

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 1 scaled inverse-time units, the expression gives 1.52035 scaled amplitude units. 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("sqrt(2*pi)*exp(-q**2/2)", locals={"q": q})
reference_input = 1.0
reference_output = float(expression.subs(q, reference_input))
print("Input:", reference_input, "scaled inverse-time units")
print(
    "Predicted Gaussian transform amplitude:",
    reference_output,
    "scaled amplitude units",
)

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.00084088 scaled amplitude units. The midpoint, at 0 scaled inverse-time units, gives 2.50663 scaled amplitude units. The upper endpoint gives 0.00084088 scaled amplitude units. Read these together with the assumptions: they describe different choices of angular frequency 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([-4.0, 0.0, 4.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} scaled inverse-time units -> "
        f"{output_value:.6g} scaled amplitude units"
    )
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 angular frequency; the vertical axis shows Gaussian transform amplitude. 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(-4.0, 4.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("Angular frequency (scaled inverse-time units)")
ax.set_ylabel("Gaussian transform amplitude (scaled amplitude units)")
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 Gaussian transform amplitude change near the reference input? Its units are the output unit divided by the input unit. For this calculation, the derivative at 1 scaled inverse-time units is -1.52035 in those ratio units. Locally, the output decreases as the input increases. This statement is local; the sign or size of the slope can be different elsewhere on the curve.

\[f'(q) = - \sqrt{2} \sqrt{\pi} q e^{- \frac{q^{2}}{2}}\]

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 = 1.04
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, "scaled amplitude units")
print("Full expression:", full_prediction, "scaled amplitude units")
print(
    "Approximation difference:",
    full_prediction - linear_prediction,
    "scaled amplitude units",
)

Here the changed input is 1.04 scaled inverse-time units. The tangent estimate is 1.45953 scaled amplitude units, while the full expression gives 1.45957 scaled amplitude units. 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 = 8.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 angular frequency inside the stated interval, predict whether Gaussian transform amplitude 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 transform convention uses the negative exponential and no forward normalisation factor. 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 scaled amplitude units: 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(4.0) - evaluate(-4.0))
for points in [101, 201, 401]:
    grid = np.linspace(-4.0, 4.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: