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
- 03Riemann integralImproper integralIntegration by substitution and by partsPointwise and uniform convergenceWeierstrass approximation theoremInterchange of limitsGaussian integralLeibniz integral ruleAbsolute and conditional convergenceFubini theorem
- 02Inner productOrthonormal basisOrthogonal projection
- 00Canonical training and evaluation loopDevice placement and CPU-GPU transfers
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 . 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 , 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:
Rearranging, and : a cosine is the sum of two rotations in opposite directions. Function , with , traces the unit circle times as goes from to and is -periodic. A complex function of a real variable is integrated componentwise, , and with that definition the usual rules still hold (linearity, substitution, parts, the fundamental theorem with ). The calculation underlying the whole lesson is:
because for every integer . An exponential making a nonzero integer number of turns averages to zero.
Functions as vectors
In the inner product adds products coordinate by coordinate, . A function is a vector with a coordinate for each point , and the sum becomes an integral. This analogy, taken seriously, gives everything we need.
The inner product of functions
Factor is a normalization: it makes constant function have norm and be the mean value of , a signal’s “mean power”. The inner-product axioms are easily checked: linearity in the first argument, conjugate symmetry and . As in any inner-product space, Cauchy–Schwarz , 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 , making the lesson interesting. Dimension is infinite, so “writing in a basis” means summing a series and we must specify how it converges. Norm measures mean-square error, not maximum error: functions can be close in and far apart in supremum norm. That gap is exactly what you will see in the Gibbs phenomenon.
The trigonometric system is orthonormal
Write for . The review calculation says
Exponentials form an orthonormal system: infinitely many unit vectors pairwise perpendicular. In real form, functions () do too, because and are combinations of and .
The best approximation is a projection
Fix and consider the subspace of trigonometric polynomials of degree at most , , of dimension . Given , which element of is closest to in ? In the answer is orthogonal projection, computed coordinate by coordinate with an orthonormal basis. Here it is the same.
Proof
(1) For , , and by linearity is orthogonal to any combination of the . (2) with the second summand in ; by (1) the summands are orthogonal and Pythagoras suffices. The minimum is attained only if , that is, . (3) Pythagoras with and by orthonormality. Partial sums of are bounded by , so the series converges with that bound.
∎This is least squares in infinite dimensions: is the least-squares fit of with basis functions, and no system needs solving because the basis is orthonormal. A consequence used shortly: since , the general term tends to zero.
A Riemann-integrable function is bounded, hence and the Bessel series converges. Intuitively, integrating against increasingly rapid oscillation averages its positive and negative values: the pieces of supporting each oscillation are nearly constant.
Fourier series
We have not yet asserted convergence: the series is a formal object associated with , and the sense in which holds is the theory’s heart. Three practical observations. If is even, the vanish and only cosines remain; if odd, only sines. If is real, , and the information is in . If the period is instead of , the exponentials are and the normalization factor .
Three complete examples
Compare magnitudes: coefficients of square and sawtooth waves, which have jumps, decay as ; those of the continuous triangle wave with corners as . Before explaining why, experiment with partial sums.
Three things the figure shows and the rest of the section explains. Error in always falls when terms are added, as guaranteed by best approximation (each is the best approximation in , and ). Maximum error falls for the triangle and smooth functions but stays near for the square wave: half the jump. Overshoot near the jump stabilizes around % of jump height, regardless of .
Regularity and coefficient decay
The rule just observed has a one-line explanation: differentiating multiplies its coefficients by .
Proof
On each subinterval of the partition, integration by parts gives . Summing over , boundary terms cancel at interior points because is continuous, and at endpoints remains by periodicity. Dividing by gives the formula.
∎Applying this times: if is of class as a periodic function and is piecewise , then , and by Riemann–Lebesgue applied to ,
The smoother is, the faster its coefficients decay. The practical rule, confirmed by the interactive:
| Regularity of (periodic) | Typical decay of | Example |
|---|---|---|
| Jumps | square wave, sawtooth | |
| Continuous, with corners ( jumps) | ||
| , with jumping | ||
| faster than any power | ||
| Analytic in a strip | geometric, for every |
The converse also works and is equally useful: if is continuous and , the derivative series through order converge uniformly by the Weierstrass M-test and, by interchanging limit and derivative, is of class (that the series converges to 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
There are three distinct questions with different answers. Does tend to zero? Always. Does tend to 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 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 are written as a periodic convolution,
and the Fejér kernel has three properties: it is nonnegative, its mean is , and outside any neighborhood it is bounded by . Hence for continuous (thus uniformly continuous and bounded by ), ; piece is small by uniform continuity and piece is bounded by , uniformly in .
Piece 2: continuous functions are dense in under norm . If is Riemann integrable and bounded by , there is a step function with and (a lower Darboux sum close to the integral), and rounding each step into a narrow ramp gives a continuous periodic with and . Since , .
Piece 3: best approximation does the rest. Given , take continuous with and a trigonometric polynomial of degree with , hence . For , , and best approximation gives
Notice the structure: we have not directly proved converges to anything. We found some polynomial near , and projection optimality made at least as close. This is the standard argument for completeness of an orthonormal system.
Pointwise: Dirichlet’s theorem
Substituting the definition of into the partial sum,
where the last equality is a geometric progression sum. The Dirichlet kernel has mean and a peak of height at , but unlike Fejér’s it takes negative values and its norm grows without bound: the Lebesgue constants are , , and for , growing as . That difference explains almost everything.
Proof
Since is even with mean , , and
Handle the first summand (the second is identical). Let on . Near , is bounded because has a right derivative at (a consequence of the mean value theorem and existence of the one-sided limit of ); away from it is integrable. Thus the first summand is , and since , a combination of Fourier coefficients of order of integrable functions and (extended by zero to ). 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 : by the uniform boundedness principle, if linear maps of norm on continuous functions with supremum norm are not uniformly bounded, there is a continuous with . 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 , almost everywhere. And you already know the practical remedy: Fejér means converge uniformly for every continuous because their kernel is positive.
Uniform: continuity and a piecewise derivative suffice
Proof
By the derivative theorem, for . By Cauchy–Schwarz in and Bessel applied to ,
Since , the Weierstrass M-test gives uniform convergence of to a continuous function . Integrating term by term (allowed by uniform convergence), for every . Then is continuous with all coefficients zero, and by convergence in , . A continuous function of zero norm is identically zero, hence .
∎Conversely, if has a jump, uniform convergence is impossible: a uniform limit of continuous functions is continuous, and each is continuous. More concretely, near the jump, cannot fall below half the jump. This is the number you saw stuck near 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- partial sum is
so the first maximum right of the jump is at . With , midpoints of a partition of into pieces of width ,
a Riemann sum for the sine integral. The maximum tends not to , the function value, but to : an overshoot over a jump of height , i.e. % of the jump. The peak moves toward the jump (distance ) and narrows, so its area tends to zero and error in does too, but its height does not change.
This value is not peculiar to the square wave. If is piecewise with a jump of size at , subtract from it for each jump a suitable multiple of a translated sawtooth whose sole jump per period is there: a continuous piecewise- function remains, whose series converges uniformly. All overshoot comes from the jump and equals 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 turns Bessel’s inequality into equality.
Proof
By best approximation, , and the last term tends to zero. The two-function version follows by applying the first to , , and (polarization identity), or directly from 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 preserves inner products like an orthogonal matrix, but between and space of square-summable sequences. The Riesz–Fischer theorem completes the picture: every sequence in consists of Fourier coefficients of some (Lebesgue) function, so the map is an isometric isomorphism.
Parseval has two immediate uses. First, measure error without integrating: . For the square wave, on odd indices, and compare the tail with an integral: . Error in decays as with jumps and, by the same calculation, as with corners; you will measure this in code.
Second, compute sums. The most famous example is the Basel problem, , solved by Euler in 1735 with a bold infinite-product argument. With Parseval it is a calculation: you will do it in exercises using . 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 . To reach the transform, let the period grow. With period , the series uses frequencies (cycles per unit of ) with coefficients . As , frequencies fill the line with spacing , product tends to a function of , and series resembles a Riemann sum. The limit suggests the following formulas.
The integral converges absolutely because , so . Also is continuous and, as with series, tends to zero at infinity (Riemann–Lebesgue lemma). Variable is frequency in cycles per unit of : if is seconds, is hertz.
Conventions: where goes
Different communities put in different places, and confusing them is the most common transform error. The three usual conventions:
| Convention | Transform | Inverse | Plancherel | Used by |
|---|---|---|---|---|
| Ordinary frequency | this lesson, signal processing, discrete numpy.fft | |||
| Angular frequency , asymmetric | physics, PDEs, probability | |||
| Angular frequency, unitary | no constants | quantum mechanics, some analysis texts |
All three are the same operation with rescaled variable: in the second. The characteristic function of a random variable with density , , also uses the opposite sign: . Ours has two advantages: no constants before either integral and Gaussian is its own transform.
Frequently used properties
All follow from substitution or integration by parts. For :
| Operation on | Effect on |
|---|---|
| Translation | modulation |
| Modulation | translation |
| Scaling , | : stretching in compresses in |
| Derivative (with , in ) | |
| (with ) | derivative |
| real | Hermitian symmetry |
| real and even | 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 translates to decay of . The fifth, for , is justified by differentiation under the integral sign (Leibniz’s rule), with integrable bound dominating.
The Gaussian, a fixed point of the transform
Proof
Let be the integral. Differentiating under the integral sign (dominated by ) and using , integration by parts gives
with no boundary terms because . This linear ODE has solution , and by the Gaussian integral. The general version follows from the scaling rule with and .
∎A Gaussian of width transforms into a Gaussian of width proportional to . 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 functions, the Plancherel identity also holds, , Parseval’s continuous analog; the transform thereby extends to an isometry of 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 , is a probability density on and, by Plancherel, is one on . Call their standard deviations and : they measure how much the function spreads in space and frequency.
Proof
Integrating by parts with (the boundary term vanishes by hypothesis),
By Cauchy–Schwarz, . By Plancherel and the derivative rule, . Squaring, . Equality in Cauchy–Schwarz requires with 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 (), and the inequality becomes .
Figure constants can be calculated by hand. For double exponential , and , so the product is times the bound; for the triangle, , and the factor is . 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: averages values of around with weights of reflected and centered at . As a sum of random variables: if and are independent with densities and , density of is (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 by ), associative and bilinear; by Fubini, , so , and the same calculation without absolute values gives : masses multiply. It inherits the better regularity of its factors: if is with bounded, , 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 , . You have already used it without naming it: multiplies coefficients by the indicator of (an abrupt cutoff), and by triangular window (a smooth cutoff). The difference between Gibbs and its absence is the difference between these windows.
Smoothing is low-pass filtering
Convolving with normal density of standard deviation multiplies each frequency by : a factor equal to at (mass is conserved) and falling rapidly from . Thus Gaussian blur erases fine detail and leaves large shapes. It is also the solution of the heat equation : , or in frequency. Each frequency decays exponentially at a rate proportional to , 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 , and where 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 equally spaced points , , and approximate coefficient by the trapezoidal rule, simply the mean for periodic functions:
Vector is the discrete Fourier transform (DFT) of the samples: multiplication by the DFT matrix, whose columns are orthogonal. If is continuous and its series absolutely convergent (allowing sums to be reordered), their exact relationship is simple. Substitute and use that equals if and otherwise,
This is the aliasing formula: on the grid frequencies and are indistinguishable, because for every , and the DFT adds all in the same class. If for , only one term remains and samples determine 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 , the highest representable frequency is .
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 inherits coefficient decay: excellent for smooth functions, mediocre with jumps. Computing DFT from its definition costs , while FFT costs ; 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 and returning color produces blurry images.
Tancik and coauthors (2020) proposed a simple fix: give the network not but Fourier features , with a random-frequency matrix . The induced kernel becomes stationary, with bandwidth controlled by : with small the network remains slow on detail; with suitable it learns high frequencies in few iterations; with excessive 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 at 256 points of 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.
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()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 , all four frequencies drop below 10% error in a few dozen steps and error between points is tiny. With the earlier order returns, though faster; with 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.
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 : the trapezoidal rule ceases to be spectral and becomes order , and only because jump nodes use the midpoint (with a one-sided value such as returned by np.sign(-np.pi), error rises to , order ). With triangle corners it falls to , and with the smooth function it is rounding error because for analytic periodic functions the trapezoidal rule converges geometrically. Slopes are , and ; for the smooth function slope is meaningless: ratio reveals geometric decay. Compare with for and for .
Now reconstruction. Error in is obtained for free by Parseval, summing the coefficient tail, and checked against direct integration. Then measure the Gibbs peak for increasing and compare with , calculated by Simpson’s rule.
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 and , as Parseval predicts. The maximum of sits exactly at and its height goes from with to with and with , close to limit , % 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 , 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.
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 () leaves RMSE and best tested Gaussian (), . 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 (): frequency costs and space . Note the tradeoff: from , increasing 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
| Function | Computes | Detail to know |
|---|---|---|
np.fft.fft(a) | unnormalized; norm="ortho" divides by and norm="forward" by | |
np.fft.ifft(X) | exact inverse of fft | |
np.fft.rfft(a, n) | nonredundant half for real signals | n pads with zeros; irfft(X, n) needs length |
np.fft.fftfreq(M, d) | frequencies of each output, in cycles per unit of d | order ; fftshift centers them |
scipy.signal.fftconvolve | linear convolution by FFT | chooses padding for you |
torch.fft.fft, rfft | same on GPU and differentiable | used in the spectral-bias experiment |
Connection with earlier material: with samples at , np.fft.fft(f(x)) / M approximates in fftfreq order. If the grid starts at , multiply by , the phase of a translation. For the continuous transform with step , at frequencies fftfreq(M, d=h), and the function must be centered with ifftshift so the origin falls at index .
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 instead of . The square wave, with phase correction, gives coefficients close to exact and 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
More than one answer may be correct.
Step 1 of 4. What are coefficients ?
Step 1 of 3. You want to integrate first in . What justifies exchanging integration order?
conv_direct(a, b), full linear convolution (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)Summary
- is the space of functions with and product . The are orthonormal and is the best degree- approximation in .
- Coefficients decay as with jumps, with corners, faster as becomes more differentiable and geometrically if analytic, because differentiation multiplies by .
- Convergence: in always (the system is complete); pointwise to the midpoint for piecewise- functions, but not every continuous one; uniform if is continuous and piecewise . Near a jump, Gibbs leaves overshoot % of jump height that does not disappear.
- Parseval, , measures truncation errors without integration and calculates sums such as or .
- Transform turns translations into phases, scalings into inverse scalings and derivatives into multiplication by . Gaussian is its own fixed point and uniquely attains uncertainty bound .
- : smoothing with a Gaussian attenuates frequency by . On sampling, the DFT sums frequencies coinciding modulo (aliasing), and FFT convolution requires zero-padding.
- Gradient-trained networks learn low frequencies first; input Fourier features change that bias, with controlling bandwidth.