Fourier analysis, from first principles
What a frequency is, why sinusoids and no other basis, how to derive any Fourier pair you need, why partial sums overshoot, and how to read the spectrum of an image. Part 1 of Seeing in frequencies: every step derived, with figures that run live on my own sketches.
Contents
- Notation and conventions
- 1. Start from what you trust: coordinates
- 2. Functions are vectors
- 3. Fourier series
- Negative frequencies are a direction of rotation
- The square wave, by hand
- 4. How good is a partial sum?
- In energy: always
- Pointwise: the Gibbs phenomenon
- Smoothness is decay
- 5. Why sinusoids? The real reason
- 6. From series to transform
- 7. Properties, each with a proof
- 8. Filters and what “frequency response” means
- 9. Images: the 2-D Fourier transform
- The projection–slice theorem
- 10. Amplitude versus phase
- 11. What Fourier cannot tell you
- 12. Implementation and caveats
- 13. Where it is used, and what is open
- Self-check
- References
Seeing in frequencies, part 1 of 4. Fourier analysis → the discrete Fourier world (sampling, the FFT, the uncertainty principle) → wavelets → wavelets for images. Two earlier posts, random wavelet features and Fourier and wavelets on the sphere, become the applied end of the series.
Here is the outline of a tree I drew, traced once around as a point in the complex plane. Every closed curve like it is a sum of circles: each circle turns at a whole number of turns per lap, and placed tip to tail, largest first, the last tip draws the tree.
One circle gets within 28% of the tree, twenty within 3.7%, a hundred within 0.6% (the error, in the corner, is the relative distance; Section 4 explains why it costs nothing to compute). By the end of this post you will be able to say exactly what those circles are, why circles and not some other shape, and what the same idea does to an image.
This post is for anyone in computer vision or applied mathematics who uses Fourier transforms and wants to understand them. It assumes calculus and a little linear algebra; every other step is derived, in folded proofs with numbered steps. The thread is one idea: a Fourier coefficient is a coordinate. Section 1 recalls what coordinates are. Sections 2 to 4 build the Fourier series and test how good it is. Section 5 answers the question most courses skip, why sinusoids. Sections 6 to 8 move to the Fourier transform, its properties and filters. Sections 9 and 10 do all of it for images, on four of my sketches. Section 11 is about what Fourier analysis cannot do, which is where the rest of the series begins.
Notation and conventions
| Symbol | Meaning |
|---|---|
| position or time; in 2-D | |
| frequency, in cycles per unit; in 2-D | |
| the Fourier basis on | |
| inner product | |
| Fourier coefficient | |
| partial sum | |
| Fourier transform | |
| convolution | |
| for , else | |
| , with |
Vectors are bold italic, matrices bold upright. Frequencies are in cycles per unit, not radians, so the transform and its inverse carry no stray factors of ; Section 6 has a table for translating to the convention used in many textbooks.
1. Start from what you trust: coordinates
Take a vector in the plane and two unit vectors at right angles. Three facts about them will carry the whole post.
Proposition 1 (Coordinates in an orthonormal basis)
If when and otherwise, then for every :
- its coordinates are inner products, ;
- it is rebuilt from them, ;
- its squared length is the sum of squared coordinates, .
Proof
Step 1. Write in the basis. Two orthonormal vectors in the plane span it, so for some numbers . This is fact 2, once we know what the are.
Step 2. Take the inner product with . By linearity, . The same with gives . This is fact 1.
Step 3. Expand the length. . This is fact 3: Pythagoras.
Example 1 (By hand)
Let , and . Then and . Rebuild: . Lengths: .
A coordinate is a shadow: drop a perpendicular from onto an axis and measure where it lands. Nothing in the three facts needed the plane or two dimensions, only an inner product and an orthonormal set. Fourier analysis is these three facts again, with functions in place of arrows.
2. Functions are vectors
Functions on add and scale like vectors: and . What they need to become geometry is an inner product.
Definition 1 (Inner product and norm of functions)
For square-integrable complex functions on ,
The set of functions with is called .
The bar on is there so that is real and non-negative, as a squared length must be. Think of as the dot product with infinitely many, densely packed coordinates .
Our basis will be the complex exponentials, and we need one fact about them first.
Definition 2 (The Fourier basis)
For each integer , .
Lemma 1 (Euler’s formula)
For real , .
Proof
Here , which converges for every complex and can be differentiated term by term, so and .
Step 1. A function that should be constant. Let .
Step 2. Differentiate with the product rule. .
Step 3. So is constant, equal to . Multiply by (using , which follows from the series): .
Proposition 2 (The eₖ are orthonormal)
if , and if .
Proof
Step 1. Multiply. with , an integer. (The conjugate of is .)
Step 2. If , the integrand is and .
Step 3. If , an antiderivative is , so , because for every integer .
Question 1
Why complex exponentials and not plain sines and cosines?
Answer
Both work. The real set is also orthonormal and gives the same expansions. A wave of one frequency has two numbers, an amplitude and a phase, and a complex coefficient stores exactly those two. The complex form is tidier for three reasons that appear below: products of exponentials add frequencies (); a shift multiplies by a constant (Section 5), where it would mix a sine with a cosine; and one formula covers every coefficient.
So what does a Fourier coefficient measure? By fact 1, it is the inner product : multiply the signal by a probe wave and add up the area. Try it.
The signal is . At the product stays mostly on one side of zero and the areas add; at any other whole number they cancel exactly. That cancellation is orthogonality. The inset shows moving in the complex plane as you slide : it sits at the origin for every integer except and , where it jumps out to a point whose length is half the wave’s amplitude and whose angle is its phase. Half, because the other half lives at , which is the subject of the next section.
3. Fourier series
Apply the three facts of Section 1 with replaced by .
Definition 3 (Fourier coefficients and partial sums)
For (extended periodically to the whole line),
The Fourier series of is the limit of as .
With infinitely many basis functions there is a new question: does the sum get back to ? Fact 2 needs care, and Section 4 answers it. Before that, two things the partial sum gets right for every .
Proposition 3 (The partial sum is the best approximation)
Among all trigonometric polynomials , the partial sum is the closest to :
Taking gives Bessel’s inequality, .
Proof
Step 1. The error is orthogonal to every with . , by orthonormality.
Step 2. So it is orthogonal to , which is the combination of those .
Step 3. Pythagoras. Write . Expanding , the two cross terms are inner products of orthogonal functions and vanish, leaving .
Step 4. The last term, by fact 3 for the orthonormal , is .
Step 5. Bessel. With (all ): .
Negative frequencies are a direction of rotation
Ask a room of engineers what a negative frequency is and someone will say a mathematical artefact. It is a direction of rotation. As increases, walks around the unit circle times per unit: anticlockwise if , clockwise if . A real oscillation moves back and forth on a line, and a single rotating point cannot do that. Two can, if they turn in opposite directions at the same speed.
Proposition 4 (A real signal pairs every frequency with its negative)
If is real-valued, then for every , the mean is real, and each pair of terms is one real wave:
Equivalently, with and .
Proof
Step 1. Conjugate the definition. The conjugate of an integral is the integral of the conjugate: .
Step 2. Use that is real. and , so .
Step 3. Recognise . By definition , the same integral. So , and with , is real.
Step 4. Add the pair. With , the second term is , and . So the pair equals .
Step 5. Polar form. Write . Then .
Step 6. Cartesian form. Write . Then , so and . From , and .
So a real wave of amplitude is two phasors of length , one at and one at . That is why the probe above found for a wave of amplitude , and why the FFT of a real cosine shows two peaks, not one (Part 2 works that out by hand).
The square wave, by hand
Example 2 (Fourier coefficients of a square wave)
Let on and on .
Step 1. The mean. .
Step 2. Split the integral for : .
Step 3. First piece. With the antiderivative : , using .
Step 4. Second piece. .
Step 5. Subtract. : zero for even , and for odd .
Step 6. Real form. and for odd , so
Numerically, , , : an FFT of 65,536 samples agrees to four decimals.
Now build partial sums yourself. The figure computes the coefficients of each shape, or of any curve you draw, and adds up the harmonics up to .
Two things stand out. The square wave’s partial sums overshoot beside each jump, and the overshoot does not shrink as grows. And the coefficients of the triangle die off much faster than those of the square. The next section explains both.
4. How good is a partial sum?
There are two questions, and they have different answers. Does the energy of the error go to zero? Yes, for every square-integrable function. Does the error go to zero at every point? Not always, and the square wave is the classic failure.
In energy: always
Theorem 1 (Convergence in L² and Parseval’s identity)
For every , as , and
The proof needs one new tool. The partial sums themselves can misbehave pointwise, but their running averages are well behaved, because they are averages of against a positive kernel.
Proof
Step 1. is a convolution. Insert the definition of : , with the Dirichlet kernel .
Step 2. Closed form of . With , the geometric sum is . Multiply top and bottom by : , since .
Step 3. Average the partial sums. The Fejér mean is with .
Step 4. Closed form of . By Step 2, . The identity makes the sum telescope: . Hence .
Step 5. Three properties of . (a) , by Step 4. (b) , because each integrates to (only its term survives, by orthogonality). (c) For any , on we have .
Step 6. Fejér means of continuous converge uniformly. By (b), . Given , uniform continuity gives with for . Split the integral: the near part is at most by (a) and (b); the far part is at most by (c), which is below for large .
Step 7. Partial sums of continuous converge in energy. is a trigonometric polynomial of degree below , so by the best-approximation property, .
Step 8. All of . Continuous periodic functions are dense in (a standard fact of measure theory). Given and , pick a continuous with . is a polynomial of degree , so by best approximation for large .
Step 9. Parseval. Step 5 of the best-approximation proof says . Let ; the first term goes to .
Two consequences we have already used. The orthonormal set is complete: nothing in is orthogonal to all of it, so fact 2 holds in the energy sense. And the squared error of a partial sum is exactly the energy of the coefficients left out, . That is how the epicycle figure at the top prints its error without comparing curves: it adds up the circles it is not drawing.
Pointwise: the Gibbs phenomenon
Energy convergence allows a thin spike of error to survive, as long as it gets thinner. Beside a jump, it does.
Proposition 5 (Gibbs overshoot)
For the square wave of Section 3, let be the partial sum with the odd harmonics . Its first maximum to the right of the jump at is at , and as ,
The function jumps from to , so the overshoot above is about of the jump, for every large enough, however many terms are used.
Proof
Step 1. The partial sum. From the example in Section 3, .
Step 2. Its derivative. with .
Step 3. Sum the cosines. The identity (from ) telescopes: . Hence .
Step 4. The first maximum. For small the denominator is positive and until the numerator first vanishes, at . So rises to a maximum at .
Step 5. Evaluate it. At , with , and . So .
Step 6. Recognise a Riemann sum. The points are the midpoints of equal intervals of width covering , so the sum tends to . Multiplying by gives .
Measured values agree: with odd terms the maximum is , , , , each at . The peak moves toward the jump and gets narrower, so its energy vanishes, but its height does not. Where does it come from? Step 1 of the Parseval proof says , and the Dirichlet kernel has negative side lobes. Averaging a jump against a kernel with negative lobes produces ripples. The Fejér kernel has no negative lobes, which is why Fejér means of a square wave never overshoot.
Note (Gibbs in practice)
The same ripples appear whenever a spectrum is cut off sharply: around edges in an image low-passed with a brick-wall filter (Section 9), in MRI scans reconstructed from a truncated set of frequencies (“truncation artefacts”), and in spectral solvers of PDEs with shocks. The cure is always the same: taper the cut instead of chopping it.
Smoothness is decay
The second observation from the series figure, that the triangle’s coefficients fall faster, is a theorem worth knowing by heart.
Proposition 6 (Smooth functions have rapidly decaying coefficients)
Let be periodic with continuous and piecewise continuous. Then for
Proof
Step 1. One integration by parts. .
Step 2. The boundary term vanishes, because and take the same values at and . So .
Step 3. Repeat times (allowed because are continuous and periodic): .
Step 4. Bound. , since .
A jump gives decay (the square wave: ). A kink gives : the triangle wave has derivative times the square wave, so its coefficients are for odd , which is what the log-scale stems in the figure show. A function with continuous derivatives decays faster than , and an infinitely smooth one faster than any power. Read backwards, this is a detector: slowly decaying coefficients mean a singularity somewhere, but the coefficients do not say where. Wavelets, in Part 3, will say where.
5. Why sinusoids? The real reason
Why this basis? There are many orthonormal bases of : Legendre polynomials, Haar functions, wavelets. The usual answer, “because signals are made of waves”, is not the reason. The reason is that sinusoids are the only functions that every shift-invariant operation leaves alone.
Write for the shift, . An operator on periodic functions is shift-invariant if it commutes with every shift: . Blurring is shift-invariant (it treats every place alike), so is differentiation, so is any convolution, and so is the Laplacian.
Proposition 7 (Every shift-invariant linear operator has the eₖ as eigenfunctions)
If is linear and shift-invariant, then for every , with .
Proof
Step 1. is an eigenfunction of each shift. .
Step 2. Push the shift through . Let . Then , using shift-invariance and then linearity.
Step 3. Read it pointwise. for all and . Put : , so .
So in the Fourier basis, every shift-invariant operator is diagonal: it multiplies the -th coordinate by and does nothing else. For a convolution (with ), , so
For the derivative, ; for the second derivative, , the eigenvalues of the Laplacian (more in the post on the Laplacian).
Proof: the convolution rule cₖ(h ∗ f) = cₖ(h) cₖ(f), directly
Step 1. Write it out. .
Step 2. Split the exponential. , and swap the order of integration (Fubini; integrable): .
Step 3. The inner integral is : substitute ; by periodicity, the integral over any interval of length is the same.
Step 4. What is left is .
The converse is what makes the exponentials special, and not just convenient.
Proposition 8 (The eₖ are the only common eigenfunctions of all shifts)
Let be continuous and periodic with for every . Then for some integer .
Proof
Step 1. . Otherwise putting in gives ; at a point where this forces , and then for all , so .
Step 2. is multiplicative. gives , so ; also (put ), so is continuous with .
Step 3. is differentiable. Pick small enough that (possible since near ). Then , and the right side is differentiable in .
Step 4. Solve. Differentiating Step 3, . So with a constant , and .
Step 5. Periodicity. forces , so and for an integer . Then .
Remark (The general principle)
Shifts form a group (the circle here, the line in Section 6, the sphere in the sphere post). The functions that every element of the group merely rescales are the group’s characters, and expanding in them is harmonic analysis on that group. On the circle the characters are ; on the line, ; on the sphere, rotations no longer commute and the role is taken by the spherical harmonics. Wherever there is symmetry, there is a Fourier transform adapted to it.
6. From series to transform
A signal on the whole line is not periodic. The trick is to pretend it is, with a period so large that the copies never meet, and to see what happens to the series as .
The heuristic, step by step. Let vanish outside and repeat it with period . Rescaling the formulas of Section 3 to period (substitute ), the basis is and
The series becomes : a Riemann sum with spacing . As it tends to . The frequencies stop being whole numbers and fill the line.
Definition 4 (Fourier transform)
For integrable on ,
The second formula, the inversion theorem, holds whenever is continuous and is integrable; Section 7 proves it.
is the same coordinate as before: the inner product of with the wave , now for every real frequency .
Example 3 (Three transforms by hand)
A box. for : , with value at (the area of the box).
A two-sided exponential. . Split at zero: and . Add over the common denominator : , a Lorentzian. (A kink at , so decay like , as in Section 4.)
A spike. The box of width and height has area and, by the scaling rule of Section 7, transform . As the box becomes the Dirac delta and its transform becomes the constant . A perfect spike contains every frequency equally. (Distribution theory makes this precise; Osgood’s notes do it well.)
Each of these was checked numerically by quadrature at and .
| Convention | Forward | Inverse |
|---|---|---|
| , this series | ||
| , physics | ||
| , unitary |
Question 2
Which convention is right?
Answer
All three are; they differ by where goes. With , the physics transform at equals ours at , and the unitary one is that divided by . The cost of mixing them is a missing factor of somewhere, usually in a Gaussian’s width or in Plancherel’s identity. Pick one and convert at the boundary of your code.
7. Properties, each with a proof
Most Fourier calculations are a few of these rules applied in sequence. Assume and are integrable, and smooth and decaying wherever a derivative appears.
Proposition 9 (Shift, modulation, scaling)
- Shift: .
- Modulation: .
- Scaling: for .
Proof
Shift. Substitute : .
Modulation. .
Scaling, . Substitute , : .
Scaling, . The same substitution reverses the limits of integration, which contributes a minus sign: .
The shift rule says that moving a signal changes only the phase of its transform, never the magnitude. That is why the magnitude spectrum of an image does not care where things are, and why positions are written in the phase (Section 10). The scaling rule says that squeezing a signal stretches its spectrum:
Proposition 10 (Derivatives and multiplication by x)
- .
- .
Proof
Derivative. Integrate by parts: . The boundary term vanishes because as .
Multiplication by . Differentiate under the integral sign (allowed when is integrable): . Divide by , and .
These two rules turn calculus into algebra, and they give the most important pair of all in four lines.
Proposition 11 (The Gaussian is its own transform)
.
Proof
Step 1. The Gaussian solves an ODE. satisfies .
Step 2. Transform both sides. The left becomes . The right becomes . So : the same ODE.
Step 3. Solve it. , so .
Step 4. The constant. . Square it and use polar coordinates: . Since , .
With scaling: , the pair in the clip above. Now the inversion theorem, which so far we only made plausible.
Theorem 2 (Fourier inversion)
If is integrable and continuous and is integrable, then for every .
Proof
The idea: insert a Gaussian damping factor to make every integral absolutely convergent, compute, and let the damping go.
Step 1. Damp. For let . Since is integrable and the damping is at most and tends to , dominated convergence gives .
Step 2. Expand and swap integrals. . The swap is allowed (Fubini) because .
Step 3. The inner integral is a Gaussian’s transform. It is the transform of evaluated at . By the Gaussian pair and the scaling rule with , it equals with .
Step 4. So ( is even).
Step 5. is an approximate identity. It is positive; it integrates to (substitute and use Step 4 of the Gaussian proof); and for any , , as does .
Step 6. Convergence. . Choose so that for (continuity at ). The near part is below . The far part is at most , which tends to by Step 5.
Step 7. Compare the limits. Step 1 and Step 6 compute the limit of the same , so they agree.
Proposition 12 (Plancherel and the convolution theorem)
- Plancherel: . Energy is the same in both domains.
- Convolution: .
- Duality: .
Proof
Plancherel. Step 1, the multiplication formula. For integrable : , by Fubini, reading the double integral both ways. Step 2, choose . Then by inversion. Step 3, substitute: . (By density this extends to all of , the content of Plancherel’s theorem.)
Convolution. . Write , swap integrals (Fubini), and substitute in the inner one: .
Duality. Inversion at : , which is the transform of evaluated at .
| Operation on | Effect on |
|---|---|
| shift by | multiply by (phase only) |
| multiply by | shift by |
| squeeze by | stretch by , scale by |
| differentiate | multiply by |
| multiply by | |
| convolve with | multiply by |
| real-valued |
The last row is the negative-frequency proposition of Section 3 on the line, with the same proof.
8. Filters and what “frequency response” means
A linear shift-invariant system (in engineering, an LTI system) takes a signal and returns , linearly and treating every time alike. Section 5 already told us everything about it: it is a convolution, , with the impulse response, and in frequency it multiplies, . The function is the frequency response: by how much, and with what phase shift, the system passes each frequency.
To see filters act, the series uses one shared signal, the song: 2048 samples over one second, containing a chord (two close tones, 40 and 56 Hz), then a chirp sweeping from 60 to 240 Hz, then a single click. It is synthetic, so every number about it is exact.
Question 3
“A filter removes frequencies.” Why is that not quite true, and what does the ringing in the figure have to do with Section 4?
Answer
An ideal low-pass filter has : one inside , zero outside. By the box pair and duality its impulse response is , which has negative side lobes. Convolving a click with it reproduces those lobes: ripples on both sides. This is the Gibbs phenomenon again, now in time: chopping a spectrum sharply is convolving with a kernel that rings. A Gaussian response has a Gaussian, positive impulse response, so it smooths without ringing; the price is a gentle roll-off instead of a clean cut. Every real filter trades sharpness in frequency against compactness and positivity in time, a first glimpse of the uncertainty principle of Part 2.
Two more facts worth keeping. Since a shift is multiplication by , a filter whose phase is linear in just delays the signal; any other phase distorts it, which is why image filters are usually designed to be symmetric (zero phase). And a derivative is the filter : a high-pass that grows without bound, which is why differentiating noisy data amplifies the noise.
9. Images: the 2-D Fourier transform
Everything carries over to two dimensions, with one new ingredient: direction.
Definition 5 (2-D Fourier transform)
For an image , ,
with and .
The basis functions are plane waves, . Their phase is constant wherever is, which is along lines perpendicular to ; moving a distance along changes by , so the wavelength is . A single point of the spectrum, together with its mirror (the image is real), is one grating: stripes perpendicular to , spaced apart, with an amplitude and a phase.
Proposition 13 (Separability and rotation)
- Separability: if , then .
- Rotation: for a rotation matrix , . Rotate an image and its spectrum rotates with it.
Proof
Separability. , so the double integral splits into (Fubini).
Rotation. Substitute . A rotation has , so , and , so . Hence .
A consequence you can see in every image spectrum: a pattern that varies in one direction puts its energy on a line through the origin in that direction, perpendicular to its stripes. If does not depend on , separability with (whose transform is a spike at ) puts all of on the horizontal axis. In the explorer below, choose Sunset: the horizon and the waves are horizontal, they vary vertically, and the spectrum has a bright vertical streak. Its strongest off-centre wave, found by the figure, is four horizontal stripes across the image.
The figure works on versions of my sketches, using the discrete transform of Part 2. The bright centre is zero frequency, and brightness is . Things to try: low-pass with a sharp edge, then tick smooth edge and watch the ringing (Gibbs, in 2-D) disappear; one wave to see what a single dot is; erase to delete a direction of texture.
How fast does the spectrum of a picture fall off? For photographs of natural scenes, power falls roughly like , so amplitude like (Field, 1987). My sketches are a little smoother: fitting the radially averaged power between 4 and 100 cycles per image gives exponents from (Portrait, with its fine hatching) to (Tree). By Section 4, this slow, power-law decay is the signature of edges: images are full of jumps.
The projection–slice theorem
One 2-D result deserves a place here because a machine in every hospital depends on it.
Theorem 3 (Projection–slice)
Let be the projection of an image onto the -axis. Then : the 1-D transform of a projection is a slice of the 2-D transform through the origin. By the rotation theorem, the same holds at every angle.
Proof
Step 1. .
Step 2. Insert : .
Step 3. Other angles. Projecting along direction is projecting the rotated image onto the -axis; by the rotation theorem its 2-D transform is , whose slice at is along the rotated axis.
A CT scanner measures X-ray projections of a body at many angles. Each projection, transformed, fills one line of the 2-D spectrum; enough angles fill it all, and an inverse 2-D transform (in practice, its rearrangement as filtered back-projection) gives the image. MRI goes further: it measures the spectrum directly, one line of “k-space” at a time.
10. Amplitude versus phase
Every Fourier coefficient is a magnitude and a phase. Which one carries the picture? Rebuild an image from the amplitudes of one sketch and the phases of another.
(On a phone the panel titles abbreviate phase as ∠.) The image with the Portrait’s amplitudes and the Tree’s phases looks like the tree: its correlation with the tree is , with the portrait . Keep the portrait’s amplitudes and draw the phases at random, and the correlation with the portrait falls to : a texture with the right mixture of scales and nothing in place. Oppenheim and Lim made this observation famous in 1981, and it is easy to underrate.
Why phase? By the shift rule, position lives in the phase. And edges are places where many frequencies agree. Look at the square wave’s series, : at the jump , every term crosses zero going upward at the same moment. An edge is a phase alignment across frequencies (Morrone and Owens call it phase congruency), and the amplitudes, which are much alike from one natural image to the next, only say how strong each scale is.
Note (What this means in practice)
Discarding phase is a common way to lose information without noticing: a magnitude spectrogram, a power spectrum used as a feature, a loss computed on only. Recovering a signal from magnitudes alone, phase retrieval, is a field of its own, central to X-ray crystallography and coherent diffraction imaging.
11. What Fourier cannot tell you
Go back to the song. Its spectrum has two sharp peaks for the chord, a broad plateau for the chirp, and a faint floor that covers every frequency. That floor is the click: a spike contains every frequency equally (Section 6). The spectrum is a perfect inventory, and it is silent about when. Nothing in says that the chirp rises rather than falls, or that the click comes last. The same is true of the edge of an eyelid in a sketch: it is everywhere in the spectrum and nowhere in particular.
This is not a defect of the computation. Every stretches over the whole line, so every coefficient is a global average. To say where and when, we need building blocks that are local in both position and frequency. How local they can be is limited by a theorem, the uncertainty principle, which Part 2 proves along with everything that changes when signals are sampled and finite. Part 3 then builds the best compromise, wavelets.
12. Implementation and caveats
In practice the integrals of this post are computed with the FFT, an algorithm for the discrete Fourier transform (Part 2 derives it). Two recipes cover most needs.
Fourier series coefficients. Sample one period at . The rectangle rule turns into .
import numpy as np
N = 4096
x = np.arange(N) / N # one period, [0, 1)
f = np.where(x < 0.5, 1.0, -1.0) # the square wave of Section 3
c = np.fft.fft(f) / N # c[k] ~ c_k for 0 <= k < N/2, and c[N - k] ~ c_{-k}
print(c[1], 2 / (np.pi * 1j)) # both about -0.6366j
The Fourier transform on a grid. Sample at . At the frequencies , a Riemann sum gives , because .
n, L = 512, 16.0
dx = L / n
xg = -L / 2 + dx * np.arange(n) # the grid starts at x0 = -8, not at 0
f = np.exp(-np.pi * (xg - 1.0) ** 2) # a Gaussian centred at x = 1
xi = np.fft.fftfreq(n, d=dx) # frequencies in cycles per unit
F = dx * np.exp(-2j * np.pi * xi * xg[0]) * np.fft.fft(f) # note the phase factor for x0
exact = np.exp(-np.pi * xi**2) * np.exp(-2j * np.pi * xi) # Gaussian pair + shift rule
print(np.abs(F - exact).max()) # about 1e-15
Both snippets were run as written. The traps, each with its symptom:
- The origin phase. Drop the factor and the magnitude is still exactly right but the phase is wrong by up to (measured: magnitude error , phase error rad). A plot of will never reveal this bug.
- Conventions. NumPy uses the DFT above, with on the inverse;
norm="ortho"puts on both. Mixing and costs a factor of (Section 6). - Frequency order. The FFT returns , then the negative frequencies. Use
fftfreqfor the values andfftshiftto centre zero for display. - Real input. A real signal has : half the output is redundant.
rfftreturns only the non-negative half and is about twice as fast. - Truncation rings. Cutting a spectrum sharply, to compress or to denoise, rings near edges (Gibbs). Taper the cut.
- Differentiation by FFT multiplies by : superb for smooth periodic data, disastrous for noisy data or data with jumps, where it amplifies noise and Gibbs ripples.
- Display. Show ; raw magnitudes are a single bright dot. Phase is meaningless where the magnitude is near zero, so mask it there.
Two issues are deliberately left for Part 2: why the FFT of a function that is not periodic on its window shows a bright cross (“leakage”), and why sampling too coarsely silently changes frequencies (“aliasing”).
13. Where it is used, and what is open
| Use Fourier analysis when | Be careful when |
|---|---|
| the operation is linear and shift-invariant (blur, convolution, differentiation, constant-coefficient PDEs) | the signal changes character over time or space (speech, a chirp, an image with distinct regions) |
| the domain is periodic, or can be made so | there are boundaries the method does not know about |
| you need global structure: dominant orientations, textures, periodicity | you need to locate a localised event |
| speed matters: convolution with large kernels, solving Poisson’s equation | the data has jumps and you need pointwise accuracy |
Where it shows up in current work. Spectral methods for PDEs on periodic domains; CT and MRI reconstruction, including from undersampled k-space; phase correlation for image registration; Fourier features and positional encodings in neural fields (Tancik et al., 2020), together with the observation that networks learn low frequencies first, spectral bias (Rahaman et al., 2019); global filtering layers in vision networks (GFNet); Fourier neural operators for learning PDE solution maps (Li et al., 2021); FFT-based long convolutions in sequence models.
Open questions worth a PhD’s attention:
- Spectral bias, made predictive. Networks fit low frequencies first. Can we predict, from an architecture and its initialisation, which frequencies it will learn and how fast, and choose encodings accordingly instead of by trial?
- Phase retrieval with learned priors. Recovering an image from Fourier magnitudes is ill-posed in general; learned priors make it work in practice. When is the answer unique and stable, and can the prior’s errors be detected?
- Fourier methods off the grid. FFT speed needs regular grids and periodic boundaries. What is the right fast spectral layer on irregular meshes, point clouds or bounded domains, without losing the diagonalisation of Section 5?
- When does global spectral mixing beat attention or convolution in vision models, and why? Current evidence is empirical and task-specific.
- Trusting individual frequencies. A learned surrogate may be accurate at low frequencies and wrong at high ones. How should uncertainty be reported per frequency band, so that a user knows which scales of a prediction to believe?
Note (Shoulders to stand on)
- Grant Sanderson (3Blue1Brown), But what is the Fourier Transform? A visual introduction (2018). The winding picture is the best first intuition for what a coefficient measures; the probe figure above is the same idea, read as an inner product.
- Brad Osgood, Lecture Notes for EE 261: The Fourier Transform and its Applications (Stanford). Rigorous and friendly at once; the place to go next, especially for distributions and the delta function.
- Antonio Torralba, Phillip Isola, William Freeman, Foundations of Computer Vision, ch. 16 (MIT Press, 2024). Fourier analysis taught on images, with care.
Self-check
Question 4
You shift an image by 10 pixels. What happens to , and what happens to the phase?
Answer
By the shift rule, is multiplied by with the shift. The magnitude is unchanged; the phase gains a linear ramp . (On a finite image the shift must be circular for this to be exact; Part 2.)
Question 5
Show that a real, even function has a real, even Fourier transform.
Answer
Step 1. . Step 2. is odd in when is even, so its integral over the line is : is real. Step 3. is even in , so .
Question 6
Why does the square wave have no even harmonics?
Answer
It satisfies . Then , and substituting gives . For even this says , so .
Question 7
Which decays faster: the Fourier coefficients of the 1-periodic extension of on , or of ?
Answer
: its periodic extension is continuous, with kinks, so its coefficients fall like . The extension of jumps at , so its coefficients fall only like (Section 4).
Question 8
You blur an image with a Gaussian of standard deviation pixels. By what factor is the amplitude of a grating of frequency (cycles per pixel) reduced?
Answer
The kernel is separable; in each direction, by the Gaussian pair and scaling ( with ), its normalised transform is . In 2-D the factor is . Energy, the square, falls by .
Question 9
A real cosine of amplitude is sampled at points and passed to an FFT. Why are there two peaks of height instead of one of height ?
Answer
By Section 3, : half the amplitude sits at and half at , and the DFT stores at index . Each phasor contributes through a geometric sum; Part 2 carries out the sum.
References
- A. V. Oppenheim, J. S. Lim. The importance of phase in signals. Proceedings of the IEEE 69(5), 1981.
- M. C. Morrone, R. A. Owens. Feature detection from local energy. Pattern Recognition Letters 6(5), 1987.
- D. J. Field. Relations between the statistics of natural images and the response properties of cortical cells. JOSA A 4(12), 1987.
- E. M. Stein, R. Shakarchi. Fourier Analysis: An Introduction. Princeton, 2003. (Fejér’s theorem, inversion, Plancherel.)
- B. Osgood. Lecture Notes for EE 261: The Fourier Transform and its Applications. Stanford University.
- A. Torralba, P. Isola, W. T. Freeman. Foundations of Computer Vision. MIT Press, 2024.
- G. Sanderson. But what is the Fourier Transform? A visual introduction. 3Blue1Brown, 2018.
- M. Tancik et al. Fourier features let networks learn high frequency functions in low dimensional domains. NeurIPS, 2020.
- N. Rahaman et al. On the spectral bias of neural networks. ICML, 2019.
- Y. Rao et al. Global filter networks for image classification. NeurIPS, 2021.
- Z. Li et al. Fourier neural operator for parametric partial differential equations. ICLR, 2021.
Was this useful?
Thanks, that helps me decide what to write next.