Module contents
Lesson 15 of 20Advanced 120 min

Fourier series and the Fourier transform

Functions as vectors in an inner-product space and their frequency decomposition. The lesson covers L², Fourier series and their convergence modes (including the Gibbs phenomenon), Parseval's identity, the Fourier transform and the convolution theorem. These underlie signal spectral analysis, characteristic functions in m04, positional encodings and neural network spectral bias.

After this lesson you can

  • Treat square-integrable functions as vectors and calculate projections onto the trigonometric basis.
  • Calculate Fourier coefficients and relate their decay rate to function regularity.
  • Explain L², pointwise and uniform convergence of Fourier series and the Gibbs phenomenon.
  • Apply Parseval and Plancherel to calculate sums and energies.
  • Compute basic Fourier transforms and prove the convolution theorem.
  • Measure a small network's spectral bias and how Fourier features correct it.

Before you start

Motivation: three problems with the same solution

In 1807 Fourier presented a paper on heat propagation with an assertion that shocked Lagrange: every periodic function, even one with jumps, can be written as a sum of sines and cosines. This was almost true, and clarifying “almost” forced analysis to be rebuilt: from it came the modern definition of function, the Riemann integral (invented to study these series), uniform convergence and later the Lebesgue integral and Hilbert spaces. Today the idea appears in three problems you will encounter building models:

  • Decompose a signal. Audio, a price series or a neuron’s activation over a sequence are functions. Writing them as a sum of oscillations at different frequencies separates slow from fast variation, the separation used by equalizers, audio compressors and seasonality analysis.
  • Smooth by convolution. A moving average, Gaussian blur, kernel density estimate or convolutional network layer computes integrals of form ∫f(y) g(x−y) ⁣dy\int f(y)\,g(x - y) \dd y. In space they are hard to analyze; in frequency they become a product, and “smoothing” means exactly “attenuating high frequencies”.
  • Understand what a network learns first. A neural network trained by gradient descent fits low-frequency target components before high-frequency ones. This spectral bias explains why an MLP poorly draws fine image details and why sinusoidal positional encodings fix it.

The common tool is to view functions as vectors in an inner-product space and decompose them in a basis of oscillations. This lesson develops that perspective rigorously: space L2L^2, Fourier series and their three convergence modes (with the Gibbs phenomenon, which never disappears), Parseval’s identity, the Fourier transform on the line, the uncertainty principle and convolution theorem. We finish with discrete sampling and a spectral-bias experiment on the GPU.

Quick review: complex numbers and Euler’s formula

Everything below is written much better with complex exponentials. What you saw with Euler’s formula suffices:

eiθ=cos⁡θ+isin⁡θ,∣eiθ∣=1,eiθ‾=e−iθ,eiθeiφ=ei(θ+φ).e^{i\theta} = \cos\theta + i\sin\theta, \qquad \abs{e^{i\theta}} = 1, \qquad \overline{e^{i\theta}} = e^{-i\theta}, \qquad e^{i\theta}e^{i\varphi} = e^{i(\theta + \varphi)}.

Rearranging, cos⁡θ=(eiθ+e−iθ)/2\cos\theta = (e^{i\theta} + e^{-i\theta})/2 and sin⁡θ=(eiθ−e−iθ)/(2i)\sin\theta = (e^{i\theta} - e^{-i\theta})/(2i): a cosine is the sum of two rotations in opposite directions. Function x↦eikxx \mapsto e^{ikx}, with k∈Zk \in \Z, traces the unit circle kk times as xx goes from −π-\pi to π\pi and is 2π2\pi-periodic. A complex function of a real variable is integrated componentwise, ∫(u+iv)=∫u+i∫v\int (u + iv) = \int u + i\int v, and with that definition the usual rules still hold (linearity, substitution, parts, the fundamental theorem with  ⁣d ⁣dxeikx=ik eikx\frac{\dd}{\dd x}e^{ikx} = ik\,e^{ikx}). The calculation underlying the whole lesson is:

12π∫−ππeikx eilx‾ ⁣dx=12π∫−ππei(k−l)x ⁣dx={1k=l,ei(k−l)π−e−i(k−l)π2πi(k−l)=0k≠l,\frac{1}{2\pi}\int_{-\pi}^{\pi} e^{ikx}\,\overline{e^{ilx}} \dd x = \frac{1}{2\pi}\int_{-\pi}^{\pi} e^{i(k - l)x} \dd x = \begin{cases} 1 & k = l, \\[2pt] \dfrac{e^{i(k - l)\pi} - e^{-i(k - l)\pi}}{2\pi i(k - l)} = 0 & k \neq l, \end{cases}

because eimπ=e−imπe^{i m\pi} = e^{-im\pi} for every integer mm. An exponential making a nonzero integer number of turns averages to zero.

Functions as vectors

In Rn\R^n the inner product adds products coordinate by coordinate, x⊤y=∑ixiyi\vb{x}\T\vb{y} = \sum_i x_i y_i. A function f:[−π,π]→Cf: [-\pi, \pi] \to \C is a vector with a coordinate for each point xx, and the sum becomes an integral. This analogy, taken seriously, gives everything we need.

The inner product of functions

Factor 1/(2π)1/(2\pi) is a normalization: it makes constant function 11 have norm 11 and ∥f∥22\norm{f}_2^2 be the mean value of ∣f∣2\abs{f}^2, a signal’s “mean power”. The inner-product axioms are easily checked: linearity in the first argument, conjugate symmetry ⟨g,f⟩=⟨f,g⟩‾\inner{g}{f} = \overline{\inner{f}{g}} and ⟨f,f⟩≥0\inner{f}{f} \ge 0. As in any inner-product space, Cauchy–Schwarz ∣⟨f,g⟩∣≤∥f∥2∥g∥2\abs{\inner{f}{g}} \le \norm{f}_2\norm{g}_2, the triangle inequality and Pythagoras for orthogonal functions hold: the proof in m02 never uses a finite number of vector coordinates.

Two things change relative to Rn\R^n, making the lesson interesting. Dimension is infinite, so “writing ff in a basis” means summing a series and we must specify how it converges. Norm ∥⋅∥2\norm{\cdot}_2 measures mean-square error, not maximum error: functions can be close in L2L^2 and far apart in supremum norm. That gap is exactly what you will see in the Gibbs phenomenon.

The trigonometric system is orthonormal

Write ek(x)=eikxe_k(x) = e^{ikx} for k∈Zk \in \Z. The review calculation says

⟨ek,el⟩={1k=l,0k≠l.\inner{e_k}{e_l} = \begin{cases} 1 & k = l, \\ 0 & k \neq l. \end{cases}

Exponentials {ek}k∈Z\{e_k\}_{k \in \Z} form an orthonormal system: infinitely many unit vectors pairwise perpendicular. In real form, functions 1,2cos⁡kx,2sin⁡kx1, \sqrt 2\cos kx, \sqrt 2\sin kx (k≥1k \ge 1) do too, because cos⁡kx\cos kx and sin⁡kx\sin kx are combinations of eke_k and e−ke_{-k}.

The best approximation is a projection

Fix NN and consider the subspace of trigonometric polynomials of degree at most NN, TN=span⁡{ek:∣k∣≤N}\mathcal{T}_N = \spn\{e_k : \abs{k} \le N\}, of dimension 2N+12N + 1. Given ff, which element of TN\mathcal{T}_N is closest to ff in L2L^2? In Rn\R^n the answer is orthogonal projection, computed coordinate by coordinate with an orthonormal basis. Here it is the same.

Proof

(1) For ∣l∣≤N\abs{l} \le N, ⟨f−SNf,el⟩=cl−∑∣k∣≤Nck⟨ek,el⟩=cl−cl=0\inner{f - S_N f}{e_l} = c_l - \sum_{\abs{k} \le N} c_k\inner{e_k}{e_l} = c_l - c_l = 0, and by linearity f−SNff - S_N f is orthogonal to any combination of the ele_l. (2) f−P=(f−SNf)+(SNf−P)f - P = (f - S_N f) + (S_N f - P) with the second summand in TN\mathcal{T}_N; by (1) the summands are orthogonal and Pythagoras suffices. The minimum is attained only if ∥SNf−P∥2=0\norm{S_N f - P}_2 = 0, that is, P=SNfP = S_N f. (3) Pythagoras with f=SNf+(f−SNf)f = S_N f + (f - S_N f) and ∥SNf∥22=∑∣k∣≤N∣ck∣2\norm{S_N f}_2^2 = \sum_{\abs{k} \le N}\abs{c_k}^2 by orthonormality. Partial sums of ∑∣ck∣2\sum\abs{c_k}^2 are bounded by ∥f∥22\norm{f}_2^2, so the series converges with that bound.

∎

This is least squares in infinite dimensions: SNfS_N f is the least-squares fit of ff with 2N+12N + 1 basis functions, and no system needs solving because the basis is orthonormal. A consequence used shortly: since ∑∣ck∣2<∞\sum\abs{c_k}^2 < \infty, the general term tends to zero.

A Riemann-integrable function is bounded, hence ∥f∥2<∞\norm{f}_2 < \infty and the Bessel series converges. Intuitively, integrating ff against increasingly rapid oscillation averages its positive and negative values: the pieces of ff supporting each oscillation are nearly constant.

Fourier series

We have not yet asserted convergence: the series is a formal object associated with ff, and the sense in which ff holds is the theory’s heart. Three practical observations. If ff is even, the bkb_k vanish and only cosines remain; if odd, only sines. If ff is real, f^(−k)=f^(k)‾\hat f(-k) = \overline{\hat f(k)}, and the information is in k≥0k \ge 0. If the period is PP instead of 2π2\pi, the exponentials are e2πikx/Pe^{2\pi ikx/P} and the normalization factor 1/P1/P.

Three complete examples

Compare magnitudes: coefficients of square and sawtooth waves, which have jumps, decay as 1/k1/k; those of the continuous triangle wave with corners as 1/k21/k^2. Before explaining why, experiment with partial sums.

InteractiveAdding harmonics
−π−π/20π/2π+9.1 %
  • ff
  • SNfS_N f, sum of harmonics 0..N0..N
  • harmonic NN: aNcos⁡Nx+bNsin⁡Nxa_N\cos Nx + b_N\sin Nx
Spectrum: amplitude ak2+bk2\sqrt{a_k^2 + b_k^2} versus kk, on log-log axes
110⁻¹10⁻²10⁻³10⁻⁴1251020501/k1/k²
9
Amplitude of harmonic NN0.141
Error ∥f−SNf∥2\|f - S_N f\|_20.201
Maximum error on [−π,π][-\pi, \pi]0.990
Overshoot (fraction of the jump)9.12 %
Spectrum slope (log-log)−1.00 ≈ k⁻¹
Near the jump, SNfS_N f overshoots by 9.1% of the jump. Increase NN: the peak narrows and approaches the jump, but its height tends to 8.958.95%, not zero.
Each +1 press adds harmonic NN, aNcos⁡Nx+bNsin⁡Nxa_N\cos Nx + b_N\sin Nx (orange), the projection of ff onto the plane of cos⁡Nx\cos Nx and sin⁡Nx\sin Nx; blue curve is sum SNfS_N f. Below is the amplitude spectrum: blue bars for harmonics already added, gray for those remaining, with references 1/k1/k and 1/k21/k^2 on log-log scale. With the square wave increase NN to 60 and watch the magenta peak by the jump: it narrows and approaches the jump, but its height does not fall. Switch to the triangle wave and compare spectrum slope and maximum error. Finally draw your own function above the graph: if it starts and ends at different heights, the periodic extension jumps at ±π\pm\pi and you will see it in the spectrum.

Three things the figure shows and the rest of the section explains. Error in L2L^2 always falls when terms are added, as guaranteed by best approximation (each SNfS_N f is the best approximation in TN\mathcal{T}_N, and TN⊂TN+1\mathcal{T}_N \subset \mathcal{T}_{N+1}). Maximum error falls for the triangle and smooth functions but stays near 11 for the square wave: half the jump. Overshoot near the jump stabilizes around 8.958.95% of jump height, regardless of NN.

Regularity and coefficient decay

The rule just observed has a one-line explanation: differentiating ff multiplies its coefficients by ikik.

Proof

On each subinterval [xj−1,xj][x_{j-1}, x_j] of the partition, integration by parts gives ∫xj−1xjf′(x)e−ikx ⁣dx=[f(x)e−ikx]xj−1xj+ik∫xj−1xjf(x)e−ikx ⁣dx\int_{x_{j-1}}^{x_j} f'(x)e^{-ikx} \dd x = \big[f(x)e^{-ikx}\big]_{x_{j-1}}^{x_j} + ik\int_{x_{j-1}}^{x_j} f(x)e^{-ikx} \dd x. Summing over jj, boundary terms cancel at interior points because ff is continuous, and at endpoints f(π)e−ikπ−f(−π)eikπ=(−1)k(f(π)−f(−π))=0f(\pi)e^{-ik\pi} - f(-\pi)e^{ik\pi} = (-1)^k\big(f(\pi) - f(-\pi)\big) = 0 remains by periodicity. Dividing by 2π2\pi gives the formula.

∎

Applying this mm times: if ff is of class Cm−1C^{m-1} as a periodic function and f(m−1)f^{(m-1)} is piecewise C1C^1, then f^(k)=f(m)^(k)/(ik)m\hat f(k) = \widehat{f^{(m)}}(k)/(ik)^m, and by Riemann–Lebesgue applied to f(m)f^{(m)},

∣f^(k)∣=∣f(m)^(k)∣∣k∣m=o(∣k∣−m).\abs{\hat f(k)} = \frac{\abs{\widehat{f^{(m)}}(k)}}{\abs{k}^m} = o\big(\abs{k}^{-m}\big).

The smoother ff is, the faster its coefficients decay. The practical rule, confirmed by the interactive:

Regularity of ff (periodic)Typical decay of ∣f^(k)∣\abs{\hat f(k)}Example
Jumps1/k1/ksquare wave, sawtooth
Continuous, with corners (f′f' jumps)1/k21/k^2∣x∣\abs{x}
C1C^1, with f′′f'' jumping1/k31/k^3x(π−∣x∣)x(\pi - \abs{x})
C∞C^\inftyfaster than any powerecos⁡xe^{\cos x}
Analytic in a strip ∣Im⁡z∣<a\abs{\operatorname{Im} z} < ageometric, O(e−b∣k∣)\bigO(e^{-b\abs{k}}) for every b<ab < a∑kr∣k∣eikx\sum_k r^{\abs k}e^{ikx}

The converse also works and is equally useful: if ff is continuous and ∑k∣k∣m∣f^(k)∣<∞\sum_k \abs{k}^m\abs{\hat f(k)} < \infty, the derivative series through order mm converge uniformly by the Weierstrass M-test and, by interchanging limit and derivative, ff is of class CmC^m (that the series converges to ff itself follows from the argument ending the uniform-convergence proof below). Reading a function’s regularity in its spectral tail is a basic skill in numerical analysis (spectral methods converge geometrically for analytic solutions) and learning (spectral bias below is the converse statement for networks).

Convergence: in what sense SNf→fS_N f \to f

There are three distinct questions with different answers. Does ∥f−SNf∥2\norm{f - S_N f}_2 tend to zero? Always. Does SNf(x)S_N f(x) tend to f(x)f(x) at every point? For reasonable functions yes, except at jumps where it tends to the midpoint; for merely continuous functions, not necessarily. Does it converge uniformly? Never if there are jumps, because the uniform limit of continuous functions is continuous; and continuity of ff plus a little more regularity suffices.

Mean square: the system is complete

The proof combines three pieces, each worth seeing.

Piece 1: Fejér’s theorem. Trigonometric polynomials are dense in continuous periodic functions under supremum norm. This is the trigonometric version of the Weierstrass approximation theorem; an explicit proof averages partial sums. Cesàro means σNf=1N+1∑n=0NSnf\sigma_N f = \frac{1}{N+1}\sum_{n=0}^{N} S_n f are written as a periodic convolution,

σNf(x)=12π∫−ππf(x−t) FN(t) ⁣dt,FN(t)=1N+1(sin⁡(N+1)t2sin⁡t2)2,\sigma_N f(x) = \frac{1}{2\pi}\int_{-\pi}^{\pi} f(x - t)\,F_N(t) \dd t, \qquad F_N(t) = \frac{1}{N+1}\Big(\frac{\sin\frac{(N+1)t}{2}}{\sin\frac{t}{2}}\Big)^2,

and the Fejér kernel FNF_N has three properties: it is nonnegative, its mean is 11, and outside any neighborhood ∣t∣≥δ\abs{t} \ge \delta it is bounded by 1(N+1)sin⁡2(δ/2)→0\frac{1}{(N+1)\sin^2(\delta/2)} \to 0. Hence for continuous ff (thus uniformly continuous and bounded by BB), ∣σNf(x)−f(x)∣≤12π∫FN(t)∣f(x−t)−f(x)∣ ⁣dt\abs{\sigma_N f(x) - f(x)} \le \frac{1}{2\pi}\int F_N(t)\abs{f(x - t) - f(x)} \dd t; piece ∣t∣<δ\abs{t} < \delta is small by uniform continuity and piece ∣t∣≥δ\abs{t} \ge \delta is bounded by 2Bsup⁡∣t∣≥δFN(t)→02B\sup_{\abs{t} \ge \delta}F_N(t) \to 0, uniformly in xx.

Piece 2: continuous functions are dense in R\mathcal{R} under norm L2L^2. If ff is Riemann integrable and bounded by BB, there is a step function ss with ∣s∣≤B\abs{s} \le B and 12π∫∣f−s∣<ε\frac{1}{2\pi}\int\abs{f - s} < \eps (a lower Darboux sum close to the integral), and rounding each step into a narrow ramp gives a continuous periodic gg with ∣g∣≤B\abs{g} \le B and 12π∫∣s−g∣<ε\frac{1}{2\pi}\int\abs{s - g} < \eps. Since ∣f−g∣≤2B\abs{f - g} \le 2B, ∥f−g∥22≤2B⋅12π∫∣f−g∣<4Bε\norm{f - g}_2^2 \le 2B\cdot\frac{1}{2\pi}\int\abs{f - g} < 4B\eps.

Piece 3: best approximation does the rest. Given ε>0\eps > 0, take continuous gg with ∥f−g∥2<ε\norm{f - g}_2 < \eps and a trigonometric polynomial PP of degree MM with sup⁡∣g−P∣<ε\sup\abs{g - P} < \eps, hence ∥g−P∥2<ε\norm{g - P}_2 < \eps. For N≥MN \ge M, P∈TNP \in \mathcal{T}_N, and best approximation gives

∥f−SNf∥2≤∥f−P∥2≤∥f−g∥2+∥g−P∥2<2ε.\norm{f - S_N f}_2 \le \norm{f - P}_2 \le \norm{f - g}_2 + \norm{g - P}_2 < 2\eps.

Notice the structure: we have not directly proved SNfS_N f converges to anything. We found some polynomial near ff, and projection optimality made SNfS_N f at least as close. This is the standard argument for completeness of an orthonormal system.

Pointwise: Dirichlet’s theorem

Substituting the definition of f^(k)\hat f(k) into the partial sum,

SNf(x)=12π∫−ππf(x−t) DN(t) ⁣dt,DN(t)=∑k=−NNeikt=sin⁡((N+12)t)sin⁡t2,S_N f(x) = \frac{1}{2\pi}\int_{-\pi}^{\pi} f(x - t)\,D_N(t) \dd t, \qquad D_N(t) = \sum_{k = -N}^{N} e^{ikt} = \frac{\sin\big((N + \tfrac12)t\big)}{\sin\frac{t}{2}},

where the last equality is a geometric progression sum. The Dirichlet kernel DND_N has mean 11 and a peak of height 2N+12N + 1 at t=0t = 0, but unlike Fejér’s it takes negative values and its L1L^1 norm grows without bound: the Lebesgue constants LN=12π∫−ππ∣DN∣L_N = \frac{1}{2\pi}\int_{-\pi}^{\pi}\abs{D_N} are 1.441.44, 2.222.22, 3.143.14 and 4.074.07 for N=1,10,100,1000N = 1, 10, 100, 1000, growing as 4π2log⁡N\frac{4}{\pi^2}\log N. That difference explains almost everything.

Proof

Since DND_N is even with mean 11, 12π∫0πDN=12\frac{1}{2\pi}\int_0^{\pi}D_N = \frac12, and

SNf(x)−f(x+)+f(x−)2=12π∫0π[f(x+t)−f(x+)]DN(t) ⁣dt+12π∫0π[f(x−t)−f(x−)]DN(t) ⁣dt.S_N f(x) - \frac{f(x^+) + f(x^-)}{2} = \frac{1}{2\pi}\int_0^{\pi}\big[f(x + t) - f(x^+)\big]D_N(t) \dd t + \frac{1}{2\pi}\int_0^{\pi}\big[f(x - t) - f(x^-)\big]D_N(t) \dd t.

Handle the first summand (the second is identical). Let h(t)=(f(x+t)−f(x+))/sin⁡(t/2)h(t) = \big(f(x + t) - f(x^+)\big)/\sin(t/2) on (0,π](0, \pi]. Near t=0t = 0, h(t)=f(x+t)−f(x+)t⋅tsin⁡(t/2)h(t) = \frac{f(x + t) - f(x^+)}{t}\cdot\frac{t}{\sin(t/2)} is bounded because ff has a right derivative at xx (a consequence of the mean value theorem and existence of the one-sided limit of f′f'); away from 00 it is integrable. Thus the first summand is 12π∫0πh(t)sin⁡((N+12)t) ⁣dt\frac{1}{2\pi}\int_0^{\pi}h(t)\sin\big((N + \tfrac12)t\big) \dd t, and since sin⁡((N+12)t)=sin⁡(Nt)cos⁡t2+cos⁡(Nt)sin⁡t2\sin\big((N + \tfrac12)t\big) = \sin(Nt)\cos\frac t2 + \cos(Nt)\sin\frac t2, a combination of Fourier coefficients of order NN of integrable functions h(t)cos⁡t2h(t)\cos\frac t2 and h(t)sin⁡t2h(t)\sin\frac t2 (extended by zero to [−π,0)[-\pi, 0)). By Riemann–Lebesgue it tends to zero.

∎

The regularity hypothesis matters. In 1873 Du Bois-Reymond constructed a continuous function whose Fourier series diverges at one point, now seen as a direct consequence of LN→∞L_N \to \infty: by the uniform boundedness principle, if linear maps f↦SNf(0)f \mapsto S_N f(0) of norm LNL_N on continuous functions with supremum norm are not uniformly bounded, there is a continuous ff with sup⁡N∣SNf(0)∣=∞\sup_N\abs{S_N f(0)} = \infty. Kolmogorov went further in 1926 with a Lebesgue-integrable function whose series diverges everywhere. The end of the story is Carleson’s theorem (1966): for f∈L2f \in L^2, SNf(x)→f(x)S_N f(x) \to f(x) almost everywhere. And you already know the practical remedy: Fejér means converge uniformly for every continuous ff because their kernel is positive.

Uniform: continuity and a piecewise derivative suffice

Proof

By the derivative theorem, f^(k)=f′^(k)/(ik)\hat f(k) = \widehat{f'}(k)/(ik) for k≠0k \neq 0. By Cauchy–Schwarz in ℓ2\ell^2 and Bessel applied to f′f',

∑k≠0∣f^(k)∣=∑k≠01∣k∣∣f′^(k)∣≤(∑k≠01k2)1/2(∑k≠0∣f′^(k)∣2)1/2≤(2∑k≥11k2)1/2∥f′∥2<∞.\sum_{k \neq 0}\abs{\hat f(k)} = \sum_{k \neq 0}\frac{1}{\abs{k}}\abs{\widehat{f'}(k)} \le \Big(\sum_{k \neq 0}\frac{1}{k^2}\Big)^{1/2}\Big(\sum_{k \neq 0}\abs{\widehat{f'}(k)}^2\Big)^{1/2} \le \Big(2\sum_{k \ge 1}\frac{1}{k^2}\Big)^{1/2}\norm{f'}_2 < \infty.

Since ∣f^(k)eikx∣=∣f^(k)∣\abs{\hat f(k)e^{ikx}} = \abs{\hat f(k)}, the Weierstrass M-test gives uniform convergence of SNfS_N f to a continuous function gg. Integrating term by term (allowed by uniform convergence), g^(k)=f^(k)\hat g(k) = \hat f(k) for every kk. Then f−gf - g is continuous with all coefficients zero, and by convergence in L2L^2, ∥f−g∥2=lim⁡N∥SN(f−g)∥2=0\norm{f - g}_2 = \lim_N\norm{S_N(f - g)}_2 = 0. A continuous function of zero L2L^2 norm is identically zero, hence g=fg = f.

∎

Conversely, if ff has a jump, uniform convergence is impossible: a uniform limit of continuous functions is continuous, and each SNfS_N f is continuous. More concretely, near the jump, sup⁡∣f−SNf∣\sup\abs{f - S_N f} cannot fall below half the jump. This is the number you saw stuck near 11 for the square wave.

The Gibbs phenomenon

Nonuniform convergence does not say what the error looks like. Surprisingly it has a fixed form. For the square wave, the degree-2n−12n - 1 partial sum is

S2n−1f(x)=4π∑j=1nsin⁡((2j−1)x)2j−1, ⁣d ⁣dxS2n−1f(x)=4π∑j=1ncos⁡((2j−1)x)=2π⋅sin⁡2nxsin⁡x,S_{2n-1}f(x) = \frac{4}{\pi}\sum_{j = 1}^{n}\frac{\sin\big((2j - 1)x\big)}{2j - 1}, \qquad \frac{\dd}{\dd x}S_{2n-1}f(x) = \frac{4}{\pi}\sum_{j = 1}^{n}\cos\big((2j - 1)x\big) = \frac{2}{\pi}\cdot\frac{\sin 2nx}{\sin x},

so the first maximum right of the jump is at xn=π/(2n)x_n = \pi/(2n). With tj=(2j−1)π/(2n)t_j = (2j - 1)\pi/(2n), midpoints of a partition of [0,π][0, \pi] into nn pieces of width π/n\pi/n,

S2n−1f(xn)=4π∑j=1nsin⁡tj2j−1=2π∑j=1nsin⁡tjtj⋅πn→n→∞2π∫0πsin⁡tt ⁣dt=2πSi⁡(π)≈1.17898,S_{2n-1}f(x_n) = \frac{4}{\pi}\sum_{j = 1}^{n}\frac{\sin t_j}{2j - 1} = \frac{2}{\pi}\sum_{j = 1}^{n}\frac{\sin t_j}{t_j}\cdot\frac{\pi}{n} \xrightarrow[n \to \infty]{} \frac{2}{\pi}\int_0^{\pi}\frac{\sin t}{t} \dd t = \frac{2}{\pi}\operatorname{Si}(\pi) \approx 1.17898,

a Riemann sum for the sine integral. The maximum tends not to 11, the function value, but to 1.1791.179: an overshoot 0.1790.179 over a jump of height 22, i.e. 8.958.95% of the jump. The peak moves toward the jump (distance π/(2n)\pi/(2n)) and narrows, so its area tends to zero and error in L2L^2 does too, but its height does not change.

This value is not peculiar to the square wave. If ff is piecewise C1C^1 with a jump of size JJ at x0x_0, subtract from it for each jump a suitable multiple of a translated sawtooth whose sole jump per period is there: a continuous piecewise-C1C^1 function remains, whose series converges uniformly. All overshoot comes from the jump and equals (1πSi⁡(π)−12)∣J∣≈0.0895 ∣J∣\big(\tfrac{1}{\pi}\operatorname{Si}(\pi) - \tfrac12\big)\abs{J} \approx 0.0895\,\abs{J} on each side.

Gibbs ringing is visible in the real world: the “halos” around edges in heavily compressed JPEG images and MRI reconstructions with few frequencies, and why low-pass filters use smooth windows rather than abrupt cutoffs.

Parseval’s identity and the Basel problem

Convergence in L2L^2 turns Bessel’s inequality into equality.

Proof

By best approximation, ∑∣k∣≤N∣f^(k)∣2=∥f∥22−∥f−SNf∥22\sum_{\abs{k} \le N}\abs{\hat f(k)}^2 = \norm{f}_2^2 - \norm{f - S_N f}_2^2, and the last term tends to zero. The two-function version follows by applying the first to f+gf + g, f−gf - g, f+igf + ig and f−igf - ig (polarization identity), or directly from ⟨SNf,SNg⟩=∑∣k∣≤Nf^(k)g^(k)‾\inner{S_N f}{S_N g} = \sum_{\abs{k} \le N}\hat f(k)\overline{\hat g(k)} and continuity of the inner product.

∎

This is Parseval’s identity: a signal’s energy is the sum of its harmonics’ energies. In m02 language, map f↦(f^(k))k∈Zf \mapsto (\hat f(k))_{k \in \Z} preserves inner products like an orthogonal matrix, but between L2(T)L^2(\mathbb{T}) and space ℓ2(Z)\ell^2(\Z) of square-summable sequences. The Riesz–Fischer theorem completes the picture: every sequence in ℓ2\ell^2 consists of Fourier coefficients of some L2L^2 (Lebesgue) function, so the map is an isometric isomorphism.

Parseval has two immediate uses. First, measure error without integrating: ∥f−SNf∥22=∑∣k∣>N∣f^(k)∣2\norm{f - S_N f}_2^2 = \sum_{\abs{k} > N}\abs{\hat f(k)}^2. For the square wave, ∣f^(k)∣=2/(π∣k∣)\abs{\hat f(k)} = 2/(\pi\abs{k}) on odd indices, and compare the tail with an integral: ∥f−SNf∥22=8π2∑k>N, k impar1k2≈4π2N\norm{f - S_N f}_2^2 = \frac{8}{\pi^2}\sum_{k > N,\ k \text{ impar}}\frac{1}{k^2} \approx \frac{4}{\pi^2 N}. Error in L2L^2 decays as N−1/2N^{-1/2} with jumps and, by the same calculation, as N−3/2N^{-3/2} with corners; you will measure this in code.

Second, compute sums. The most famous example is the Basel problem, ∑k≥11/k2\sum_{k \ge 1}1/k^2, solved by Euler in 1735 with a bold infinite-product argument. With Parseval it is a calculation: you will do it in exercises using f(x)=xf(x) = x. Here is a similar example with the triangle wave, giving a result harder to obtain otherwise.

The Fourier transform

A signal on the line need not be periodic: a pulse, probability density or filter kernel lives on R\R. To reach the transform, let the period grow. With period PP, the series uses frequencies k/Pk/P (cycles per unit of xx) with coefficients ck=1P∫−P/2P/2f(x)e−2πixk/P ⁣dxc_k = \frac{1}{P}\int_{-P/2}^{P/2}f(x)e^{-2\pi i x k/P}\dd x. As P→∞P \to \infty, frequencies ξ=k/P\xi = k/P fill the line with spacing 1/P1/P, product P ckP\,c_k tends to a function of ξ\xi, and series f(x)=∑k(Pck) e2πixk/P 1Pf(x) = \sum_k (P c_k)\,e^{2\pi i x k/P}\,\frac{1}{P} resembles a Riemann sum. The limit suggests the following formulas.

The integral converges absolutely because ∣f(x)e−2πixξ∣=∣f(x)∣\abs{f(x)e^{-2\pi ix\xi}} = \abs{f(x)}, so ∣f^(ξ)∣≤∫∣f∣\abs{\hat f(\xi)} \le \int\abs{f}. Also f^\hat f is continuous and, as with series, tends to zero at infinity (Riemann–Lebesgue lemma). Variable ξ\xi is frequency in cycles per unit of xx: if xx is seconds, ξ\xi is hertz.

Conventions: where 2π2\pi goes

Different communities put 2π2\pi in different places, and confusing them is the most common transform error. The three usual conventions:

ConventionTransformInversePlancherelUsed by
Ordinary frequency ξ\xi∫f(x)e−2πixξ ⁣dx\int f(x)e^{-2\pi ix\xi}\dd x∫f^(ξ)e2πixξ ⁣dξ\int\hat f(\xi)e^{2\pi ix\xi}\dd\xi∥f^∥2=∥f∥2\norm{\hat f}_2 = \norm{f}_2this lesson, signal processing, discrete numpy.fft
Angular frequency ω\omega, asymmetric∫f(x)e−iωx ⁣dx\int f(x)e^{-i\omega x}\dd x12π∫F(ω)eiωx ⁣dω\frac{1}{2\pi}\int F(\omega)e^{i\omega x}\dd\omega∥F∥22=2π∥f∥22\norm{F}_2^2 = 2\pi\norm{f}_2^2physics, PDEs, probability
Angular frequency, unitary12π∫f(x)e−iωx ⁣dx\frac{1}{\sqrt{2\pi}}\int f(x)e^{-i\omega x}\dd x12π∫F(ω)eiωx ⁣dω\frac{1}{\sqrt{2\pi}}\int F(\omega)e^{i\omega x}\dd\omegano constantsquantum mechanics, some analysis texts

All three are the same operation with rescaled variable: F(ω)=f^(ω/2π)F(\omega) = \hat f(\omega/2\pi) in the second. The characteristic function of a random variable with density pp, φ(t)=E[eitX]=∫p(x)eitx ⁣dx\varphi(t) = \E[e^{itX}] = \int p(x)e^{itx}\dd x, also uses the opposite sign: φ(t)=p^(−t/2π)\varphi(t) = \hat p(-t/2\pi). Ours has two advantages: no constants before either integral and Gaussian e−πx2e^{-\pi x^2} is its own transform.

Frequently used properties

All follow from substitution or integration by parts. For f∈L1(R)f \in L^1(\R):

Operation on ffEffect on f^\hat f
Translation f(x−a)f(x - a)modulation e−2πiaξf^(ξ)e^{-2\pi ia\xi}\hat f(\xi)
Modulation e2πiaxf(x)e^{2\pi i a x}f(x)translation f^(ξ−a)\hat f(\xi - a)
Scaling f(x/s)f(x/s), s>0s > 0s f^(sξ)s\,\hat f(s\xi): stretching in xx compresses in ξ\xi
Derivative f′(x)f'(x) (with f′∈L1f' \in L^1, f→0f \to 0 in ±∞\pm\infty)2πiξ f^(ξ)2\pi i\xi\,\hat f(\xi)
−2πix f(x)-2\pi i x\,f(x) (with xf∈L1xf \in L^1)derivative f^′(ξ)\hat f'(\xi)
ff realHermitian symmetry f^(−ξ)=f^(ξ)‾\hat f(-\xi) = \overline{\hat f(\xi)}
ff real and evenf^\hat f real and even

The scaling rule quantifies “narrow in time, wide in frequency”. The derivative rule is the same as for series: differentiation multiplies by frequency, so smoothness of ff translates to decay of f^\hat f. The fifth, for −2πix f(x)-2\pi ix\,f(x), is justified by differentiation under the integral sign (Leibniz’s rule), with integrable bound ∣∂ξ(f(x)e−2πixξ)∣=2π∣x∣∣f(x)∣\abs{\partial_\xi(f(x)e^{-2\pi ix\xi})} = 2\pi\abs{x}\abs{f(x)} dominating.

The Gaussian, a fixed point of the transform

Proof

Let φ(ξ)\varphi(\xi) be the integral. Differentiating under the integral sign (dominated by 2π∣x∣e−πx22\pi\abs{x}e^{-\pi x^2}) and using −2πix e−πx2=i ⁣d ⁣dxe−πx2-2\pi ix\,e^{-\pi x^2} = i\frac{\dd}{\dd x}e^{-\pi x^2}, integration by parts gives

φ′(ξ)=i∫−∞∞( ⁣d ⁣dxe−πx2)e−2πixξ ⁣dx=−i∫−∞∞e−πx2 (−2πiξ) e−2πixξ ⁣dx=−2πξ φ(ξ),\varphi'(\xi) = i\int_{-\infty}^{\infty}\Big(\frac{\dd}{\dd x}e^{-\pi x^2}\Big)e^{-2\pi ix\xi}\dd x = -i\int_{-\infty}^{\infty}e^{-\pi x^2}\,(-2\pi i\xi)\,e^{-2\pi ix\xi}\dd x = -2\pi\xi\,\varphi(\xi),

with no boundary terms because e−πx2→0e^{-\pi x^2} \to 0. This linear ODE has solution φ(ξ)=φ(0)e−πξ2\varphi(\xi) = \varphi(0)e^{-\pi\xi^2}, and φ(0)=∫e−πx2 ⁣dx=1\varphi(0) = \int e^{-\pi x^2}\dd x = 1 by the Gaussian integral. The general version follows from the scaling rule with f(x)=e−πx2f(x) = e^{-\pi x^2} and x↦x/(s2π)x \mapsto x/(s\sqrt{2\pi}).

∎

A Gaussian of width ss transforms into a Gaussian of width proportional to 1/s1/s. The product of widths is constant: the first hint of the uncertainty principle. This theorem also makes the characteristic function a tool for proving the central limit theorem: the normal transform is another Gaussian.

For L1∩L2L^1 \cap L^2 functions, the Plancherel identity also holds, ∫∣f∣2=∫∣f^∣2\int\abs{f}^2 = \int\abs{\hat f}^2, Parseval’s continuous analog; the transform thereby extends to an isometry of L2(R)L^2(\R) onto itself. The proof of inversion and Plancherel uses the Gaussian as an approximation kernel (the continuous version of Fejér’s argument); see Stein and Shakarchi chapter 5, and return to it with inversion and uniqueness in probability.

The uncertainty principle

For a function with ∥f∥2=1\norm{f}_2 = 1, ∣f∣2\abs{f}^2 is a probability density on xx and, by Plancherel, ∣f^∣2\abs{\hat f}^2 is one on ξ\xi. Call their standard deviations Δx\Delta x and Δξ\Delta\xi: they measure how much the function spreads in space and frequency.

Proof

Integrating by parts with x′=1x' = 1 (the boundary term vanishes by hypothesis),

1=∫∣f∣2 ⁣dx=−∫x  ⁣d ⁣dx∣f∣2 ⁣dx=−∫x(f′fˉ+ffˉ′) ⁣dx=−2Re⁡∫xf(x) f′(x)‾ ⁣dx.1 = \int\abs{f}^2\dd x = -\int x\,\frac{\dd}{\dd x}\abs{f}^2\dd x = -\int x\big(f'\bar f + f\bar f'\big)\dd x = -2\operatorname{Re}\int x f(x)\,\overline{f'(x)}\dd x.

By Cauchy–Schwarz, 1≤2(∫x2∣f∣2)1/2(∫∣f′∣2)1/21 \le 2\big(\int x^2\abs{f}^2\big)^{1/2}\big(\int\abs{f'}^2\big)^{1/2}. By Plancherel and the derivative rule, ∫∣f′∣2=∫∣2πiξf^(ξ)∣2 ⁣dξ=4π2∫ξ2∣f^∣2\int\abs{f'}^2 = \int\abs{2\pi i\xi\hat f(\xi)}^2\dd\xi = 4\pi^2\int\xi^2\abs{\hat f}^2. Squaring, 1≤16π2(∫x2∣f∣2)(∫ξ2∣f^∣2)1 \le 16\pi^2\big(\int x^2\abs{f}^2\big)\big(\int\xi^2\abs{\hat f}^2\big). Equality in Cauchy–Schwarz requires f′=−c xff' = -c\,xf with cc real positive (also making the real part maximal), whose solution is a Gaussian.

∎

This is not an instrument limitation: it is a theorem about functions. A short-lived signal necessarily contains many frequencies, and resolving nearby frequencies requires observing for a long time. In quantum mechanics the transform relates the position wavefunction to the momentum wavefunction (p=hξp = h\xi), and the inequality becomes Δx Δp≥h/(4π)=ℏ/2\Delta x\,\Delta p \ge h/(4\pi) = \hbar/2.

InteractiveNarrow in time, wide in frequency
f(x)f(x) and the band ±Δx\pm\Delta x
−4−2024
f^(ξ)\hat f(\xi) (normalized) and the band ±Δξ\pm\Delta\xi
−3−2−10123
The (Δx,Δξ)(\Delta x, \Delta\xi) plane on log-log axes: no function lies below the bound
0.110.11ΔxΔξΔx·Δξ < 1/(4π): imposible
  • bound Δx Δξ=1/(4π)\Delta x\,\Delta\xi = 1/(4\pi) (Gaussians)
  • two-sided exponential (2\sqrt 2 times) and triangle (1.2\sqrt{1.2} times)
  • path of chosen shape as ss varies
0.50
Δx\Delta x0.354
Δξ\Delta \xi0.225
Δx Δξ\Delta x\,\Delta\xi0.0796
Bound 1/(4π)1/(4\pi)0.0796
Product / bound1.000
The Gaussian attains the bound: Δx Δξ=1/(4π)\Delta x\,\Delta\xi = 1/(4\pi) for any ss. Narrowing it in xx widens it in ξ\xi by the same factor.
Above, the function and its transform (normalized to height 1) with bands ±Δx\pm\Delta x and ±Δξ\pm\Delta\xi. Below, each function is a point in plane (Δx,Δξ)(\Delta x, \Delta\xi) on log-log scale, and shaded region Δx Δξ<1/(4π)\Delta x\,\Delta\xi < 1/(4\pi) is forbidden. Move Gaussian width ss: its point slides along the bound without leaving it. Switch to the double exponential or triangle: the point follows a parallel line above, because scaling does not change the product and only shape determines distance. The rectangle, with jumps, has Δξ=∞\Delta\xi = \infty. The wave packet, with two peaks at ±ξ0\pm\xi_0, moves away from the bound as ξ0\xi_0 increases.

Figure constants can be calculated by hand. For double exponential e−∣x∣/se^{-\abs{x}/s}, Δx=s/2\Delta x = s/\sqrt2 and Δξ=1/(2πs)\Delta\xi = 1/(2\pi s), so the product is 2\sqrt 2 times the bound; for the triangle, Δx=s/10\Delta x = s/\sqrt{10}, Δξ=3/(2πs)\Delta\xi = \sqrt3/(2\pi s) and the factor is 1.2≈1.095\sqrt{1.2} \approx 1.095. The triangle coming so close is no accident: it is bell-shaped and has no jumps.

Convolution and the convolution theorem

There are three interpretations of the same formula. As a moving average: (f∗g)(x)(f * g)(x) averages values of ff around xx with weights of gg reflected and centered at xx. As a sum of random variables: if XX and YY are independent with densities ff and gg, density of X+YX + Y is f∗gf * g (convolution of densities). And as a translation-invariant linear system: every linear filter commuting with translations is convolution with its impulse response, what a convolutional layer computes (discrete 2D convolution).

Convolution is commutative (replace yy by x−yx - y), associative and bilinear; by Fubini, ∫∣f∗g∣≤∫∣f∣∫∣g∣\int\abs{f * g} \le \int\abs{f}\int\abs{g}, so f∗g∈L1f * g \in L^1, and the same calculation without absolute values gives ∫f∗g=∫f∫g\int f * g = \int f\int g: masses multiply. It inherits the better regularity of its factors: if gg is C1C^1 with g′g' bounded, (f∗g)′=f∗g′(f * g)' = f * g', by Leibniz’s rule. Convolution with a smooth function smooths. For densities, the probabilistic interpretation also says means and variances add, because they do for sums of independent variables.

This is the convolution theorem: convolution in space is multiplication in frequency. The proof is three lines with Fubini, done step by step in the exercises. The periodic version is identical: with (f∗g)(x)=12π∫−ππf(y)g(x−y) ⁣dy(f * g)(x) = \frac{1}{2\pi}\int_{-\pi}^{\pi}f(y)g(x - y)\dd y, f∗g^(k)=f^(k)g^(k)\widehat{f * g}(k) = \hat f(k)\hat g(k). You have already used it without naming it: SNf=f∗DNS_N f = f * D_N multiplies coefficients by the indicator of ∣k∣≤N\abs{k} \le N (an abrupt cutoff), and σNf=f∗FN\sigma_N f = f * F_N by triangular window (1−∣k∣N+1)+\big(1 - \frac{\abs k}{N+1}\big)_+ (a smooth cutoff). The difference between Gibbs and its absence is the difference between these windows.

InteractiveConvolution in space, product in frequency
Space: f(y)f(y), g(x−y)g(x - y) and their product
−4−2024
Frequency: ∣f^(ξ)∣|\hat f(\xi)|, ∣g^(ξ)∣|\hat g(\xi)| and ∣f^ g^∣|\hat f\,\hat g|
−3−2−10123
  • ff and ∣f^∣|\hat f|
  • g(x−y)g(x - y) and ∣g^∣|\hat g|
  • f∗gf * g and ∣f^ g^∣|\hat f\,\hat g|
  • numerical transform of f∗gf * g computed in space
First function
2.00
Sliding kernel
0.30
Position
0.80
(f∗g)(x)(f * g)(x) = shaded area0.3737
Mass of f∗gf * g1.0000
Var⁡(f∗g)\operatorname{Var}(f * g) versus Var⁡f+Var⁡g\operatorname{Var} f + \operatorname{Var} g0.4233 vs 0.4233
∣g^(1)∣|\hat g(1)|: how much gg passes at ξ=1\xi = 10.1692
max⁡∣f∗g^−f^ g^∣\max|\widehat{f * g} - \hat f\,\hat g| (quadrature)1.3·10⁻⁵
The Gaussian with σ=0.30\sigma = 0.30 multiplies frequency ξ\xi by e−2π2σ2ξ2e^{-2\pi^2\sigma^2\xi^2}: it passes low frequencies and suppresses high ones. At ξ=1\xi = 1, 16.9% remains.
In the space panel, g(x−y)g(x - y) (orange, reflected) slides over f(y)f(y) (blue); magenta product area f(y) g(x−y)f(y)\,g(x - y) is value (f∗g)(x)(f * g)(x), drawn as xx advances. In frequency, magnitudes ∣f^∣|\hat f|, ∣g^∣|\hat g| and their product, and circles for the numerically computed transform of the spatial convolution: they lie on the product. Start with the rectangle smoothed by a Gaussian and widen σ\sigma: edges round and the sinc's side lobes disappear in frequency. Try two equal-width rectangles (a triangle, with transform sinc⁡2\operatorname{sinc}^2; different widths give a trapezoid) and the causal exponential, which delays the signal. Check the readouts that variances add.

Smoothing is low-pass filtering

Convolving with normal density ϕσ\phi_\sigma of standard deviation σ\sigma multiplies each frequency by ϕ^σ(ξ)=e−2π2σ2ξ2\hat\phi_\sigma(\xi) = e^{-2\pi^2\sigma^2\xi^2}: a factor equal to 11 at ξ=0\xi = 0 (mass is conserved) and falling rapidly from ξ≈1/(2πσ)\xi \approx 1/(2\pi\sigma). Thus Gaussian blur erases fine detail and leaves large shapes. It is also the solution of the heat equation ∂tu=∂xxu\partial_t u = \partial_{xx}u: u(⋅,t)=f∗ϕ2tu(\cdot, t) = f * \phi_{\sqrt{2t}}, or u^(ξ,t)=e−4π2ξ2tf^(ξ)\hat u(\xi, t) = e^{-4\pi^2\xi^2 t}\hat f(\xi) in frequency. Each frequency decays exponentially at a rate proportional to ξ2\xi^2, so heat smooths: highs die first. Fourier invented his series exactly to solve this equation, with the separation of variables from lesson 19.

The theorem also says what cannot be done. Undoing a convolution (deblurring) means dividing by g^\hat g, and where g^\hat g is nearly zero any noise is multiplied by a huge number. Deconvolution is ill-conditioned and therefore regularized.

From series to DFT: sampling and aliasing

A computer stores samples, not functions. Take MM equally spaced points xj=2πj/Mx_j = 2\pi j/M, j=0,…,M−1j = 0, \dots, M - 1, and approximate coefficient f^(n)\hat f(n) by the trapezoidal rule, simply the mean for periodic functions:

f^(n)≈1M∑j=0M−1f(xj) e−2πijn/M=XnM.\hat f(n) \approx \frac{1}{M}\sum_{j = 0}^{M - 1}f(x_j)\,e^{-2\pi i jn/M} = \frac{X_n}{M}.

Vector (X0,…,XM−1)(X_0, \dots, X_{M-1}) is the discrete Fourier transform (DFT) of the samples: multiplication by the DFT matrix, whose columns are orthogonal. If ff is continuous and its series absolutely convergent (allowing sums to be reordered), their exact relationship is simple. Substitute f(xj)=∑kf^(k)e2πijk/Mf(x_j) = \sum_k\hat f(k)e^{2\pi ijk/M} and use that 1M∑je2πij(k−n)/M\frac1M\sum_j e^{2\pi ij(k - n)/M} equals 11 if k≡n(modM)k \equiv n \pmod M and 00 otherwise,

XnM=∑m∈Zf^(n+mM).\frac{X_n}{M} = \sum_{m \in \Z}\hat f(n + mM).

This is the aliasing formula: on the grid frequencies nn and n+Mn + M are indistinguishable, because e2πij(n+M)/M=e2πijn/Me^{2\pi ij(n + M)/M} = e^{2\pi ijn/M} for every jj, and the DFT adds all in the same class. If f^(k)=0\hat f(k) = 0 for ∣k∣≥M/2\abs{k} \ge M/2, only one term remains and samples determine ff exactly; otherwise high frequencies masquerade as low ones. This is the periodic sampling theorem: sample at more than twice the maximum frequency (Nyquist limit). On the line too, with step hh, the highest representable frequency is 1/(2h)1/(2h).

Three practical consequences. The DFT of the circular convolution of two vectors is the product of their DFTs, so obtaining linear convolution requires zero-padding (you will implement this in an exercise). Approximation Xn/M≈f^(n)X_n/M \approx \hat f(n) inherits coefficient decay: excellent for smooth functions, mediocre with jumps. Computing DFT from its definition costs O(M2)\bigO(M^2), while FFT costs O(Mlog⁡M)\bigO(M\log M); study it with FFT convolution in the DFT and FFT lesson and in more detail in numerical aliasing.

Frontier: spectral bias in networks

Rahaman and coauthors (2019) observed that a ReLU MLP trained by gradient descent learns target components in frequency order: low first, high much later. A quantitative explanation came with the tangent-kernel regime: there gradient descent fits each target component at a rate proportional to a kernel eigenvalue, and for usual networks these eigenvalues decay rapidly with frequency. Study this as spectral bias in deep learning theory. The bias is partly a virtue (smooth functions generalize) and partly a problem: an MLP taking coordinates (x,y)(x, y) and returning color produces blurry images.

Tancik and coauthors (2020) proposed a simple fix: give the network not v\vb{v} but Fourier features γ(v)=[cos⁡(2πBv),sin⁡(2πBv)]\gamma(\vb{v}) = [\cos(2\pi\mat{B}\vb{v}), \sin(2\pi\mat{B}\vb{v})], with B\mat{B} a random-frequency matrix N(0,σ2)\Normal(0, \sigma^2). The induced kernel becomes stationary, with bandwidth controlled by σ\sigma: with small σ\sigma the network remains slow on detail; with suitable σ\sigma it learns high frequencies in few iterations; with excessive σ\sigma it fits training points and generalizes poorly between them. It is the same idea as transformer sinusoidal positional encodings, taken by RoPE to rotations at multiple frequencies, coordinate Fourier features in NeRF, and the analogous problem in physics-informed networks (PINN spectral bias).

The experiment fits in one cell. Fit f(x)=∑k∈{1,5,10,20}sin⁡(2πkx)f(x) = \sum_{k \in \{1, 5, 10, 20\}}\sin(2\pi kx) at 256 points of [0,1)[0, 1) with an MLP of three 256-neuron hidden layers on the GPU (usual device placement), a minimal training loop and Adam. Every 25 steps measure, using FFT of predictions on the grid, relative error of each of four coefficients.

[ ]MLP spectral bias and Fourier featuresLocal GPU
import time
import numpy as np
import torch
import matplotlib.pyplot as plt

dev = "cuda" if torch.cuda.is_available() else "cpu"
n = 256
x = torch.arange(n, device=dev, dtype=torch.float32) / n      # rejilla de entrenamiento en [0, 1)
x_test = x + 0.5 / n                                           # puntos intermedios, nunca vistos
frecs = [1, 5, 10, 20]
objetivo = lambda z: sum(torch.sin(2 * np.pi * k * z) for k in frecs)
y, y_test = objetivo(x), objetivo(x_test)
Y = torch.fft.rfft(y)                                          # Y[k] = coeficiente de la frecuencia k (sin normalizar)

def mlp(d_in):
    return torch.nn.Sequential(
        torch.nn.Linear(d_in, 256), torch.nn.ReLU(),
        torch.nn.Linear(256, 256), torch.nn.ReLU(),
        torch.nn.Linear(256, 256), torch.nn.ReLU(),
        torch.nn.Linear(256, 1)).to(dev)

def entrenar(caracteristicas, pasos, cada=25, semilla=1):
    torch.manual_seed(semilla)
    entrada, entrada_test = caracteristicas(x[:, None]), caracteristicas(x_test[:, None])
    red = mlp(entrada.shape[1])
    opt = torch.optim.Adam(red.parameters(), lr=1e-3)
    hist = []
    for t in range(pasos + 1):
        pred = red(entrada).squeeze(1)
        perdida = ((pred - y) ** 2).mean()
        if t % cada == 0:
            with torch.no_grad():
                P = torch.fft.rfft(pred)
                hist.append([t] + [(abs(P[k] - Y[k]) / abs(Y[k])).item() for k in frecs])
        opt.zero_grad(); perdida.backward(); opt.step()
    with torch.no_grad():
        err_test = ((red(entrada_test).squeeze(1) - y_test) ** 2).mean().item()
    return np.array(hist), perdida.item(), err_test

def primer_paso(h, umbral=0.1):
    return [int(h[np.argmax(h[:, 1 + j] < umbral), 0]) if (h[:, 1 + j] < umbral).any() else None for j in range(len(frecs))]

t0 = time.time()
h_xy, ent, test = entrenar(lambda z: z, pasos=10000)
print(f"MLP sobre x ({time.time() - t0:.0f} s): pérdida final {ent:.2e}, error en puntos nuevos {test:.2e}")
print("  paso en que el error relativo de cada frecuencia baja de 0.1:", dict(zip(frecs, primer_paso(h_xy))))
print("  error relativo final por frecuencia:", {k: round(float(e), 3) for k, e in zip(frecs, h_xy[-1, 1:])})

resultados = {}
for sigma in [1, 10, 100]:
    torch.manual_seed(2)
    B = torch.randn(1, 64, device=dev) * sigma
    gamma = lambda z, B=B: torch.cat([torch.cos(2 * np.pi * z @ B), torch.sin(2 * np.pi * z @ B)], dim=1)
    h, ent, test = entrenar(gamma, pasos=1000, cada=5)
    resultados[sigma] = h
    print(f"Fourier, sigma = {sigma:3d}: pérdida {ent:.1e}, error en puntos nuevos {test:.1e}, "
          f"pasos hasta error < 0.1 por frecuencia {dict(zip(frecs, primer_paso(h)))}")

fig, ax = plt.subplots(1, 2, figsize=(10, 3.6), sharey=True)
for j, k in enumerate(frecs):
    ax[0].semilogy(h_xy[:, 0], h_xy[:, 1 + j], label=f"k = {k}")
    ax[1].semilogy(resultados[10][:, 0], resultados[10][:, 1 + j], label=f"k = {k}")
ax[0].set_title("MLP sobre x"); ax[1].set_title("MLP sobre características de Fourier (σ = 10)")
for a in ax:
    a.axhline(0.1, color="gray", lw=0.8, ls="--"); a.set_xlabel("paso"); a.legend()
ax[0].set_ylabel("error relativo del coeficiente")
plt.tight_layout(); plt.show()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The order is clear: frequency 1 is learned in tens of steps, 5 in hundreds, 10 in thousands, and 20 remains unlearned after 10,000 steps, although the network has ample capacity. With Fourier features of σ=10\sigma = 10, all four frequencies drop below 10% error in a few dozen steps and error between points is tiny. With σ=1\sigma = 1 the earlier order returns, though faster; with σ=100\sigma = 100 the network perfectly fits all 256 training points and fails between them: it learned frequencies the grid cannot distinguish (aliasing again).

Implementation from scratch

Start with coefficients. A periodic function’s integral over a period is exceptionally well approximated by the trapezoidal rule on a uniform grid, here the sample mean. Compare with exact coefficients of four examples and measure decay.

[ ]Coefficients by quadrature and their decayBrowser
import numpy as np

def coeficientes(f, K, M=4096):
    """c_k = (1/2π) ∫ f(x) e^{-ikx} dx para k = -K..K, con la regla del trapecio periódica de M nodos."""
    x = -np.pi + 2 * np.pi * np.arange(M) / M
    k = np.arange(-K, K + 1)
    return k, (f(x)[None, :] * np.exp(-1j * np.outer(k, x))).mean(axis=1)

def exactos(nombre, k):
    kk = np.where(k == 0, 1, k)                      # evita dividir por cero; k = 0 se trata aparte
    impar = (k % 2 == 1)
    if nombre == "cuadrada":
        return np.where(impar, 2 / (1j * np.pi * kk), 0)
    if nombre == "diente de sierra":
        return np.where(k == 0, 0, 1j * (-1.0) ** k / kk)
    if nombre == "triangular":
        return np.where(k == 0, np.pi / 2, np.where(impar, -2 / (np.pi * kk**2), 0))
    return np.where(k == 0, 0, 0.5 ** np.abs(k) / 2)   # suave: sum_{k>=1} r^k cos kx con r = 1/2

r = 0.5
funciones = {
    # en los nodos que caen sobre un salto (0 y −π) tomamos el punto medio del salto
    "cuadrada": lambda x: np.where(x == -np.pi, 0.0, np.sign(x)),
    "diente de sierra": lambda x: np.where(x == -np.pi, 0.0, x),
    "triangular": np.abs,
    "suave": lambda x: (r * np.cos(x) - r**2) / (1 - 2 * r * np.cos(x) + r**2),
}
K = 64
for nombre, f in funciones.items():
    k, c = coeficientes(f, K)
    err = np.max(np.abs(c - exactos(nombre, k)))
    impares = np.arange(5, K, 2)
    mag = np.abs(c[K + impares])
    pendiente = np.polyfit(np.log(impares), np.log(mag), 1)[0]
    print(f"{nombre:17s} error frente al exacto {err:.1e}   pendiente log|c_k| vs log k {pendiente:7.2f}   |c_9 / c_7| = {mag[2] / mag[1]:.3f}")

With jumps, quadrature error is of order 10−510^{-5}: the trapezoidal rule ceases to be spectral and becomes order 1/M21/M^2, and only because jump nodes use the midpoint (with a one-sided value such as −1-1 returned by np.sign(-np.pi), error rises to 2.4⋅10−42.4 \cdot 10^{-4}, order 1/M1/M). With triangle corners it falls to 10−710^{-7}, and with the smooth function it is rounding error because for analytic periodic functions the trapezoidal rule converges geometrically. Slopes are −1-1, −1-1 and −2-2; for the smooth function slope is meaningless: ratio ∣c9/c7∣=0.25=r2\abs{c_9/c_7} = 0.25 = r^2 reveals geometric decay. Compare with 7/9=0.7787/9 = 0.778 for 1/k1/k and (7/9)2=0.605(7/9)^2 = 0.605 for 1/k21/k^2.

Now reconstruction. Error in L2L^2 is obtained for free by Parseval, summing the coefficient tail, and checked against direct integration. Then measure the Gibbs peak for increasing NN and compare with 2πSi⁡(π)\frac{2}{\pi}\operatorname{Si}(\pi), calculated by Simpson’s rule.

[ ]L² error, Parseval and the Gibbs peakBrowser
import numpy as np
import matplotlib.pyplot as plt

def cola(N, amplitud, K=400000):
    """‖f − S_N f‖₂ = (Σ_{|k|>N} |c_k|²)^{1/2} para coeficientes no nulos solo en los impares."""
    k = np.arange(N + 1, K, dtype=float)
    k = k[k % 2 == 1]
    return np.sqrt(2 * np.sum(amplitud(k) ** 2))

Ns = np.array([4, 16, 64, 256, 1024])
e_cuad = np.array([cola(N, lambda k: 2 / (np.pi * k)) for N in Ns])        # sign(x)
e_tri = np.array([cola(N, lambda k: 2 / (np.pi * k**2)) for N in Ns])      # |x|
for N, a, b in zip(Ns, e_cuad, e_tri):
    print(f"N = {N:5d}   ‖f − S_N f‖₂   cuadrada {a:.2e}   triangular {b:.2e}")
print("pendientes log-log:", round(np.polyfit(np.log(Ns), np.log(e_cuad), 1)[0], 3), round(np.polyfit(np.log(Ns), np.log(e_tri), 1)[0], 3))

def S_cuadrada(x, N):
    k = np.arange(1, N + 1, 2)
    return (4 / np.pi) * (np.sin(np.outer(x, k)) / k).sum(axis=1)

x = np.linspace(-np.pi, np.pi, 100001)
directo = np.sqrt(np.mean((np.sign(x) - S_cuadrada(x, 16)) ** 2))
print(f"comprobación directa para N = 16: {directo:.4f}  (Parseval: {e_cuad[1]:.4f})")

for N in [9, 99, 999]:
    xs = np.linspace(1e-6, 3 * np.pi / (N + 1), 3001)
    s = S_cuadrada(xs, N)
    i = s.argmax()
    print(f"N = {N:4d}: máximo de S_N = {s[i]:.5f} en x = {xs[i]:.5f}   (π/(N+1) = {np.pi / (N + 1):.5f})")

t = np.linspace(0, np.pi, 20001)
y = np.sinc(t / np.pi)                                    # sin(t)/t, con valor 1 en t = 0
h = t[1] - t[0]
Si = h / 3 * (y[0] + y[-1] + 4 * y[1:-1:2].sum() + 2 * y[2:-1:2].sum())
print(f"límite (2/π) Si(π) = {2 / np.pi * Si:.6f}   sobreoscilación = {100 * (Si / np.pi - 0.5):.3f} % del salto")

fig, ax = plt.subplots(1, 2, figsize=(10, 3.4))
xz = np.linspace(-0.6, 0.6, 2001)
for N in [9, 29, 99]:
    ax[0].plot(xz, S_cuadrada(xz, N), lw=1.2, label=f"N = {N}")
ax[0].axhline(2 / np.pi * Si, color="gray", ls="--", lw=0.8); ax[0].set_title("Gibbs: el pico no baja"); ax[0].legend()
ax[1].loglog(Ns, e_cuad, "o-", label="cuadrada, ∝ N^(-1/2)")
ax[1].loglog(Ns, e_tri, "s-", label="triangular, ∝ N^(-3/2)")
ax[1].set_xlabel("N"); ax[1].set_title("‖f − S_N f‖₂"); ax[1].legend()
plt.tight_layout(); plt.show()

Slopes are −0.5-0.5 and −1.5-1.5, as Parseval predicts. The maximum of SNS_N sits exactly at π/(N+1)\pi/(N + 1) and its height goes from 1.18231.1823 with N=9N = 9 to 1.179011.17901 with N=99N = 99 and 1.178981.17898 with N=999N = 999, close to limit 1.1789801.178980, 8.9498.949% of the jump.

Finally filtering. A signal with a step and smooth oscillation is contaminated with white noise; compare two cleaning methods: truncate the series (keep ∣k∣≤K0\abs{k} \le K_0, an ideal low-pass filter) and convolve with a narrow Gaussian. We compute Gaussian convolution both in space and as a coefficient product to see the convolution theorem work.

[ ]Denoising: truncation versus smoothingBrowser
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(0)
M = 1024
x = -np.pi + 2 * np.pi * np.arange(M) / M
limpia = np.where(np.abs(x) < 1.0, 1.0, 0.0) + 0.5 * np.sin(2 * x)
ruidosa = limpia + 0.3 * rng.standard_normal(M)

k = np.fft.fftfreq(M, d=1 / M)            # frecuencias enteras en el orden de numpy: 0, 1, ..., M/2 - 1, -M/2, ..., -1
C = np.fft.fft(ruidosa)

def truncar(K0):
    return np.fft.ifft(np.where(np.abs(k) <= K0, C, 0)).real

def suavizar(s):                            # gaussiana de anchura s (radianes): multiplica la frecuencia k por e^{-s²k²/2}
    return np.fft.ifft(C * np.exp(-0.5 * (s * k) ** 2)).real

def suavizar_en_el_espacio(s):              # la misma operación como convolución circular directa
    d = np.minimum(np.arange(M), M - np.arange(M)) * (2 * np.pi / M)
    nucleo = np.exp(-0.5 * (d / s) ** 2)
    nucleo /= nucleo.sum()
    return np.array([np.dot(ruidosa, np.roll(nucleo[::-1], j + 1)) for j in range(M)])

rmse = lambda y: np.sqrt(np.mean((y - limpia) ** 2))
lejos = np.abs(np.abs(x) - 1.0) > 0.6       # zona sin saltos
print(f"señal ruidosa: RMSE {rmse(ruidosa):.3f}")
for K0 in [5, 10, 20, 40, 80]:
    y = truncar(K0)
    print(f"truncar |k| ≤ {K0:2d}:     RMSE {rmse(y):.3f}   lejos de los saltos {np.sqrt(np.mean((y - limpia)[lejos] ** 2)):.3f}")
for s in [0.02, 0.05, 0.1, 0.2]:
    y = suavizar(s)
    print(f"gaussiana s = {s:.2f}: RMSE {rmse(y):.3f}   lejos de los saltos {np.sqrt(np.mean((y - limpia)[lejos] ** 2)):.3f}")
print("espacio frente a frecuencia, diferencia máxima:", np.max(np.abs(suavizar_en_el_espacio(0.05) - suavizar(0.05))))

plt.figure(figsize=(10, 3.2))
plt.plot(x, ruidosa, color="0.8", lw=0.6, label="ruidosa")
plt.plot(x, truncar(20), lw=1.4, label="truncar |k| ≤ 20")
plt.plot(x, suavizar(0.05), lw=1.4, label="gaussiana s = 0.05")
plt.plot(x, limpia, "k--", lw=1, label="limpia")
plt.xlim(-2, 2); plt.legend(loc="lower center", ncol=4); plt.tight_layout(); plt.show()

Best truncation (K0=20K_0 = 20) leaves RMSE 0.0880.088 and best tested Gaussian (s=0.05s = 0.05), 0.0800.080. The clearest difference is in the graph: truncation produces Gibbs ringing around each jump and on flat areas because the sharp frequency cutoff convolves with an oscillating Dirichlet kernel; the Gaussian never oscillates. Both Gaussian convolution versions agree up to rounding (10−1510^{-15}): frequency costs O(Mlog⁡M)\bigO(M\log M) and space O(M2)\bigO(M^2). Note the tradeoff: from s=0.05s = 0.05, increasing ss lowers error away from jumps (more noise averaged) but raises overall error (jumps blur). Uncertainty again: one cannot filter strongly in frequency without widening in space.

The library version

FunctionComputesDetail to know
np.fft.fft(a)Xn=∑jaje−2πijn/MX_n = \sum_j a_j e^{-2\pi ijn/M}unnormalized; norm="ortho" divides by M\sqrt M and norm="forward" by MM
np.fft.ifft(X)1M∑nXne2πijn/M\frac1M\sum_n X_n e^{2\pi ijn/M}exact inverse of fft
np.fft.rfft(a, n)nonredundant half for real signalsn pads with zeros; irfft(X, n) needs length
np.fft.fftfreq(M, d)frequencies of each output, in cycles per unit of dorder 0,1,…,−10, 1, \dots, -1; fftshift centers them
scipy.signal.fftconvolvelinear convolution by FFTchooses padding for you
torch.fft.fft, rfftsame on GPU and differentiableused in the spectral-bias experiment

Connection with earlier material: with samples at xj=2πj/Mx_j = 2\pi j/M, np.fft.fft(f(x)) / M approximates f^(n)\hat f(n) in fftfreq order. If the grid starts at −π-\pi, multiply by einπ=(−1)ne^{in\pi} = (-1)^n, the phase of a translation. For the continuous transform with step hh, f^(ξ)≈h∑jf(xj)e−2πixjξ\hat f(\xi) \approx h\sum_j f(x_j)e^{-2\pi ix_j\xi} at frequencies ξ=\xi = fftfreq(M, d=h), and the function must be centered with ifftshift so the origin falls at index 00.

[ ]numpy.fft versus coefficients and the transformBrowser
import numpy as np

# 1. Aliasing: con 16 nodos, cos(13x) es indistinguible de cos(3x)
M = 16
x = 2 * np.pi * np.arange(M) / M
c = np.fft.fft(np.cos(3 * x) + 0.5 * np.cos(13 * x)) / M
k = np.fft.fftfreq(M, d=1 / M).astype(int)
print("coeficientes no nulos medidos con 16 nodos:", {int(kk): round(float(cc.real), 3) for kk, cc in zip(k, c) if abs(cc) > 1e-12})
print("cos(13 x_j) == cos(3 x_j):", np.allclose(np.cos(13 * x), np.cos(3 * x)), "  porque 13 = 16 − 3")

# 2. Coeficientes de la onda cuadrada con una rejilla que empieza en −π: hay que corregir la fase (−1)^n
M = 64
xm = -np.pi + 2 * np.pi * np.arange(M) / M
cuad = np.sign(xm)
cuad[0] = 0.0                                   # valor medio en el salto de ±π
n = np.fft.fftfreq(M, d=1 / M)
c_fft = np.fft.fft(cuad) / M * (-1.0) ** n
print("ĉ(1), ĉ(3) con FFT:", np.round(c_fft[[1, 3]], 4), "  exactos:", np.round([2 / (1j * np.pi), 2 / (3j * np.pi)], 4))

# 3. Transformada continua: la gaussiana e^{-πx²} es su propia transformada
N, h = 512, 0.05
xs = (np.arange(N) - N // 2) * h
G = h * np.fft.fft(np.fft.ifftshift(np.exp(-np.pi * xs**2)))
xi = np.fft.fftfreq(N, d=h)
print(f"max |G(ξ) − e^(−πξ²)| = {np.max(np.abs(G - np.exp(-np.pi * xi**2))):.1e}   con ξ hasta {xi.max():.2f} = 1/(2h) − 1/(Nh)")

With 16 nodes, frequency 13 is added to frequency 3: measured coefficient is 0.75=0.5+0.250.75 = 0.5 + 0.25 instead of 0.50.5. The square wave, with phase correction, gives coefficients close to exact −0.6366i-0.6366i and −0.2122i-0.2122i except for known aliasing error. The Gaussian is exact up to rounding: smooth and rapidly decaying in both domains, the ideal DFT case.

Common mistakes

Exercises

NumericFirst coefficient of the square wave
The square wave equals −1-1 on (−π,0)(-\pi, 0) and 11 on (0,π)(0, \pi). Calculate coefficient b1=1π∫−ππf(x)sin⁡x ⁣dxb_1 = \frac{1}{\pi}\int_{-\pi}^{\pi} f(x)\sin x \dd x of its sine series.
NumericHeight of the Gibbs peak
For the same square wave, what is the limiting maximum of partial sums SNfS_N f near the jump at x=0x = 0 as N→∞N \to \infty? Give four digits.
NumericParseval with the square wave
Apply Parseval's identity to the square wave and calculate ∑k impar1k2=1+19+125+⋯\sum_{k \text{ impar}} \frac{1}{k^2} = 1 + \frac19 + \frac1{25} + \cdots.
QuizReading regularity from the spectrum
Fourier coefficients of periodic function ff satisfy ∣f^(k)∣≈C/∣k∣3\abs{\hat f(k)} \approx C/\abs{k}^3 (and decay no faster). What should you expect of ff?
QuizWhich convergence is guaranteed
Which statements are true?

More than one answer may be correct.

NumericMinimum bandwidth
A signal has temporal spread Δx=0.25\Delta x = 0.25 (standard deviation of normalized ∣f∣2\abs{f}^2). What is the smallest possible Δξ\Delta\xi, with ξ\xi in cycles per unit of xx?
NumericAn integral via Plancherel
Calculate ∫−∞∞(sin⁡xx)2 ⁣dx\displaystyle\int_{-\infty}^{\infty}\Big(\frac{\sin x}{x}\Big)^2\dd x using that the transform of 1[∣x∣≤12]\ind[\abs{x} \le \frac12] is sin⁡πξπξ\frac{\sin \pi\xi}{\pi\xi}.
NumericA disguised frequency
Signal cos⁡(2π⋅9 t)\cos(2\pi\cdot 9\,t) (tt in seconds) is sampled at 10 samples per second. What frequency between 0 and 5 Hz does the DFT of the samples see?
ProofThe Basel problem with Parseval
Prove: ∑k=1∞1k2=π26\displaystyle\sum_{k=1}^{\infty}\frac{1}{k^2} = \frac{\pi^2}{6}.
0
Let f(x)=xf(x) = x on (−π,π)(-\pi, \pi), extended with period 2π2\pi. We will use Parseval's identity 12π∫−ππ∣f∣2=∑k∈Z∣f^(k)∣2\frac{1}{2\pi}\int_{-\pi}^{\pi}\abs{f}^2 = \sum_{k \in \Z}\abs{\hat f(k)}^2.

Step 1 of 4. What are coefficients f^(k)\hat f(k)?

ProofThe convolution theorem
Prove: If f,g:R→Cf, g: \R \to \C are continuous, bounded and absolutely integrable, then f∗g^(ξ)=f^(ξ) g^(ξ)\widehat{f * g}(\xi) = \hat f(\xi)\,\hat g(\xi) for every ξ∈R\xi \in \R.
0
By definition, f∗g^(ξ)=∫−∞∞(∫−∞∞f(y) g(x−y) ⁣dy)e−2πixξ ⁣dx\widehat{f * g}(\xi) = \int_{-\infty}^{\infty}\Big(\int_{-\infty}^{\infty} f(y)\,g(x - y)\dd y\Big)e^{-2\pi ix\xi}\dd x.

Step 1 of 3. You want to integrate first in xx. What justifies exchanging integration order?

CodeDirect convolution and FFT convolution
Implement conv_direct(a, b), full linear convolution cn=∑jajbn−jc_n = \sum_j a_j b_{n-j} (length len(a) + len(b) - 1), without using np.convolve, and conv_fft(a, b), which computes the same as a product of discrete transforms with zero-padding: pad both signals to n = len(a) + len(b) - 1, multiply their np.fft.rfft and return with np.fft.irfft(·, n). Tests check length, a hand-worked case, equality with np.convolve and that your FFT version is not circular convolution.
import numpy as np

def conv_direct(a, b):
  """Convolución lineal completa c[n] = sum_j a[j] b[n - j], de longitud len(a) + len(b) - 1."""
  a, b = np.asarray(a, dtype=float), np.asarray(b, dtype=float)
  # tu código
  return np.zeros(1)

def conv_fft(a, b):
  """La misma convolución como producto de DFT, con relleno de ceros."""
  a, b = np.asarray(a, dtype=float), np.asarray(b, dtype=float)
  # tu código
  return np.zeros(1)
Shift+Enter to run

Summary

Key idea
Square-integrable functions form an inner-product space in which exponentials eikxe^{ikx} form an orthonormal basis: Fourier coefficients are coordinates, partial sum is a projection, energy is conserved (Parseval), and convolution becomes multiplication. A function’s smoothness and coefficient decay rate are the same information.
  • L2L^2 is the space of functions with ∥f∥22=12π∫∣f∣2<∞\norm{f}_2^2 = \frac{1}{2\pi}\int\abs{f}^2 < \infty and product ⟨f,g⟩=12π∫fgˉ\inner{f}{g} = \frac{1}{2\pi}\int f\bar g. The ek=eikxe_k = e^{ikx} are orthonormal and SNf=∑∣k∣≤Nf^(k)ekS_N f = \sum_{\abs k \le N}\hat f(k)e_k is the best degree-NN approximation in L2L^2.
  • Coefficients decay as 1/k1/k with jumps, 1/k21/k^2 with corners, faster as ff becomes more differentiable and geometrically if analytic, because differentiation multiplies by ikik.
  • Convergence: in L2L^2 always (the system is complete); pointwise to the midpoint for piecewise-C1C^1 functions, but not every continuous one; uniform if ff is continuous and piecewise C1C^1. Near a jump, Gibbs leaves overshoot 8.958.95% of jump height that does not disappear.
  • Parseval, ∥f∥22=∑∣f^(k)∣2\norm{f}_2^2 = \sum\abs{\hat f(k)}^2, measures truncation errors without integration and calculates sums such as ∑1/k2=π2/6\sum 1/k^2 = \pi^2/6 or ∑1/k4=π4/90\sum 1/k^4 = \pi^4/90.
  • Transform f^(ξ)=∫f(x)e−2πixξ ⁣dx\hat f(\xi) = \int f(x)e^{-2\pi ix\xi}\dd x turns translations into phases, scalings into inverse scalings and derivatives into multiplication by 2πiξ2\pi i\xi. Gaussian e−πx2e^{-\pi x^2} is its own fixed point and uniquely attains uncertainty bound Δx Δξ≥1/(4π)\Delta x\,\Delta\xi \ge 1/(4\pi).
  • f∗g^=f^ g^\widehat{f * g} = \hat f\,\hat g: smoothing with a Gaussian attenuates frequency ξ\xi by e−2π2σ2ξ2e^{-2\pi^2\sigma^2\xi^2}. On sampling, the DFT sums frequencies coinciding modulo MM (aliasing), and FFT convolution requires zero-padding.
  • Gradient-trained networks learn low frequencies first; input Fourier features change that bias, with σ\sigma controlling bandwidth.