Module contents
Lesson 10 of 26Core 110 min

Function approximation: Chebyshev, minimax and Fourier

Find compact function approximations using orthogonal polynomials, Chebyshev coefficient decay and minimax approximation, as used for functions such as exp and sin. Then study the discrete Fourier transform, the FFT, aliasing and fast convolution.

After this lesson you can

  • Compute Chebyshev coefficients by a DCT on Chebyshev nodes and truncate adaptively.
  • Relate coefficient decay to smoothness and analyticity.
  • Explain the equioscillation characterization of best approximation and how math libraries evaluate exp, log and sin.
  • Implement recursive and iterative radix-2 FFTs and justify O(n log n) complexity.
  • Use the FFT for fast convolution without circular wraparound, and diagnose aliasing and spectral leakage.

Before you start

Motivation: representing a function with few numbers

The previous lesson gave a polynomial passing through data: polynomial interpolation. Here the question changes. You have a function ff evaluable anywhere, perhaps expensive or defined by a program, and seek a compact replacement: few coefficients, controlled error throughout the interval, and fast evaluation. This arises in many places:

  • Expensive functions evaluated millions of times. A density, smooth loss or ODE solution as a function of a parameter is tabulated once as a Chebyshev series, then evaluated with a recurrence of nn steps. Chebfun, Trefethen and collaborators’ system that “computes with functions” like vectors, works this way.
  • Math-library functions. When you write np.exp(x), the library does not sum a Taylor series. It reduces xx to a tiny interval, evaluates a polynomial whose coefficients minimize maximum error, and reconstructs the result by shifting the exponent. Final error is below one ulp and computation takes nanoseconds.
  • Signals and images. Filtering a signal, convolving an image with a large kernel, JPEG compression and estimating a time-series spectrum are changes of basis to sines and cosines. FFT performs this in O(nlog⁡n)\bigO(n\log n) rather than O(n2)\bigO(n^2), making it one of history’s most used algorithms.

The lesson’s halves are the same idea in two bases. On [−1,1][-1, 1] the good basis is Chebyshev polynomials; on a period, complex exponentials. They are connected: Tk(cos⁡θ)=cos⁡kθT_k(\cos\theta) = \cos k\theta, so a Chebyshev series is a cosine series in disguise and its coefficients come from a cosine transform. Along the way see why coefficient decay reveals smoothness, what the best maximum-norm polynomial looks like, and why a filmed wheel seems to rotate backward.

Continuous least squares and orthogonal polynomials

Start with the easiest version of “best approximation”: least squares. Fix weight w(x)>0w(x) > 0 on (a,b)(a, b) and inner product

⟨f,g⟩w=∫abf(x) g(x) w(x) ⁣dx,∥f∥w=⟨f,f⟩w.\inner{f}{g}_w = \int_a^b f(x)\,g(x)\,w(x) \dd x, \qquad \norm{f}_w = \sqrt{\inner{f}{f}_w}.

Seeking p∈Pnp \in \mathcal{P}_n minimizing ∥f−p∥w\norm{f - p}_w means seeking the orthogonal projection of ff onto subspace Pn\mathcal{P}_n: error f−pf - p must be orthogonal to all Pn\mathcal{P}_n. Writing p=∑kckϕkp = \sum_k c_k\phi_k in basis ϕ0,…,ϕn\phi_0, \dots, \phi_n gives normal equations Gc=b\mat{G}\vb{c} = \vb{b} with Gjk=⟨ϕj,ϕk⟩wG_{jk} = \inner{\phi_j}{\phi_k}_w and bj=⟨f,ϕj⟩wb_j = \inner{f}{\phi_j}_w.

The monomial basis ϕk=xk\phi_k = x^k is disastrous. With w=1w = 1 on [0,1][0, 1], Gjk=1/(j+k+1)G_{jk} = 1/(j + k + 1) is the Hilbert matrix, whose condition number grows like e3.5ne^{3.5n}; on [−1,1][-1, 1] the situation is similar. This is the numerical least-squares problem again: columns xkx^k are almost parallel because for large kk they resemble the same curve near zero rising at the edges. The remedy is also the same: orthogonalize.

In an orthogonal basis the normal equations are diagonal and each coefficient is computed separately:

p⋆=∑k=0nck pk,ck=⟨f,pk⟩w⟨pk,pk⟩w.p^\star = \sum_{k=0}^{n} c_k\,p_k, \qquad c_k = \frac{\inner{f}{p_k}_w}{\inner{p_k}{p_k}_w}.

Two practical consequences: increasing degree leaves computed coefficients unchanged and adds one; there is no system to solve or condition number to fear, since each ckc_k is an integral.

The three-term recurrence

Gram–Schmidt on monomials would be unstable and expensive. It is unnecessary: orthogonal polynomials come from a three-term recurrence, thanks to a useful inner-product property.

Proof

Polynomial q=x pk−pk+1q = x\,p_k - p_{k+1} has degree at most kk, because both terms are monic of degree k+1k + 1. Since p0,…,pkp_0, \dots, p_k is an orthogonal basis of Pk\mathcal{P}_k, q=∑j=0kγjpjq = \sum_{j=0}^{k} \gamma_j p_j with γj=⟨q,pj⟩w/⟨pj,pj⟩w\gamma_j = \inner{q}{p_j}_w/\inner{p_j}{p_j}_w. Compute numerators. By orthogonality ⟨pk+1,pj⟩w=0\inner{p_{k+1}}{p_j}_w = 0 for j≤kj \le k, so ⟨q,pj⟩w=⟨x pk,pj⟩w\inner{q}{p_j}_w = \inner{x\,p_k}{p_j}_w. Crucially, multiplication by xx is symmetric in this inner product:

⟨x pk,pj⟩w=∫x pk pj w ⁣dx=⟨pk,x pj⟩w.\inner{x\,p_k}{p_j}_w = \int x\,p_k\,p_j\,w \dd x = \inner{p_k}{x\,p_j}_w.

If j≤k−2j \le k - 2, x pjx\,p_j has degree ≤k−1\le k - 1 and is orthogonal to pkp_k: γj=0\gamma_j = 0. Only j=kj = k, giving γk=αk\gamma_k = \alpha_k, and j=k−1j = k - 1 survive; for the latter x pk−1=pk+(grado≤k−1)x\,p_{k-1} = p_k + (\text{grado} \le k - 1) gives ⟨pk,x pk−1⟩w=⟨pk,pk⟩w\inner{p_k}{x\,p_{k-1}}_w = \inner{p_k}{p_k}_w and γk−1=βk\gamma_{k-1} = \beta_k. Rearranging gives pk+1=x pk−αkpk−βkpk−1p_{k+1} = x\,p_k - \alpha_k p_k - \beta_k p_{k-1}.

∎

Each weight gives a family; these three are most useful (in standard, not monic, normalization):

FamilyInterval and weightRecurrenceUse
Legendre PkP_k[−1,1][-1, 1], w=1w = 1(k+1)Pk+1=(2k+1)xPk−kPk−1(k + 1)P_{k+1} = (2k + 1)xP_k - kP_{k-1}unweighted least squares, Gaussian quadrature
Chebyshev TkT_k[−1,1][-1, 1], w=(1−x2)−1/2w = (1 - x^2)^{-1/2}Tk+1=2xTk−Tk−1T_{k+1} = 2xT_k - T_{k-1}near-optimal maximum-norm approximation
Hermite HekHe_kR\R, w=e−x2/2w = e^{-x^2/2}Hek+1=x Hek−k Hek−1He_{k+1} = x\,He_k - k\,He_{k-1}expectations under a normal distribution

Hermite polynomials turn E[g(X)]\E[g(X)] with X∼N(0,1)X \sim \Normal(0, 1) into a short sum, next lesson’s Gauss–Hermite quadrature. Coefficients αk,βk\alpha_k, \beta_k form the tridiagonal Jacobi matrix whose eigenvalues are Gaussian quadrature nodes.

[ ]Monomials versus LegendreBrowser
import numpy as np
from numpy.polynomial import legendre as L

f = np.exp
xq, wq = L.leggauss(60)            # cuadratura de Gauss-Legendre: exacta hasta grado 119
xx = np.linspace(-1, 1, 2001)

def mc_monomios(n):
    """Ecuaciones normales con la base x^k: G_jk = ∫ x^(j+k) dx en [-1, 1]."""
    k = np.arange(n + 1)
    s = k[:, None] + k[None, :]
    G = np.where(s % 2 == 0, 2.0 / (s + 1), 0.0)
    b = np.array([np.sum(wq * f(xq) * xq**j) for j in k])
    c = np.linalg.solve(G, b)
    return np.polyval(c[::-1], xx), np.linalg.cond(G)

def mc_legendre(n):
    """Base ortogonal: c_k = <f, P_k> / <P_k, P_k>, con <P_k, P_k> = 2/(2k+1)."""
    c = np.array([(2 * k + 1) / 2 * np.sum(wq * f(xq) * L.legval(xq, np.eye(n + 1)[k]))
                  for k in range(n + 1)])
    return L.legval(xx, c)

print(" n   cond(G) monomios   error monomios   error Legendre")
for n in [4, 8, 12, 16, 20]:
    pm, kappa = mc_monomios(n)
    pl = mc_legendre(n)
    print(f"{n:2d}   {kappa:16.2e}   {np.max(np.abs(f(xx) - pm)):14.2e}   {np.max(np.abs(f(xx) - pl)):14.2e}")

In exact arithmetic both methods compute the same polynomial. Not in floating point. They agree through degree 8; beyond that the monomial Gram matrix’s condition number, multiplying about 5.6 per degree, reaches 3×10143\times 10^{14} with n=20n = 20, and error rises from 1.7×10−121.7\times 10^{-12} (degree 12) to 7.8×10−107.8\times 10^{-10} (degree 20): adding degrees worsens approximation. Legendre stays between 0.90.9 and 2.4×10−122.4\times 10^{-12}: this floor comes not from the basis but rounding in floating-point quadrature computing each coefficient, growing slowly as each degree adds a small coefficient error. The next cell builds families from scratch with the recurrence and discrete inner products (Stieltjes procedure), recovering known βk\beta_k: k2/(4k2−1)k^2/(4k^2 - 1) for Legendre, 1/21/2 then 1/41/4 for monic Chebyshev, and kk for Hermite.

[ ]The recurrence from scratch (Stieltjes)Browser
import numpy as np
from numpy.polynomial import legendre, hermite_e

def stieltjes(x, w, n):
    """alpha_k y beta_k de los polinomios mónicos ortogonales para <f, g> = sum_j w_j f(x_j) g(x_j)."""
    p_ant, p = np.zeros_like(x), np.ones_like(x)
    alfa, beta, norma_ant = [], [], None
    for k in range(n):
        norma = np.sum(w * p * p)
        a = np.sum(w * x * p * p) / norma
        b = norma / norma_ant if k > 0 else 0.0
        alfa.append(a)
        beta.append(b)
        p_ant, p = p, (x - a) * p - b * p_ant       # la recurrencia de tres términos
        norma_ant = norma
    return np.array(alfa), np.array(beta)

N = 80
xl, wl = legendre.leggauss(N)
xc = np.cos(np.pi * (np.arange(N) + 0.5) / N); wc = np.full(N, np.pi / N)   # Gauss-Chebyshev
xh, wh = hermite_e.hermegauss(N)
k = np.arange(1, 8)
for nombre, (x, w), teoria in [("Legendre", (xl, wl), k**2 / (4 * k**2 - 1)),
                               ("Chebyshev", (xc, wc), np.where(k == 1, 0.5, 0.25)),
                               ("Hermite", (xh, wh), k.astype(float))]:
    a, b = stieltjes(x, w, 8)
    print(f"{nombre:9s} max|alfa| = {np.max(np.abs(a)):.0e}   beta_1..7 = {np.round(b[1:], 6)}")
    print(f"{'':9s} teoría                 = {np.round(teoria, 6)}")

All αk\alpha_k are zero (the three weights are symmetric), and βk\beta_k match closed formulas through the sixth displayed digit. This procedure works for any integrable weight, including an empirical one.

Chebyshev series

Among these families Chebyshev dominates numerical approximation, for a one-line reason. With x=cos⁡θx = \cos\theta,

Tk(cos⁡θ)=cos⁡(kθ).T_k(\cos\theta) = \cos(k\theta).

Induction using cos⁡((k+1)θ)+cos⁡((k−1)θ)=2cos⁡θcos⁡(kθ)\cos((k + 1)\theta) + \cos((k - 1)\theta) = 2\cos\theta\cos(k\theta) verifies this, exactly recurrence Tk+1=2xTk−Tk−1T_{k+1} = 2xT_k - T_{k-1}. Thus TkT_k oscillates between −1-1 and 11 with k+1k + 1 extrema at xj=cos⁡(jπ/k)x_j = \cos(j\pi/k), and substitution x=cos⁡θx = \cos\theta makes everything on [−1,1][-1, 1] periodic on θ\theta. Weight (1−x2)−1/2(1 - x^2)^{-1/2} is not arbitrary: it makes  ⁣dx/1−x2=− ⁣dθ\dd x/\sqrt{1 - x^2} = -\dd\theta, turning orthogonality of TkT_k into cosine orthogonality:

∫−11Tj(x)Tk(x)1−x2 ⁣dx=∫0πcos⁡(jθ)cos⁡(kθ) ⁣dθ={0j≠k,π/2j=k≥1,πj=k=0.\int_{-1}^1 \frac{T_j(x)T_k(x)}{\sqrt{1 - x^2}}\dd x = \int_0^\pi \cos(j\theta)\cos(k\theta)\dd\theta = \begin{cases} 0 & j \neq k, \\ \pi/2 & j = k \ge 1, \\ \pi & j = k = 0. \end{cases}

With g(θ)=f(cos⁡θ)g(\theta) = f(\cos\theta), formula aka_k says the Chebyshev series of ff is the Fourier cosine series of gg, which is even and 2π2\pi-periodic. Everything about Fourier series carries over.

Computation by a cosine transform

The aka_k integrals do not use generic quadrature. Take NN Chebyshev points of the first kind, xj=cos⁡θjx_j = \cos\theta_j with θj=π(j+12)/N\theta_j = \pi(j + \tfrac12)/N, j=0,…,N−1j = 0, \dots, N - 1 (zeros of TNT_N, the previous lesson’s Chebyshev nodes). Cosines are discretely orthogonal there too: ∑jcos⁡(kθj)cos⁡(lθj)=N2δkl\sum_j \cos(k\theta_j)\cos(l\theta_j) = \tfrac{N}{2}\delta_{kl} for 0≤k,l<N0 \le k, l < N not both zero. Thus the polynomial interpolating ff at these points, p=∑k<NckTkp = \sum_{k<N} c_kT_k, has coefficients

ck=2N∑j=0N−1f(xj)cos⁡(kθj),c0 a la mitad.c_k = \frac{2}{N}\sum_{j=0}^{N-1} f(x_j)\cos(k\theta_j), \qquad c_0 \text{ a la mitad}.

This sum is a type-II discrete cosine transform, studied below and computed by FFT in O(Nlog⁡N)\bigO(N\log N). ckc_k are not exactly aka_k: cosines of frequencies kk, 2N−k2N - k, 2N+k2N + k, … agree on θj\theta_j up to sign, so interpolation adds them. Substitute the series to verify:

ck=ak+∑m≥1(−1)m(a2mN−k+a2mN+k).c_k = a_k + \sum_{m \ge 1} (-1)^m\big(a_{2mN - k} + a_{2mN + k}\big).

This is coefficient aliasing, the same phenomenon seen in signals. If aka_k have fallen below ε\eps before k=Nk = N, both sets agree to machine precision and are indistinguishable in practice.

Decay reveals smoothness

These series are useful because the decay rate of ∣ak∣\abs{a_k} is precisely related to regularity of ff, in two distinct regimes.

The proof integrates by parts ν+1\nu + 1 times in ∫0πg(θ)cos⁡(kθ) ⁣dθ\int_0^\pi g(\theta)\cos(k\theta)\dd\theta: each integration contributes factor 1/k1/k. Thus ∣x∣\abs{x} (ν=1\nu = 1, f′=sign⁡f' = \operatorname{sign} has variation 2) has ak=O(k−2)a_k = \bigO(k^{-2}); indeed a2j=(−1)j+1 4/(π(4j2−1))a_{2j} = (-1)^{j+1}\,4/(\pi(4j^2 - 1)). ∣x∣3\abs{x}^3 has O(k−4)\bigO(k^{-4}) and a jump, O(k−1)\bigO(k^{-1}).

For analytic functions decay is geometric, with rate set by a geometric object. The Bernstein ellipse EρE_\rho, ρ>1\rho > 1, is the complex region enclosed by the image of circle ∣z∣=ρ\abs{z} = \rho under Joukowski transform x=(z+z−1)/2x = (z + z^{-1})/2: an ellipse with foci ±1\pm 1 and semiaxes (ρ+ρ−1)/2(\rho + \rho^{-1})/2 and (ρ−ρ−1)/2(\rho - \rho^{-1})/2 summing to ρ\rho.

Proof

Define F(z)=f((z+z−1)/2)F(z) = f\big((z + z^{-1})/2\big). Joukowski’s map takes annulus ρ−1<∣z∣<ρ\rho^{-1} < \abs{z} < \rho inside EρE_\rho (each interior point except [−1,1][-1, 1] has two preimages zz and 1/z1/z), so FF is analytic in the annulus with ∣F∣≤M\abs{F} \le M. On the unit circle z=eiθz = e^{i\theta} and F(eiθ)=f(cos⁡θ)=∑kakcos⁡(kθ)=a0+∑k≥1ak2(zk+z−k)F(e^{i\theta}) = f(\cos\theta) = \sum_k a_k\cos(k\theta) = a_0 + \sum_{k\ge1} \tfrac{a_k}{2}(z^k + z^{-k}). This is the Laurent series of FF, whose coefficients can be computed on any circle ∣z∣=s\abs{z} = s in the annulus:

ak2=12πi∮∣z∣=sF(z)zk+1 ⁣dz⟹∣ak∣2≤M 2πs2πsk+1=Ms−k.\frac{a_k}{2} = \frac{1}{2\pi i}\oint_{\abs{z} = s} \frac{F(z)}{z^{k+1}}\dd z \quad\Longrightarrow\quad \frac{\abs{a_k}}{2} \le \frac{M\,2\pi s}{2\pi s^{k+1}} = M s^{-k}.

Taking s→ρs \to \rho gives ∣ak∣≤2Mρ−k\abs{a_k} \le 2M\rho^{-k}. The error bound is the geometric tail sum ∑k>n2Mρ−k=2Mρ−n/(ρ−1)\sum_{k > n} 2M\rho^{-k} = 2M\rho^{-n}/(\rho - 1), because ∣Tk∣≤1\abs{T_k} \le 1 on [−1,1][-1, 1].

∎

The nearest singularity sets ρ\rho. A function with poles at ±iδ\pm i\delta, such as 1/(1+(x/δ)2)1/(1 + (x/\delta)^2), is analytic in any ellipse excluding them; the largest passes through them, with minor semiaxis (ρ−ρ−1)/2=δ(\rho - \rho^{-1})/2 = \delta, giving ρ=δ+1+δ2\rho = \delta + \sqrt{1 + \delta^2}. Runge’s function δ=0.2\delta = 0.2 has ρ≈1.22\rho \approx 1.22: coefficient envelope falls 18 % per degree (odd coefficients vanish since the function is even), requiring about 170 to reach 10−1510^{-15}. An entire function such as exe^x is analytic in every ellipse and coefficients decay faster than any ρ−k\rho^{-k}.

InteractiveCoefficient decay reveals smoothness
f(x)=11+(x/δ)2f(x) = \dfrac{1}{1 + (x/\delta)^2} and its truncation fnf_n
Complex plane: [−1,1][-1, 1], singularities and EρE_\rho
1−1iδ
log⁡10∣ak∣\log_{10}\abs{a_k} versus kk (exact zeros fall to the noise floor)
machine ε
  • ff
  • fnf_n (truncated at degree nn)
  • ∣ak∣\abs{a_k} (discarded in grey)
  • theoretical slope ρ−k\rho^{-k}
0.30
10
Ellipse ρ\rho1.344
∥f−fn∥∞\norm{f - f_n}_\infty3.7e−2
∑k>n∣ak∣\sum_{k > n}\abs{a_k} (bound)3.7e−2
Adaptive degree (1e−14)110
Analytic in EρE_\rho with ρ=δ+1+δ2=1.344\rho = \delta + \sqrt{1 + \delta^2} = 1.344: the coefficient envelope is divided by 1.34 per degree (odd coefficients vanish because ff is even), until rounding floor.
Above, the function and truncation fnf_n; right, the complex plane with [−1,1][-1, 1], singularities and the largest Bernstein ellipse in which ff is analytic. Below, log⁡10∣ak∣\log_{10}\abs{a_k} from a 512-point DCT, with theorem-predicted slope dashed. With poles, reduce δ\delta toward 0.15: the ellipse flattens against the interval, the line becomes shallower and required degree soars. Try ∣x∣3\abs{x}^3, ∣x∣\abs{x} and the jump: no log-scale straight line remains, only slow decay that never reaches the floor. Move nn and compare ∥f−fn∥∞\norm{f - f_n}_\infty with the sum of discarded coefficients.

Notice the floor: below 10−1610^{-16} coefficients stop falling and form a rounding-noise plateau, because values f(xj)f(x_j) are known only to relative precision ε\eps. Chebfun uses this plateau to choose degree.

[ ]Chebyshev coefficients by DCTBrowser
import numpy as np
from scipy.fft import dct
from scipy.special import iv

def cheb_coeffs(f, N):
    """Coeficientes del interpolante de f en N puntos de Chebyshev de primera especie (una DCT-II)."""
    theta = np.pi * (np.arange(N) + 0.5) / N
    c = dct(f(np.cos(theta)), type=2) / N
    c[0] /= 2
    return c

# e^x: los coeficientes exactos son a_0 = I_0(1) y a_k = 2 I_k(1) (Bessel modificada)
c = cheb_coeffs(np.exp, 32)
exacto = np.r_[iv(0, 1), 2 * iv(np.arange(1, 64), 1)]
print("e^x, error en los 15 primeros coeficientes:", np.max(np.abs(c[:15] - exacto[:15])))

# aliasing con N = 8: c_3 = a_3 - (a_13 + a_19) + (a_29 + a_35) - ...
c8 = cheb_coeffs(np.exp, 8)
print(f"N = 8:  c_3 = {c8[3]:.15f}   a_3 = {exacto[3]:.15f}   a_3 - a_13 - a_19 = {exacto[3] - exacto[13] - exacto[19]:.15f}")

# decaimiento geométrico: polos en ±iδ, ρ = δ + sqrt(1 + δ²)
for delta in [0.2, 0.5, 1.0]:
    a = cheb_coeffs(lambda x: 1 / (1 + (x / delta)**2), 512)
    k = np.arange(4, 512, 2)
    k = k[np.abs(a[k]) > 1e-13]
    pendiente = np.polyfit(k, np.log(np.abs(a[k])), 1)[0]
    print(f"δ = {delta}: ρ teórico = {delta + np.sqrt(1 + delta**2):.4f}   ρ medido = {np.exp(-pendiente):.4f}   "
          f"último |a_k| > 1e-15 en k = {np.flatnonzero(np.abs(a) > 1e-15).max()}")

# decaimiento algebraico: pendiente de log|a_k| frente a log k
for nombre, f, nu in [("|x|", np.abs, 1), ("|x|^3", lambda x: np.abs(x)**3, 3), ("sign", np.sign, 0)]:
    a = cheb_coeffs(f, 4096)
    k = np.arange(20, 401)
    k = k[np.abs(a[k]) > 1e-13]
    p = np.polyfit(np.log(k), np.log(np.abs(a[k])), 1)[0]
    print(f"{nombre:6s} pendiente = {p:.3f}   (teoría: -{nu + 1})")

Output confirms both laws. For poles, ρ\rho measured on the coefficient line matches δ+1+δ2\delta + \sqrt{1 + \delta^2} to four digits, and the last coefficient above 10−1510^{-15} occurs at k=168k = 168, 7070 and 3838 for δ=0.2\delta = 0.2, 0.50.5 and 11. For singular functions log-log slopes are near −2-2, −4-4 and −1-1. The aliasing line shows that with only 8 points coefficient c3c_3 is no longer a3a_3, but equals a3−a13−a19a_3 - a_{13} - a_{19} to the last digit.

Taylor versus Chebyshev

Why not use a Taylor polynomial, another power series with known coefficients? Taylor concentrates accuracy at one point. Its error on xx is f(n+1)(ξ)xn+1/(n+1)!f^{(n+1)}(\xi)x^{n+1}/(n + 1)!, tiny near 0 and maximal at endpoints. Chebyshev truncation spreads error across the interval, almost like an+1Tn+1(x)a_{n+1}T_{n+1}(x), which oscillates at constant amplitude.

[ ]Taylor versus Chebyshev for e^xBrowser
import math
import numpy as np
from numpy.polynomial import chebyshev as C

xx = np.linspace(-1, 1, 20001)
a = cheb_coeffs(np.exp, 64)
for n in [3, 10]:
    taylor = sum(xx**k / math.factorial(k) for k in range(n + 1))
    e_tay = np.max(np.abs(np.exp(xx) - taylor))
    e_che = np.max(np.abs(np.exp(xx) - C.chebval(xx, a[:n + 1])))
    print(f"grado {n:2d}:  Taylor {e_tay:.3e}   Chebyshev truncada {e_che:.3e}   cociente {e_tay / e_che:,.0f}   a_(n+1) = {a[n + 1]:.3e}")

At degree 10 Taylor’s error is 2.73×10−82.73\times 10^{-8} (at x=1x = 1) and Chebyshev truncation’s 2.61×10−112.61\times 10^{-11}, about a thousand times less with the same coefficient count. Truncation error is almost exactly a11=2.50×10−11a_{11} = 2.50\times 10^{-11} as predicted. Quantitatively, both errors are the size of the first discarded term, but in the Taylor basis it is x11/11!x^{11}/11!, equal to 1/11!1/11! at x=1x = 1, while in Chebyshev it is a11T11a_{11}T_{11}, and a11≈2−10/11!a_{11} \approx 2^{-10}/11! because x11=2−10T11+…x^{11} = 2^{-10}T_{11} + \dots (the leading coefficient of T11T_{11} is 2102^{10}).

Best approximation: minimax and equioscillation

Least squares minimizes average error. Often the worst case matters: a math library guarantees error for all xx. The question becomes

En(f)=min⁡p∈Pn ∥f−p∥∞,∥g∥∞=max⁡x∈[−1,1]∣g(x)∣.E_n(f) = \min_{p \in \mathcal{P}_n}\ \norm{f - p}_\infty, \qquad \norm{g}_\infty = \max_{x \in [-1, 1]} \abs{g(x)}.

The minimum exists (in finite-dimensional Pn\mathcal{P}_n it suffices to minimize on a compact set), and the polynomial attaining it is the best approximation, or minimax polynomial. Find it before seeing the theorem.

InteractiveHunting for equioscillation
Error e(x)=ex−p(x)e(x) = e^x - p(x) on [−1,1][-1, 1], with band ±max⁡∣e∣\pm\max\abs{e}
  • error e(x)e(x)
  • band ±max⁡∣e∣\pm\max\abs{e}
  • optimal level ±E∗\pm E^*
  • positive extremum (filled if touching band)
  • negative extremum
p=c0T0+c1T1+c2T2+c3T3p = c_0T_0 + c_1T_1 + c_2T_2 + c_3T_3
1.2500
1.1250
0.2500
0.0417
max⁡∣ex−p(x)∣\max\abs{e^x - p(x)}5.162e−2
Ratio to optimum E∗E^*9.336
Alternating extrema on the band1
Remez steps0
The error is unbalanced: one extremum dominates and the others are far from the band. The maximum can be lowered.
Polynomial p=c0T0+c1T1+c2T2+c3T3p = c_0T_0 + c_1T_1 + c_2T_2 + c_3T_3 approximates exe^x on [−1,1][-1, 1]; the curve is error ex−p(x)e^x - p(x) and the shaded band ±max⁡∣e∣\pm\max\abs{e}. Start with Taylor: error is huge at x=1x = 1 and tiny elsewhere. Adjust coefficients to lower the maximum: whenever one extremum falls another rises. When you can improve no further, count points touching the band and inspect their signs. Then select Remez step and compare with the polynomial found in two or three steps. Gray lines mark optimal level ±E∗\pm E^*.

What you just saw is approximation theory’s central theorem, proved by Chebyshev in the nineteenth century.

Proof

We prove equioscillation suffices, the direction used by the algorithm. Suppose p⋆p^\star equioscillates at x0<⋯<xn+1x_0 < \dots < x_{n+1} and q∈Pnq \in \mathcal{P}_n exists with ∥f−q∥∞<∥f−p⋆∥∞=:E\norm{f - q}_\infty < \norm{f - p^\star}_\infty =: E. Then r=q−p⋆=(f−p⋆)−(f−q)r = q - p^\star = (f - p^\star) - (f - q) satisfies, at each xix_i,

sign⁡r(xi)=sign⁡(σ(−1)iE−(f−q)(xi))=σ(−1)i,\operatorname{sign} r(x_i) = \operatorname{sign}\big(\sigma(-1)^iE - (f - q)(x_i)\big) = \sigma(-1)^i,

because ∣(f−q)(xi)∣<E\abs{(f - q)(x_i)} < E. Polynomial rr changes sign between consecutive points: n+1n + 1 changes, hence n+1n + 1 roots. But deg⁡r≤n\deg r \le n, so r=0r = 0 and q=p⋆q = p^\star, contradicting ∥f−q∥∞<E\norm{f - q}_\infty < E. Necessity follows conversely: if error alternates at fewer than n+2n + 2 extrema, construct a polynomial with the appropriate sign on each segment which, added with a small factor, lowers the maximum. Uniqueness follows because the mean of two best approximations is also best and must equioscillate at the same points as both (Trefethen, ATAP, chapter 10).

∎

This result characterizes minimax approximation and equioscillation. A familiar example: the best degree-nn polynomial for xn+1x^{n+1} is xn+1−2−nTn+1(x)x^{n+1} - 2^{-n}T_{n+1}(x), because error 2−nTn+12^{-n}T_{n+1} equioscillates at the n+2n + 2 extrema of Tn+1T_{n+1}. The same property makes Chebyshev nodes optimal for the nodal polynomial.

The Remez algorithm

The proof suggests an algorithm published by Evgeny Remez in 1934. It maintains a reference of n+2n + 2 points and repeats two steps:

  1. Level. Solve the linear system of n+2n + 2 equations p(xi)+(−1)ih=f(xi)p(x_i) + (-1)^ih = f(x_i) in n+2n + 2 unknowns c0,…,cn,hc_0, \dots, c_n, h. The polynomial has exactly alternating error ±h\pm h on the reference.
  2. Exchange. Find local extrema of error f−pf - p throughout the interval, one per constant-sign segment, and use them as the new reference.

There is a free certificate. If error of pp alternates sign at n+2n + 2 points, no degree-nn polynomial can have error smaller than the smallest of those ∣e(xi)∣\abs{e(x_i)} (the proof’s argument with ≤\le instead of ==, the de la Vallée Poussin theorem). In particular,

∣h∣≤En(f)≤∥f−p∥∞,\abs{h} \le E_n(f) \le \norm{f - p}_\infty,

and when both bounds agree, you are done.

[ ]Remez from scratch for e^xBrowser
import numpy as np
from numpy.polynomial import chebyshev as C

def remez(f, n, iters=10, m=4001, verbose=True):
    xx = np.linspace(-1, 1, m)
    fx = f(xx)
    ref = -np.cos(np.pi * np.arange(n + 2) / (n + 1))      # referencia inicial: extremos de T_{n+1}
    signos = (-1.0) ** np.arange(n + 2)
    for it in range(iters):
        A = np.column_stack([C.chebvander(ref, n), signos])
        sol = np.linalg.solve(A, f(ref))                      # nivelar: p(x_i) + (-1)^i h = f(x_i)
        c, h = sol[:-1], sol[-1]
        e = fx - C.chebval(xx, c)
        cortes = np.flatnonzero(np.diff(np.sign(e))) + 1      # intercambiar: un extremo por tramo de signo
        ext = np.array([t[np.argmax(np.abs(e[t]))] for t in np.split(np.arange(m), cortes)])
        emax = np.max(np.abs(e))
        if verbose:
            print(f"iteración {it}: |h| = {abs(h):.10e}   max|e| = {emax:.10e}   tramos = {len(ext)}")
        if len(ext) != n + 2 or emax - abs(h) < 1e-15:
            break
        ref = xx[ext]
    return c, emax, xx[ext]

c_mm, E3, puntos = remez(np.exp, 3)
print("\nE_3(exp) =", E3, "  puntos de equioscilación:", np.round(puntos, 4))

xx = np.linspace(-1, 1, 20001)
a = cheb_coeffs(np.exp, 64)
e_tru = np.max(np.abs(np.exp(xx) - C.chebval(xx, a[:4])))
e_int = np.max(np.abs(np.exp(xx) - C.chebval(xx, C.chebinterpolate(np.exp, 3))))
e_tay = np.max(np.abs(np.exp(xx) - (1 + xx + xx**2 / 2 + xx**3 / 6)))
print(f"truncada de Chebyshev: {e_tru:.4e} ({e_tru / E3:.3f} E_3)   interpolante: {e_int:.4e} ({e_int / E3:.3f} E_3)   Taylor: {e_tay:.4e} ({e_tay / E3:.1f} E_3)")

# constantes de Lebesgue de la truncada: L_n = (1/π) ∫_0^π |sin((n+1/2)t) / sin(t/2)| dt
t = np.linspace(1e-9, np.pi, 200001)
for n in [3, 10, 100, 1000]:
    Ln = np.trapezoid(np.abs(np.sin((n + 0.5) * t) / np.sin(t / 2)), t) / np.pi
    print(f"n = {n:4d}:  L_n = {Ln:.3f}   (4/π²) ln n = {4 / np.pi**2 * np.log(n):.3f}")

Remez converges in two iterations to grid precision. First ∣h∣\abs{h} moves from 5.4742×10−35.4742\times 10^{-3} to 5.52834×10−35.52834\times 10^{-3} and maximum error exceeds it by only 6×10−86\times 10^{-8}; second, both bounds agree to all printed digits: E3(ex)=5.52837×10−3E_3(e^x) = 5.52837\times 10^{-3}, with n+2=5n + 2 = 5 equioscillation points at −1-1, −0.682-0.682, 0.04950.0495, 0.73150.7315 and 11. The distance between ∣h∣\abs{h} and max⁡∣e∣\max\abs{e} falls from 10−410^{-4} to 10−810^{-8} then zero: Remez’s quadratic convergence for smooth functions makes it practical.

Chebyshev truncation is nearly as good

The table’s most useful result is not the optimum but how close Chebyshev truncation comes: 1.097 E31.097\,E_3 without solving anything, versus Taylor’s 9.3 E39.3\,E_3. This is no accident. Let PP be a linear operator reproducing Pn\mathcal{P}_n (Pp=pPp = p), such as truncation or interpolation. For any p∈Pnp \in \mathcal{P}_n, f−Pf=(f−p)−P(f−p)f - Pf = (f - p) - P(f - p), so

∥f−Pf∥∞≤(1+∥P∥) ∥f−p∥∞⟹∥f−Pf∥∞≤(1+Λn) En(f),\norm{f - Pf}_\infty \le (1 + \norm{P})\,\norm{f - p}_\infty \quad\Longrightarrow\quad \norm{f - Pf}_\infty \le (1 + \Lambda_n)\,E_n(f),

taking p=p⋆p = p^\star, with Λn=∥P∥\Lambda_n = \norm{P} the operator’s Lebesgue constant. For truncation, since it is the Fourier partial sum of f(cos⁡θ)f(\cos\theta), Λn\Lambda_n is the Fourier-series Lebesgue constant, growing like (4/π2)ln⁡n(4/\pi^2)\ln n. The cell computes it: 1.781.78 for n=3n = 3, 2.222.22 for n=10n = 10, 3.143.14 for n=100n = 100 and 4.074.07 for n=1000n = 1000, always about 1.31.3 above (4/π2)ln⁡n(4/\pi^2)\ln n. Even at degree 1000 truncation loses at most factor 5.15.1 versus optimal, under one decimal digit. For Chebyshev-point interpolation the constant is smaller still, order (2/π)ln⁡n(2/\pi)\ln n (previous lesson). Trefethen summarizes in ATAP chapter 16: in practice exact best approximation is rarely worthwhile unless used billions of times, exactly the math-library case.

How exp, log and sin are computed

Library elementary-function evaluation follows three steps: range reduction, approximation on a small interval, and reconstruction. See exp in FreeBSD’s library, descended from Sun’s fdlibm (file lib/msun/src/e_exp.c):

  1. Reduction. Write x=kln⁡2+rx = k\ln 2 + r with k=round⁡(x/ln⁡2)k = \operatorname{round}(x/\ln 2) and ∣r∣≤12ln⁡2≈0.3466\abs{r} \le \tfrac12\ln 2 \approx 0.3466. Then ex=2kere^x = 2^k e^r. Subtraction x−kln⁡2x - k\ln 2 is delicate: rounding ln⁡2\ln 2 to float64 multiplies error by kk (up to 1024). Cody and Waite’s trick splits ln⁡2\ln 2 into ln2HI =0.693147180369123816490= 0.693147180369123816490, whose last bits are zero so k⋅k\cdotln2HI is exact, and correction ln2LO =1.90821492927058770002×10−10= 1.90821492927058770002\times 10^{-10}, computing r=(x−k ln2HI)−k ln2LOr = (x - k\,\mathrm{ln2HI}) - k\,\mathrm{ln2LO}.
  2. Approximation. On [−0.3466,0.3466][-0.3466, 0.3466] fdlibm approximates auxiliary function R(r2)=r(er+1)/(er−1)=2+r2/6−r4/360+…R(r^2) = r(e^r + 1)/(e^r - 1) = 2 + r^2/6 - r^4/360 + \dots with a degree-5 polynomial in r2r^2 obtained by “a special Remez algorithm”; its code comment bounds error by 2−592^{-59}. It recovers ere^r by division.
  3. Reconstruction. Multiply by 2k2^k by adding kk to the result’s exponent, an exact operation. The code comment guarantees final error always below 1 ulp.

log and sin follow the same scheme with different reductions. For log⁡x\log x, split x=2emx = 2^e m with m∈[2/2,2)m \in [\sqrt2/2, \sqrt2), so log⁡x=eln⁡2+log⁡m\log x = e\ln 2 + \log m, and approximate log⁡m\log m near 1 (fdlibm uses variable s=(m−1)/(m+1)s = (m - 1)/(m + 1), in which log⁡m=2atanh⁡(s)\log m = 2\operatorname{atanh}(s) is odd and well approximated on s2s^2). For sin⁡x\sin x reduce modulo π/2\pi/2, x=kπ/2+rx = k\pi/2 + r with ∣r∣≤π/4\abs{r} \le \pi/4, and depending on k mod 4k \bmod 4 evaluate ±sin⁡r\pm\sin r or ±cos⁡r\pm\cos r. For enormous xx (1030010^{300}, for example), reduction needs hundreds of bits of 2/π2/\pi: the Payne–Hanek algorithm.

Modern libraries add a table. Arm’s exp implementation (optimized-routines, math/exp.c) reduces using x=kln⁡2/N+rx = k\ln 2/N + r, stores 2j/N2^{j/N} for j=0,…,N−1j = 0, \dots, N - 1 in a table and leaves ∣r∣≤ln⁡2/(2N)\abs{r} \le \ln 2/(2N), an interval small enough for a degree-4 or degree-5 polynomial. Its comment bounds error by 0.5+1.11/N0.5 + 1.11/N ulp plus polynomial contribution. Half an ulp is unavoidable: rounding the result itself. Improving on this, always returning the nearest float to the exact value (correct rounding), meets the table-maker’s dilemma: for some xx the exact value is so close to a midpoint that many bits are needed to decide rounding direction. IEEE 754-2008 only recommends correct rounding for these functions; CRlibm and CORE-MATH achieve it with a rarely triggered extended-precision second phase (Muller, Elementary Functions, chapter 12).

Lab: mini Chebfun and your own exp

Chebfun in forty lines

You can now build Chebfun’s central piece: sample more and more points until the plateau appears, truncate the series and operate on coefficients. Differentiation uses recurrence dk−1=dk+1+2k ckd_{k-1} = d_{k+1} + 2k\,c_k (downward from k=nk = n, with dn=dn+1=0d_n = d_{n+1} = 0 and d0d_0 halved at the end), derived from 2Tk=Tk+1′/(k+1)−Tk−1′/(k−1)2T_k = T'_{k+1}/(k + 1) - T'_{k-1}/(k - 1). Integration gives ∫−11Tk ⁣dx=2/(1−k2)\int_{-1}^1 T_k \dd x = 2/(1 - k^2) if kk is even, 0 if odd.

[ ]Mini ChebfunBrowser
import numpy as np

class MiniChebfun:
    """Una función en [-1, 1] representada por su serie de Chebyshev, con el grado elegido solo."""

    def __init__(self, f=None, coef=None, tol=1e-14, nmax=2**14):
        if coef is None:
            N = 16
            while True:
                c = cheb_coeffs(f, N)
                escala = np.max(np.abs(c))
                if np.max(np.abs(c[-N // 8:])) < tol * escala:     # el último octavo ya es meseta
                    break
                if N >= nmax:
                    raise RuntimeError(f"sin meseta con {N} puntos: ¿f es suave?")
                N *= 2
            coef = c[: np.flatnonzero(np.abs(c) > tol * escala).max() + 1]
        self.c = np.asarray(coef, dtype=float)

    def __len__(self):
        return len(self.c)

    def __call__(self, x):                       # Clenshaw
        x = np.asarray(x, dtype=float)
        b1 = np.zeros_like(x); b2 = np.zeros_like(x)
        for ck in self.c[:0:-1]:
            b1, b2 = 2 * x * b1 - b2 + ck, b1
        return x * b1 - b2 + self.c[0]

    def deriv(self):
        n = len(self.c) - 1
        d = np.zeros(n + 2)
        for k in range(n, 0, -1):
            d[k - 1] = d[k + 1] + 2 * k * self.c[k]
        d[0] /= 2
        return MiniChebfun(coef=d[: max(n, 1)])

    def sum(self):
        k = np.arange(0, len(self.c), 2)
        return np.sum(self.c[k] * 2 / (1 - k**2))

xx = np.linspace(-1, 1, 5001)
f = lambda x: np.exp(x) * np.sin(5 * x)
F = MiniChebfun(f)
dF = F.deriv()
exacta = lambda x: np.exp(x) * (np.sin(5 * x) + 5 * np.cos(5 * x))
integral = (np.exp(1) * (np.sin(5) - 5 * np.cos(5)) - np.exp(-1) * (np.sin(-5) - 5 * np.cos(-5))) / 26
print(f"e^x sin 5x: grado {len(F) - 1}   error {np.max(np.abs(F(xx) - f(xx))):.1e}   "
      f"error de la derivada {np.max(np.abs(dF(xx) - exacta(xx))):.1e}   error de la integral {abs(F.sum() - integral):.1e}")

for delta in [1.0, 0.5, 0.2, 0.05]:
    R = MiniChebfun(lambda x: 1 / (1 + (x / delta)**2))
    print(f"polos en ±{delta}i: grado {len(R) - 1}")

try:
    MiniChebfun(np.abs)
except RuntimeError as err:
    print("|x|:", err)

The constructor chooses degree 24 for exsin⁡5xe^x\sin 5x with error 2×10−152\times 10^{-15}, differentiates with roughly 100 times greater error 2.2×10−132.2\times 10^{-13} (differentiation amplifies rounding in high coefficients, multiplied by 2k2k in the recurrence), and integrates with error 3×10−163\times 10^{-16}. For poles, degrees (36, 68, 164 and 646 for δ=1\delta = 1, 0.50.5, 0.20.2 and 0.050.05) follow ln⁡(1014)/ln⁡ρ\ln(10^{14})/\ln\rho, predicting 37, 67, 162 and 645, and grow like 1/δ1/\delta as poles approach the interval, because ln⁡ρ≈δ\ln\rho \approx \delta for small δ\delta. With ∣x∣\abs{x} no plateau appears even at 16 38416\,384 points: coefficients decay like k−2k^{-2} and order 10710^7 points would be needed to reach 10−1410^{-14}. Chebfun handles this by splitting at the singular point.

Your own exp, measured in ulps

Now the three math-library steps. For Remez in float64, desired error is order 10−1810^{-18}, below rounding of er−p(r)e^r - p(r), and Remez cannot see extrema hidden by rounding. Instead approximate what remains after the first Taylor terms:

er=∑k=05rkk!+r6g(r),g(r)=∑j≥0rj(j+6)!.e^r = \sum_{k=0}^{5}\frac{r^k}{k!} + r^6 g(r), \qquad g(r) = \sum_{j \ge 0}\frac{r^j}{(j + 6)!}.

Relative error δ\delta in gg gives, in ere^r, error at most r6g(r) δ≤2.5×10−6 δr^6 g(r)\,\delta \le 2.5\times 10^{-6}\,\delta on reduced interval ∣r∣≤12ln⁡2\abs{r} \le \tfrac12\ln 2, so δ\delta of 10−1210^{-12} suffices, easily handled in float64. Exact reference is mpmath with 40 digits.

[ ]exp with range reduction and Remez, measured in ulpsBrowser
import math
import numpy as np
import mpmath

H = math.log(2) / 2
M = 5

def g(r):
    """Cola de la serie: (e^r - sum_{k<=5} r^k/k!) / r^6, sumada término a término (sin cancelación)."""
    r = np.asarray(r, dtype=float)
    s, t = np.zeros_like(r), np.full_like(r, 1 / math.factorial(M + 1))
    for j in range(25):
        s, t = s + t, t * r / (j + M + 2)
    return s

def remez_relativo(f, n, a, b, iters=8, m=20001):
    """Remez en la base de monomios con error relativo: p(x_i) + (-1)^i h f(x_i) = f(x_i)."""
    xx = np.linspace(a, b, m); fx = f(xx)
    ref = (a + b) / 2 - (b - a) / 2 * np.cos(np.pi * np.arange(n + 2) / (n + 1))
    for _ in range(iters):
        A = np.column_stack([np.vander(ref, n + 1, increasing=True), (-1.0) ** np.arange(n + 2) * f(ref)])
        sol = np.linalg.solve(A, f(ref)); c = sol[:-1]
        e = (fx - np.polyval(c[::-1], xx)) / fx
        cortes = np.flatnonzero(np.diff(np.sign(e))) + 1
        ext = [t[np.argmax(np.abs(e[t]))] for t in np.split(np.arange(m), cortes)]
        if len(ext) != n + 2:
            break
        ref = xx[ext]
    return c, np.max(np.abs(e))

cg, err_g = remez_relativo(g, 6, -H, H)
print(f"g: grado 6, error relativo minimax {err_g:.2e}  ->  error en e^r como mucho {H**6 * g(H) * err_g:.1e}")

LN2HI, LN2LO = 6.93147180369123816490e-01, 1.90821492927058770002e-10    # los de fdlibm
TAYLOR = [1 / math.factorial(k) for k in range(M + 1)]

def mi_exp(x, reordenada=False):
    x = np.asarray(x, dtype=float)
    k = np.rint(x / math.log(2))
    r = (x - k * LN2HI) - k * LN2LO                     # Cody-Waite
    q = np.polyval(cg[::-1], r)
    if not reordenada:
        for coef in TAYLOR[::-1]:                       # Horner de todo el polinomio
            q = q * r + coef
        p = q
    else:
        for coef in TAYLOR[:1:-1]:                      # q = 1/2 + r/6 + ...
            q = q * r + coef
        p = 1.0 + (r + r * r * q)                       # el 1 se suma al final, una sola vez
    return np.ldexp(p, k.astype(int))                   # 2^k, exacto

rng = np.random.default_rng(0)
x = np.concatenate([rng.uniform(-1, 1, 1500), rng.uniform(-700, 700, 1500)])
mpmath.mp.dps = 40
ref = [mpmath.exp(mpmath.mpf(float(v))) for v in x]

def ulps(y):
    return np.array([abs(float((mpmath.mpf(float(yy)) - R) / np.spacing(float(R)))) for yy, R in zip(y, ref)])

for nombre, y in [("mi_exp", mi_exp(x)), ("mi_exp reordenada", mi_exp(x, True)), ("np.exp", np.exp(x))]:
    u = ulps(y)
    print(f"{nombre:18s} error máximo {u.max():.3f} ulp   media {u.mean():.3f}   correctamente redondeados {np.mean(u <= 0.5):.1%}")

Approximation error no longer matters: degree-6 polynomial gg has relative error 1.1×10−121.1\times 10^{-12}, which in ere^r is at most 2.7×10−182.7\times 10^{-18}, about forty times below half an ulp of 1. Remaining error is rounding, measured in 3000 comparisons with mpmath. Horner on the whole polynomial has maximum error 1.091.09 ulp and 9.8 % of outputs are not nearest floats. Rearranging so 11 is added once, at the end, to a small quantity (r+r2qr + r^2q, whose rounding matters little relative to 1) lowers the maximum to 0.880.88 ulp without changing the correctly rounded fraction. np.exp has maximum error 0.5000.500 ulp and rounds correctly 99.9 % of cases: a table, short polynomial and extra-precision final sum achieve this. The gap from your version to the library is the last-bit engineering described by Muller.

Rational approximation: Padé and AAA

Polynomials have a limitation you have already seen: a singularity near the interval (the poles of 1/(1+25x2)1/(1 + 25x^2)) or inside it (∣x∣\abs{x}) forces them to enormous degrees. Ratios of polynomials, r=p/qr = p/q, do not have that problem: a pole is represented by a zero of qq.

The Padé approximant [m/k][m/k] is the rational function with deg⁡p≤m\deg p \le m and deg⁡q≤k\deg q \le k whose Taylor series agrees with that of ff through order m+km + k. It is computed using a linear system from the Taylor coefficients. For exe^x, the [2/2][2/2] is

ex≈1+x/2+x2/121−x/2+x2/12,e^x \approx \frac{1 + x/2 + x^2/12}{1 - x/2 + x^2/12},

and at [−1,1][-1, 1] its error is 4.0×10−34.0\times 10^{-3}, compared with 9.95×10−39.95\times 10^{-3} for the degree-4 Taylor polynomial, which uses the same five coefficients. But Padé inherits Taylor’s limitation: it is local, accurate at 0 and worse at the edges.

The modern version, the AAA algorithm (adaptive Antoulas-Anderson; Nakatsukasa, Sète and Trefethen, 2018), does for rational functions what Chebfun does for polynomials. Write the rational function in barycentric form,

r(z)=∑j=1mwjfjz−zj∑j=1mwjz−zj,r(z) = \frac{\sum_{j=1}^{m} \dfrac{w_j f_j}{z - z_j}}{\sum_{j=1}^{m} \dfrac{w_j}{z - z_j}},

which interpolates fj=f(zj)f_j = f(z_j) at the support points zjz_j for any nonzero weights. At each step it adds the sample point with maximum error as a support point (greedy) and chooses the weights by solving a linearized least-squares problem: the right singular vector for the smallest singular value of the Loewner matrix Aij=(Fi−fj)/(Zi−zj)A_{ij} = (F_i - f_j)/(Z_i - z_j) over the remaining samples. The paper presents the method as fast, flexible and robust and applies it to functions on arbitrary sets in the complex plane.

[ ]Padé and AAA from scratchBrowser
import math
import numpy as np

# Padé [m/k] de e^x: q(x) f(x) - p(x) = O(x^(m+k+1)), con q_0 = 1
def pade(a, m, k):
    """a: coeficientes de Taylor a_0..a_{m+k}. Devuelve (p, q) en potencias crecientes."""
    A = np.array([[a[m + i - j] if m + i - j >= 0 else 0.0 for j in range(1, k + 1)] for i in range(1, k + 1)])
    q = np.r_[1.0, np.linalg.solve(A, -np.array(a[m + 1: m + k + 1]))]
    p = np.array([sum(q[j] * a[i - j] for j in range(min(i, k) + 1)) for i in range(m + 1)])
    return p, q

a = [1 / math.factorial(i) for i in range(5)]
p, q = pade(a, 2, 2)
xx = np.linspace(-1, 1, 2001)
print("Padé [2/2] de e^x: p =", np.round(p, 6), " q =", np.round(q, 6))
print(f"  error en [-1, 1]: {np.max(np.abs(np.exp(xx) - np.polyval(p[::-1], xx) / np.polyval(q[::-1], xx))):.2e}"
      f"   Taylor de grado 4: {np.max(np.abs(np.exp(xx) - sum(a[i] * xx**i for i in range(5)))):.2e}")

def aaa(Z, F, tol=1e-13, mmax=60):
    libres = np.ones(len(Z), bool); zj, fj = [], []
    R = np.full(len(Z), F.mean()); errores = []
    for _ in range(mmax):
        j = np.argmax(np.abs(F - R))                      # voraz: donde peor va
        zj.append(Z[j]); fj.append(F[j]); libres[j] = False
        C = 1 / (Z[libres, None] - np.array(zj)[None, :])  # matriz de Cauchy
        A = (F[libres, None] - np.array(fj)[None, :]) * C  # matriz de Loewner
        w = np.linalg.svd(A, full_matrices=False)[2][-1].conj()
        R = F.copy(); R[libres] = (C @ (w * np.array(fj))) / (C @ w)
        errores.append(np.max(np.abs(F - R)))
        if errores[-1] <= tol * np.max(np.abs(F)):
            break
    return np.array(zj), np.array(fj), w, errores

Z = np.linspace(-1, 1, 2000)
zj, fj, w, err = aaa(Z, 1 / (1 + 25 * Z**2))
print(f"\nRunge con AAA: {len(zj)} puntos soporte (grado {len(zj) - 1}), error {err[-1]:.1e}")
zj, fj, w, err = aaa(Z, np.abs(Z), mmax=37)
print("|x| con AAA, error en las muestras según el grado:", {m: f"{err[m]:.0e}" for m in [4, 8, 16, 24, 32, 36]})
from numpy.polynomial import chebyshev as C
print("|x| con polinomios (interpolante de Chebyshev):", {n: f"{np.max(np.abs(C.chebval(Z, C.chebinterpolate(np.abs, n)) - np.abs(Z))):.0e}" for n in [10, 40, 160]})

The Runge function, which requires a polynomial of degree 168, is exactly a rational function of degree 2, and AAA finds it with three support points and rounding error. With ∣x∣\abs{x}, AAA’s error drops roughly tenfold every few degrees, whereas the polynomial interpolant’s error only halves when the degree doubles. This is the phenomenon Newman discovered in 1964: the best degree-nn rational approximation to ∣x∣\abs{x} converges like e−cne^{-c\sqrt n}, compared with 1/n1/n for polynomials (Trefethen, ATAP, chapter 25). Rational functions are the natural frontier of function approximation, and AAA has made them as easy to use as polynomials.

The DFT as a change of basis and the FFT

Now move from [−1,1][-1, 1] to signals of NN samples x0,…,xN−1x_0, \dots, x_{N-1} (in this section indices start at 0, as in the code and customary for the DFT). Let ω=e−2πi/N\omega = e^{-2\pi i/N}, a primitive NN-th root of unity.

Orthogonality follows from a geometric sum: for k≠lk \neq l, ∑nω(k−l)n=(1−ω(k−l)N)/(1−ωk−l)=0\sum_n \omega^{(k - l)n} = (1 - \omega^{(k-l)N})/(1 - \omega^{k-l}) = 0, because ωN=1\omega^N = 1. Thus the DFT is a change of basis to the orthogonal basis of exponentials e2πikn/Ne^{2\pi i kn/N}, and Xk/NX_k/N are the coordinates of x\vb{x} in it. These vectors are eigenvectors of all linear operators invariant under circular shifts, which is why they matter: in the Fourier basis a convolution becomes diagonal, as you will see.

Cooley–Tukey: divide and conquer

Computing FNx\mat{F}_N\vb{x} as a matrix-vector product costs N2N^2 complex multiplications. If NN is even, separate the even and odd indices:

Xk=∑m=0N/2−1x2m ω2mk+ωk∑m=0N/2−1x2m+1 ω2mk=Ek+ωkOk,X_k = \sum_{m=0}^{N/2-1} x_{2m}\,\omega^{2mk} + \omega^k\sum_{m=0}^{N/2-1} x_{2m+1}\,\omega^{2mk} = E_k + \omega^k O_k,

where EE and OO are the size-N/2N/2 DFTs of the even and odd samples, because ω2=e−2πi/(N/2)\omega^2 = e^{-2\pi i/(N/2)}. Both have period N/2N/2, and ωk+N/2=−ωk\omega^{k + N/2} = -\omega^k, so

Xk=Ek+ωkOk,Xk+N/2=Ek−ωkOk,k=0,…,N/2−1.X_k = E_k + \omega^kO_k, \qquad X_{k+N/2} = E_k - \omega^kO_k, \qquad k = 0, \dots, N/2 - 1.

This pair of formulas is a butterfly: one complex multiplication by the twiddle factor ωk\omega^k, one addition and one subtraction. If N=2pN = 2^p, the recursion reaches size 1. The cost satisfies T(N)=2T(N/2)+N/2T(N) = 2T(N/2) + N/2 multiplications, giving T(N)=N2log⁡2NT(N) = \frac N2\log_2 N, plus Nlog⁡2NN\log_2 N complex additions. This is the discrete Fourier transform and FFT of Cooley and Tukey (1965). The idea is older: Heideman, Johnson and Burrus (1984) found it in a manuscript by Gauss from around 1805, where he used it to interpolate asteroid orbits.

InteractiveFFT butterflies
inputstage 1stage 2output X_kW₈⁰W₈⁰W₈⁰W₈⁰W₈⁰W₈²W₈⁰W₈²W₈⁰W₈¹W₈²W₈³x₀ = 0x₄ = 4x₂ = 2x₆ = 6x₁ = 1x₅ = 5x₃ = 3x₇ = 7X₀X₁X₂X₃X₄X₅X₆X₇
  • current stage butterfly: a+Wba + Wb above
  • a−Wba - Wb below (subtraction)
  • twiddle factor W8j=e−2πij/8W_8^{j} = e^{-2\pi i j/8}, beside the input it multiplies
reordered input
2^10 = 1024
Multiplications completed (n = 8)0 of 12 · Direct DFT: 64
FFT, n = 2^10: (n/2)·log₂n5120
Direct DFT: n²1.05 M
Ratio n² / ((n/2) log₂ n)205
Input is placed in bit-reversed order: position i=(b2b1b0)2i = (b_2b_1b_0)_2 receives x(b0b1b2)2x_{(b_0b_1b_2)_2}. Each stage combines neighbors at distances 1, 2 and 4.
The 8-point decimation-in-time FFT. Input is placed in bit-reversed order and each stage combines pairs at distances 1, 2 and 4 with the twiddle factors W8j=e−2πij/8W_8^j = e^{-2\pi i j/8} shown next to the input they multiply. Step through the player and inspect the values in each column (below the diagram, for the selected signal). With the impulse at n=1n = 1, the output should be Xk=W8kX_k = W_8^k: check it. The counter compares the (n/2)log⁡2n(n/2)\log_2 n complex multiplications of the FFT with the n2n^2 of the direct DFT; increase nn to 2202^{20}.

The iterative version avoids recursion. If you unroll the recursion, sample xnx_n ends up at the position whose binary index is nn reversed (with N=8N = 8: x1=x001x_1 = x_{001} goes to position 100=4100 = 4), because each level separates by the least significant bit. So permute the input by bit reversal and apply log⁡2N\log_2 N in-place butterfly stages of size 2,4,…,N2, 4, \dots, N.

For NN that is not a power of 2, the idea generalizes to any factorization N=N1N2N = N_1N_2 (Cooley and Tukey already did this), and for prime NN there are algorithms that rewrite the DFT as a convolution (Rader, Bluestein). FFTW, Frigo and Johnson’s library, combines all of these and selects the fastest decomposition for your machine at runtime; their 2005 paper describes it as a DFT implementation that adapts to the hardware, and thanks to those algorithms for primes it keeps the cost O(Nlog⁡N)\bigO(N\log N) for any NN.

The discrete cosine transform

The DFT assumes that the signal is periodic: the nonexistent xNx_N is x0x_0. If the signal is not periodic (a ramp, a piece of an image), the periodic extension has a jump at the boundary, so the coefficients decay only like 1/k1/k and the truncated reconstruction has Gibbs oscillations. The solution is the same as for Chebyshev: reflect.

The connection to the DFT is exact. Form the even extension of length 2N2N, y=(x0,…,xN−1,xN−1,…,x0)\vb{y} = (x_0, \dots, x_{N-1}, x_{N-1}, \dots, x_0), and calculate its DFT with ω2N=e−iπ/N\omega_{2N} = e^{-i\pi/N}. Pairing nn with 2N−1−n2N - 1 - n,

Yk=∑n=0N−1xn(e−iπkn/N+eiπk(n+1)/N)=2eiπk/(2N)∑n=0N−1xncos⁡(πk(2n+1)2N)=2eiπk/(2N)Ck.Y_k = \sum_{n=0}^{N-1} x_n\big(e^{-i\pi kn/N} + e^{i\pi k(n + 1)/N}\big) = 2e^{i\pi k/(2N)}\sum_{n=0}^{N-1} x_n\cos\Big(\frac{\pi k(2n + 1)}{2N}\Big) = 2e^{i\pi k/(2N)}C_k.

Thus the DCT is a DFT of the reflected signal, computed with an FFT and, crucially, sees an extension without jumps: the reflected signal is continuous, and its coefficients decay like 1/k21/k^2 rather than 1/k1/k. This is energy compaction: for smooth signals almost all the energy lies in the first coefficients. It is also the same DCT used for the Chebyshev coefficients: f(cos⁡θ)f(\cos\theta) is the even extension of ff, viewed at θ\theta.

InteractiveSpectral compression: DFT versus DCT
What the DFT sees: periodic extension
What the DCT sees: even extension
Reconstruction with K=7K = 7 numbers
Relative error ∥x−xK∥2/∥x∥2\norm{x - x_K}_2/\norm{x}_2 versus KK
  • DFT
  • DCT
  • signal
  • truncated DFT
  • truncated DCT
  • jump in periodic extension
7
Relative error, DFT1.82e−1
Relative error, DCT1.22e−2
Maximum error DFT / DCT0.464 / 0.036
The DFT pays for the boundary jump (red): coefficients decay as 1/k1/k and Gibbs appears at the ends. The DCT does not see that jump: with K=7K = 7 its error is 15 times smaller.
A signal of 64 samples and what each transform sees: the DFT, the periodic extension with a jump (red) at the boundary; the DCT, the even extension, without a jump. In the middle, reconstruction retaining only KK low-frequency real numbers (the constant term and (K−1)/2(K-1)/2 pairs of complex coefficients for the DFT, the first KK coefficients for the DCT). Below, relative error versus KK. With the ramp, inspect the ends of the DFT reconstruction for small KK; then try the step: with an interior jump, both decay at the same slow rate and the DCT retains only a constant-factor advantage, around 1.4, because it does not also pay for the boundary jump.

JPEG builds on this: it divides the image into blocks of 8×88\times 8 pixels, applies the two-dimensional DCT-II to each (rows and then columns), quantizes the 64 coefficients more aggressively at higher frequencies and encodes the result, where most high-frequency coefficients have become zero.

[ ]The DCT is the DFT of the even extensionBrowser
import numpy as np
from scipy.fft import dct, idct, fft

N = 64
t = (np.arange(N) + 0.5) / N
x = t + 0.15 * np.sin(3 * t)                     # la rampa suave del interactivo

C = dct(x, type=2) / 2                           # scipy, sin normalizar, da 2 C_k
Y = fft(np.r_[x, x[::-1]])[:N]                   # DFT de la extensión par
print("max |Y_k - 2 e^{iπk/2N} C_k| =", np.max(np.abs(Y - 2 * np.exp(1j * np.pi * np.arange(N) / (2 * N)) * C)))

# compactación: error relativo al guardar K números reales
Cn = dct(x, norm="ortho")
X = np.fft.fft(x)
def err_dct(K):
    return np.linalg.norm(x - idct(np.r_[Cn[:K], np.zeros(N - K)], norm="ortho")) / np.linalg.norm(x)
def err_dft(K):
    m = (K - 1) // 2
    Xk = X.copy(); Xk[m + 1: N - m] = 0
    return np.linalg.norm(x - np.fft.ifft(Xk).real) / np.linalg.norm(x)
for K in [3, 7, 15, 31]:
    print(f"K = {K:2d}:  DFT {err_dft(K):.2e}   DCT {err_dct(K):.2e}")
k = np.arange(1, 20)
print("decaimiento |X_k| (DFT):", np.round(np.abs(X[k]) * k, 2)[:6], "≈ constante: 1/k")
print("decaimiento |C_k| (DCT), k impar:", np.round(np.abs(Cn[k[::2]]) * k[::2] ** 2, 2)[:6], "≈ constante: 1/k²")

The first line confirms the identity to machine precision. With K=7K = 7 numbers the DCT reconstructs the ramp with relative error 1.2 % and the DFT with 18 %; with K=31K = 31, 0.08 % versus 7.8 %. The last two lines explain it: ∣Xk∣ k\abs{X_k}\,k is nearly constant (decay 1/k1/k, the jump) and ∣Ck∣ k2\abs{C_k}\,k^2 is too (decay 1/k21/k^2, the corner of the even extension).

Sampling and aliasing

A continuous signal s(t)s(t) is observed at times tn=n/fst_n = n/f_s, with fsf_s the sampling frequency. For a complex exponential,

e2πi(f+mfs)tn=e2πiftn e2πimn=e2πiftn,m∈Z:e^{2\pi i(f + mf_s)t_n} = e^{2\pi i f t_n}\,e^{2\pi i m n} = e^{2\pi i f t_n}, \qquad m \in \Z:

frequencies differing by a multiple of fsf_s give exactly the same samples. For a real signal, moreover, cos⁡(2πftn)=cos⁡(2π(fs−f)tn)\cos(2\pi f t_n) = \cos(2\pi(f_s - f)t_n), so every frequency folds into the interval [0,fs/2][0, f_s/2]. This is sampling and aliasing: the apparent frequency is the distance from ff to the nearest multiple of fsf_s,

faparente=∣f−fsround⁡(f/fs)∣.f_{\text{aparente}} = \abs{f - f_s\operatorname{round}(f/f_s)}.

The limit fs/2f_s/2 is the Nyquist frequency, and the Nyquist–Shannon sampling theorem says it is precisely the limit: if ss has no frequency components ≥fs/2\ge f_s/2, the samples determine it completely and it can be reconstructed with sinc interpolation. If it does, information is lost: after sampling, no algorithm can distinguish 70 Hz from 30 Hz at fs=100f_s = 100 Hz. That is why analog-to-digital converters use a low-pass filter before sampling.

InteractiveThe wagon-wheel effect
sin⁡(2πft)\sin(2\pi f t) over one second, its samples and the sinusoid they trace
The wheel in the frames
frame 6
Spectrum ∣X∣\abs{X} of the samples (Hz)
peak at 1.0 Hz
Apparent frequency versus ff
fₛ/2
  • actual signal
  • samples / wheel marker
  • alias traced by samples and its spectral peak
  • folding: ∣f−fs round(f/fs)∣\abs{f - f_s\,\mathrm{round}(f/f_s)}
9.0
10
Nyquist limit fs/2f_s/25.0 Hz
Apparent frequency f−fs round(f/fs)f - f_s\,\mathrm{round}(f/f_s)−1.0 Hz
Rotation per frame (actual / apparent)324° / −36°
f>fs/2f > f_s/2: aliasing. Samples match a 1.0 Hz sinusoid and the wheel appears to turn backward at 1.0 turns/s.
A wheel rotates at ff revolutions per second and you photograph it at fsf_s frames per second. Above, the sinusoid of frequency ff (thin), its samples and the slower sinusoid they trace (dashed). Below, the wheel in each frame with the trail of the previous three, the spectrum of the samples and the folding curve f↦faparentef \mapsto f_{\text{aparente}}. The initial state already has aliasing: with f=9f = 9 Hz and fs=10f_s = 10 Hz, the wheel turns 324° per frame, appearing as −36°-36°: it seems to rotate backward at 1 revolution/s. Set ff to 10 (it appears stationary), 5 (right at the limit: the sine samples vanish), and 21.

The wheel shows something the real sinusoid hides: with a complex exponential (a rotation) the apparent frequency has a sign, f−fsround⁡(f/fs)∈[−fs/2,fs/2]f - f_s\operatorname{round}(f/f_s) \in [-f_s/2, f_s/2], indicating the direction of rotation. A real signal is the sum of two opposite rotations, so its spectrum is symmetric and only half is needed.

That sign also explains the FFT output order. Index kk corresponds to frequency kfs/Nk f_s/N, but because of aliasing k>N/2k > N/2 are the same as the negative frequencies (k−N)fs/N(k - N)f_s/N. np.fft.fftfreq(N, d=1/fs) returns frequencies in output order: first 0,1,…,N/2−10, 1, \dots, N/2 - 1 (for fs/Nf_s/N), then the negative −N/2,…,−1-N/2, \dots, -1. np.fft.fftshift reorders them from smallest to largest for plotting, and np.fft.rfft returns only the N/2+1N/2 + 1 nonnegative ones for a real signal.

Spectral leakage and windows

Observing a signal for a finite time multiplies it by a rectangular window, and the DFT of NN samples assumes that the observation repeats periodically. If a tone does not complete an integer number of cycles in the window, the repetition has a jump and its energy leaks into all bins, with slowly decaying sidelobes. These can mask weak components or, worse, appear to be nonexistent components. The remedy is a window w[n]w[n] that smoothly brings the signal to zero at the boundaries before the DFT, such as the Hann window, w[n]=12−12cos⁡(2πn/N)w[n] = \tfrac12 - \tfrac12\cos(2\pi n/N): in exchange for a wider main lobe (poorer resolution between nearby tones), the sidelobes decay much faster.

InteractiveSpectral leakage and windows
x[n] w[n]x[n]\,w[n] and its periodic extension (what the DFT sees)
Spectrum in dB relative to peak, bins 00 to 3232
  • DTFT of x wx\,w (zero-padded to 1024)
  • 64-point DFT
  • weak-tone level
  • window w[n]w[n]
10.50
−50
Window
Strong-tone leakage in bin 20−30.5 dB
Bin nearest f1f_1 versus peak−4.05 dB
The weak tone (−50 dB) is buried under strong-tone leakage at −30 dB in bin 20. It is a window artifact, not a signal component.
A strong tone at f1f_1 cycles per window and a weak one in bin 20, with 64 samples. Above, the windowed signal and its periodic copy, as seen by the DFT. Below, the spectrum in dB: the curve is the transform of the 64 samples with zero padding (what lies between bins) and the points are the 33 DFT values. Initially, f1=10.5f_1 = 10.5 with a rectangular window: leakage of the strong tone into bin 20 is only 30.5 dB below the peak and masks the −50-50 dB tone. Set f1f_1 to 10 (everything lines up) and back to 10.5; then switch to Hann and Blackman and lower the weak tone until even they cannot see it.
[ ]Frequency order, aliasing and window lobesBrowser
import numpy as np
from scipy.signal import get_window

# fftfreq: el orden de salida de la FFT
fs, N = 100.0, 8
print("fftfreq:          ", np.fft.fftfreq(N, d=1 / fs))
print("fftshift(fftfreq):", np.fft.fftshift(np.fft.fftfreq(N, d=1 / fs)))

# 70 Hz muestreados a 100 Hz durante 1 s
N = 100
t = np.arange(N) / fs
X = np.abs(np.fft.rfft(np.cos(2 * np.pi * 70 * t)))
print("pico del espectro de un coseno de 70 Hz a fs = 100 Hz:", np.fft.rfftfreq(N, 1 / fs)[np.argmax(X)], "Hz")
print("¿muestras idénticas a las de 30 Hz?", np.allclose(np.cos(2 * np.pi * 70 * t), np.cos(2 * np.pi * 30 * t)))

# lóbulo lateral más alto y fuga a 9.5 bins de un tono situado entre dos bins
N, Z = 64, 64 * 64
for nombre in ["boxcar", "hann", "blackman"]:
    w = get_window(nombre, N)                    # periódica, como la del interactivo
    W = np.abs(np.fft.rfft(w, Z)); W /= W[0]
    db = 20 * np.log10(W + 1e-300)
    primer_cero = np.argmax(np.diff(db) > 0)     # final del lóbulo principal
    n = np.arange(N)
    x = np.sin(2 * np.pi * 10.5 * n / N) * w
    S = np.abs(np.fft.fft(x, Z)); S /= S.max()
    print(f"{nombre:9s} lóbulo lateral más alto {db[primer_cero:].max():6.1f} dB   "
          f"ancho del lóbulo principal ±{primer_cero / 64:.0f} bins   fuga en el bin 20 {20 * np.log10(S[20 * 64]):6.1f} dB")

The output puts numbers to the figure. The rectangular window’s highest sidelobe is at −13.3-13.3 dB and its leakage in bin 20 (9.5 bins from the tone) is −30.5-30.5 dB below the peak; Hann lowers the highest sidelobe to −31.5-31.5 dB and leakage to −68.6-68.6 dB, and Blackman lowers them further (−58.1-58.1 and −76.5-76.5 dB), at the cost of a main lobe of ±2\pm 2 and ±3\pm 3 bins instead of ±1\pm 1. Choosing a window trades resolution (distinguishing nearby tones) against dynamic range (seeing a weak tone beside a strong one). Harris (1978) provides the classic analysis; spectral estimates of time series such as the periodogram use it routinely.

FFT convolution

The circular convolution of two vectors of length NN is

(x⊛y)n=∑m=0N−1xm y(n−m) mod N,(\vb{x} \circledast \vb{y})_n = \sum_{m=0}^{N-1} x_m\,y_{(n - m) \bmod N},

and the FFT diagonalizes it.

You will prove this in a guided exercise; the idea is that ωkn=ωkm ωk(n−m)\omega^{kn} = \omega^{km}\,\omega^{k(n - m)} and the exponent matters only modulo NN. A linear filter invariant under circular shifts is a circulant matrix, and the theorem says that the Fourier basis diagonalizes it, with eigenvalues DFT(y)\mathrm{DFT}(\vb{y}).

The convolutions you want are almost never circular. The linear convolution of x\vb{x} (length nn) and h\vb{h} (length mm), yk=∑jxjhk−jy_k = \sum_j x_j h_{k - j}, has length n+m−1n + m - 1. If you take FFTs of size LL and multiply, you obtain the circular convolution of size LL, which is the linear one folded: samples yky_k with k≥Lk \ge L are added to yk−Ly_{k - L}. To avoid folding, zero-pad both to L≥n+m−1L \ge n + m - 1. This gives FFT convolution: three FFTs of size LL and a product, O(Llog⁡L)\bigO(L\log L) versus the nmnm multiplications of the direct sum.

InteractiveCircular versus linear convolution
Input xx (n=48n = 48) and filter hh (bottom left, scaled)
h (×1.9)
Output: exact linear convolution versus circular convolution of size LL
L = 48
  • exact linear (length n+m−1n + m - 1)
  • circular, IDFT(DFT(x)⋅DFT(h))\mathrm{IDFT}(\mathrm{DFT}(x)\cdot\mathrm{DFT}(h))
  • samples contaminated by wraparound
  • tail that wraps around (lost)
16
0 (L = 48)
Required: L≥n+m−1L \ge n + m - 163
Contaminated samples15
Maximum error versus linear3.6e−1
Power of 2 to use64
With L=48L = 48 the output tail (indices 48 to 62) wraps around and adds to the first 15 samples. 15 zeros are missing.
A signal of n=48n = 48 samples (a pulse at the end and a bell at the beginning) filtered with an exponential filter of length mm. The thick line is the exact linear convolution; the points are IDFT(DFT(x)⋅DFT(h))\mathrm{IDFT}(\mathrm{DFT}(x)\cdot\mathrm{DFT}(h)) with both signals padded to L=n+PL = n + P. Without padding, the tail of the pulse wraps around and is added to the bell at the beginning (red points). Increase PP and observe how many samples are contaminated; the error drops to rounding error exactly at L=n+m−1L = n + m - 1. Change mm: the padding required is always m−1m - 1.

In practice LL is rounded up to an FFT-friendly length (a power of 2, or a product of small primes: scipy.fft.next_fast_len). For a very long signal and a short filter, use overlap-add: split the signal into blocks, convolve each block by FFT and add the tails of length m−1m - 1 to the next block; this is how scipy.signal.oaconvolve works.

Lab: FFT from scratch and fast convolution

Three ways to compute the DFT

[ ]Matrix DFT, recursive FFT and iterative FFTBrowser
import time
import numpy as np

def dft_matriz(x):
    N = len(x)
    n = np.arange(N)
    return np.exp(-2j * np.pi * np.outer(n, n) / N) @ x

def fft_recursiva(x):
    N = len(x)
    if N == 1:
        return x.astype(complex)
    E = fft_recursiva(x[0::2])
    O = fft_recursiva(x[1::2])
    w = np.exp(-2j * np.pi * np.arange(N // 2) / N)     # factores de giro tabulados
    return np.concatenate([E + w * O, E - w * O])

def fft_iterativa(x):
    x = np.asarray(x, dtype=complex)
    N = len(x)
    bits = N.bit_length() - 1
    idx = np.arange(N)
    rev = np.zeros(N, dtype=int)
    for b in range(bits):                               # inversión de bits, vectorizada
        rev |= ((idx >> b) & 1) << (bits - 1 - b)
    X = x[rev]
    m = 2
    while m <= N:                                       # etapas de mariposas de tamaño 2, 4, ..., N
        w = np.exp(-2j * np.pi * np.arange(m // 2) / m)
        X = X.reshape(-1, m)
        a, b = X[:, : m // 2], w * X[:, m // 2:]
        X = np.concatenate([a + b, a - b], axis=1).reshape(-1)
        m *= 2
    return X

def cronometra(f, x, rep=3):
    mejor = np.inf
    for _ in range(rep):
        t0 = time.perf_counter(); f(x); mejor = min(mejor, time.perf_counter() - t0)
    return mejor

rng = np.random.default_rng(1)
x = rng.normal(size=1024) + 1j * rng.normal(size=1024)
ref = np.fft.fft(x)
for nombre, f in [("DFT matricial", dft_matriz), ("FFT recursiva", fft_recursiva), ("FFT iterativa", fft_iterativa)]:
    print(f"{nombre:14s} error relativo frente a np.fft: {np.linalg.norm(f(x) - ref) / np.linalg.norm(ref):.1e}")

print("\n   N   DFT matricial   recursiva   iterativa    np.fft")
for N in [64, 256, 1024]:
    x = rng.normal(size=N)
    tiempos = [cronometra(f, x) for f in (dft_matriz, fft_recursiva, fft_iterativa, np.fft.fft)]
    print(f"{N:5d}   " + "   ".join(f"{1e3 * t:9.3f} ms" for t in tiempos))

Both FFTs agree with np.fft to relative error 4.6×10−164.6\times 10^{-16}; the matrix DFT has 1.3×10−131.3\times 10^{-13}, three hundred times more (the next section explains why). Timings are measured in your browser and vary between runs, but the ratios are stable. In the runs used to check the lesson, the matrix DFT multiplied its time by between 12 and 17 whenever NN quadrupled (close to the 16 predicted by cost N2N^2), the recursive version by about 4 (it pays Python overhead for each of its 2N−12N - 1 calls), and the iterative version by less than 2, because at these sizes its log⁡2N\log_2 N vectorized passes are dominated by a fixed cost per pass. np.fft (pocketfft, in C) was about ten times faster than the iterative version.

Accuracy compared with the direct DFT

To measure the error properly, we need an exact reference. A sum of exponentials with integer frequencies provides one: if xn=∑jaje2πikjn/Nx_n = \sum_j a_j e^{2\pi i k_j n/N}, its DFT equals NajNa_j in bins kjk_j and zero elsewhere.

[ ]Rounding error grows like log N, not NBrowser
import numpy as np

rng = np.random.default_rng(2)
print("    N    error FFT iterativa   error DFT matricial")
for p in [6, 8, 10, 12, 14]:
    N = 2**p
    k = rng.choice(N, size=5, replace=False)
    a = rng.normal(size=5) + 1j * rng.normal(size=5)
    n = np.arange(N)
    fase = 2 * np.pi * (np.outer(n, k) % N) / N        # reducir k·n módulo N antes: argumento < 2π, exacto
    x = (a[None, :] * np.exp(1j * fase)).sum(axis=1)
    exacta = np.zeros(N, complex); exacta[k] = N * a
    e_fft = np.linalg.norm(fft_iterativa(x) - exacta) / np.linalg.norm(exacta)
    e_dft = np.linalg.norm(dft_matriz(x) - exacta) / np.linalg.norm(exacta) if N <= 1024 else np.nan
    print(f"{N:5d}   {e_fft:16.1e}   {e_dft:18.1e}")

FFT error stays between 33 and 5×10−165\times 10^{-16} and barely changes when NN is multiplied by 256, whereas matrix DFT error grows in proportion to NN, from 7.5×10−157.5\times 10^{-15} with N=64N = 64 to 1.2×10−131.2\times 10^{-13} with N=1024N = 1024. The cause is its factors: dft_matriz computes e−2πikn/Ne^{-2\pi i kn/N} with the unreduced argument, which reaches 2πN2\pi N, and the absolute error in that argument (and hence in phase) is proportional to its size. Notice that the test signal does reduce knkn modulo NN before multiplying by 2π/N2\pi/N: without that precaution, the reference itself would have the same error and the experiment would measure nothing.

Fast convolution and its crossover point

[ ]FFT convolution versus direct convolutionBrowser
import time
import numpy as np
from scipy.signal import fftconvolve

def conv_fft(x, h):
    L = len(x) + len(h) - 1
    Lf = 1 << (L - 1).bit_length()                      # potencia de 2 >= n + m - 1
    y = np.fft.irfft(np.fft.rfft(x, Lf) * np.fft.rfft(h, Lf), Lf)
    return y[:L]

rng = np.random.default_rng(3)
x, h = rng.normal(size=1000), rng.normal(size=300)
print("error frente a np.convolve:   ", np.max(np.abs(conv_fft(x, h) - np.convolve(x, h))))
print("error frente a fftconvolve:   ", np.max(np.abs(conv_fft(x, h) - fftconvolve(x, h))))
sin_relleno = np.fft.irfft(np.fft.rfft(x) * np.fft.rfft(h, len(x)), len(x))
print("sin relleno (circular), error en las primeras 299 muestras:",
      np.max(np.abs(sin_relleno[:299] - np.convolve(x, h)[:299])))

print("\n  n = m   directa (np.convolve)   FFT propia   fftconvolve")
for n in [16, 64, 256, 1024, 4096]:
    x, h = rng.normal(size=n), rng.normal(size=n)
    t = [cronometra(lambda _: f(x, h), None, rep=3) for f in (np.convolve, conv_fft, fftconvolve)]
    print(f"{n:6d}   {1e3 * t[0]:14.3f} ms   {1e3 * t[1]:8.3f} ms   {1e3 * t[2]:8.3f} ms")

Padding to n+m−1n + m - 1 yields the linear convolution to machine precision; without padding, the first m−1=299m - 1 = 299 samples are completely wrong, the contamination shown in the figure. In the timings, direct convolution wins for short signals (its C loop has none of the overhead of three FFTs) and FFT wins for long ones: direct cost grows like n2n^2 and FFT cost like nlog⁡nn\log n. In the verification runs they tied around n=m=256n = m = 256, and with n=m=4096n = m = 4096 the homemade FFT was between 28 and 30 times faster. fftconvolve was slower than the homemade version on short signals: it validates arguments, chooses fast lengths that need not be powers of 2, and supports multiple dimensions, all with a fixed cost. This crossover is not universal: it depends on the implementation and hardware, so scipy.signal.convolve(method="auto") estimates both costs before choosing.

Images

In two dimensions everything repeats with the 2D FFT (rows then columns). For a kernel of k×kk\times k on an image of n×nn\times n, direct convolution costs n2k2n^2k^2 and the FFT costs O(n2log⁡n)\bigO(n^2\log n) independently of kk.

[ ]Blur an image: direct versus FFTBrowser
import numpy as np
from scipy.signal import convolve2d, fftconvolve

n = 256
u = np.linspace(-1, 1, n)
img = ((u[None, :]**2 + u[:, None]**2) < 0.4).astype(float) + 0.5 * (np.abs(u[None, :] - 0.3) < 0.05)
print("   k   directa      FFT     cociente   diferencia máxima")
for k in [3, 9, 21, 41]:
    s = np.arange(k) - k // 2
    g = np.exp(-(s[None, :]**2 + s[:, None]**2) / (2 * (k / 6)**2)); g /= g.sum()
    t_dir = cronometra(lambda _: convolve2d(img, g, mode="same"), None, rep=1)
    t_fft = cronometra(lambda _: fftconvolve(img, g, mode="same"), None, rep=1)
    dif = np.max(np.abs(convolve2d(img, g, mode="same") - fftconvolve(img, g, mode="same")))
    print(f"{k:4d}   {1e3 * t_dir:7.1f} ms   {1e3 * t_fft:5.1f} ms   {t_dir / t_fft:8.1f}   {dif:.1e}")

Direct convolution time grows with kernel area, k2k^2, while FFT time barely changes, so the ratio shoots up with filter size: in verification runs, with k=3k = 3 direct convolution was slightly faster, and with k=41k = 41, between 70 and 85 times slower. Both give the same result up to 10−1510^{-15}. That is why CNN convolutional layers (kernels of 3×33\times 3) are computed directly or with GEMM, and FFT only pays off for large filters.

In the libraries

FunctionWhat it doesDetail that matters
numpy.polynomial.Chebyshev.interpolate(f, deg)interpolant at first-kind Chebyshev pointsreturns an object with deriv, integ, roots; domain rescales to [a,b][a, b]
numpy.polynomial.chebyshev.chebfit(x, y, deg)discrete least squares in the Chebyshev basiswell conditioned, unlike polyfit at high degree
scipy.fft.fft, ifftcomplex DFT1/N1/N goes in ifft; norm="ortho" distributes it
scipy.fft.rfft, irfftDFT of a real signalreturns N/2+1N/2 + 1 coefficients; pass n to irfft if NN is odd
scipy.fft.fftfreq, rfftfreq, fftshiftfrequencies of each binorder 0,+,−0, +, -; fftshift centers it
scipy.fft.dct, idctDCT types I through IVtype=2 by default; norm="ortho" makes it orthogonal
scipy.fft.next_fast_len(n)convenient length ≥n\ge nproducts of 2, 3, 5 (and 7, 11 in some variants)
scipy.signal.fftconvolve, oaconvolve, convolveFFT, block or selected convolutionmode="full", "same", "valid"; convolve selects the method
scipy.signal.get_windowwindowsperiodic by default (fftbins=True), suitable for the DFT
[ ]The same calculations with numpy and scipyBrowser
import numpy as np
from numpy.polynomial import Chebyshev
from scipy import fft as sfft

f = lambda x: np.exp(x) * np.sin(5 * x)
p = Chebyshev.interpolate(f, 31)
xx = np.linspace(-1, 1, 5001)
print("Chebyshev.interpolate, grado 31:", np.max(np.abs(p(xx) - f(xx))))
print("coeficientes iguales a los de MiniChebfun:", np.max(np.abs(p.coef[:len(F)] - F.c)))
print("integral con integ():", p.integ(lbnd=-1)(1), "  MiniChebfun:", F.sum())

x = np.random.default_rng(4).normal(size=1000)
print("rfft frente a fft:", np.max(np.abs(sfft.rfft(x) - sfft.fft(x)[:501])))
print("dct orto es ortogonal:", np.allclose(sfft.idct(sfft.dct(x, norm="ortho"), norm="ortho"), x),
      "  conserva la norma:", np.isclose(np.linalg.norm(sfft.dct(x, norm="ortho")), np.linalg.norm(x)))
print("next_fast_len(1299) =", sfft.next_fast_len(1299), "  frente a la potencia de 2:", 1 << (1298).bit_length())

Common mistakes

Exercises

QuizTaylor versus Chebyshev
For exe^x on [−1,1][-1, 1], the degree-nn Taylor polynomial at 0 is worse than the Chebyshev series truncated to the same degree. Why, and how does the ratio between their maximum errors grow with nn (in exact arithmetic)?
NumericA folded frequency
A 70 Hz sinusoidal signal is sampled at 100 Hz. At what apparent frequency (in Hz, between 0 and the Nyquist frequency) is it observed?
NumericHow much the FFT saves
For n=220n = 2^{20}, approximately what is the ratio n2/(nlog⁡2n)n^2/(n\log_2 n) between the costs of the direct DFT and the FFT?
QuizHow many points?
You compute the best degree-5 approximation to a continuous function ff on [−1,1][-1, 1] with Remez. At the end, the error curve reaches its absolute maximum, with alternating signs, at exactly 6 points. What do you conclude?
NumericThe degree required by a pole
A function ff is analytic on [−1,1][-1, 1] and its closest singularity is a pair of poles at ±0.5i\pm 0.5i. Using ∣ak∣≈Cρ−k\abs{a_k} \approx C\rho^{-k} with the ρ\rho of the Bernstein ellipse passing through the poles, how many additional degrees does the series need to gain 10 decimal digits of accuracy (that is, for ρ−Δk=10−10\rho^{-\Delta k} = 10^{-10})?
NumericFFT size
You want the linear convolution of a 1000-sample signal with a 300-sample filter using an FFT with power-of-2 size. What is the smallest valid size?
QuizA nonexistent tone
You analyze 64 samples from a motor turning at 10.5 cycles per window and the spectrum shows a level about −30-30 dB relative to the peak in bin 20, where you expected a weak harmonic at −50-50 dB. What change lets you see it?
ProofThe circular convolution theorem
Prove: For x,y∈CN\vb{x}, \vb{y} \in \C^N, DFT(x⊛y)k=XkYk\mathrm{DFT}(\vb{x} \circledast \vb{y})_k = X_kY_k for every kk, where (x⊛y)n=∑mxmy(n−m) mod N(\vb{x} \circledast \vb{y})_n = \sum_{m} x_m y_{(n-m) \bmod N} and Xk=∑nxnωknX_k = \sum_n x_n\omega^{kn} with ω=e−2πi/N\omega = e^{-2\pi i/N}.
0
Write the DFT of the convolution: ∑n=0N−1(∑m=0N−1xmy(n−m) mod N)ωkn\sum_{n=0}^{N-1}\Big(\sum_{m=0}^{N-1} x_m y_{(n - m) \bmod N}\Big)\omega^{kn}.

Step 1 of 3. What is the first step?

CodeIterative radix-2 FFT
Implement fft_iterative(x) for power-of-2 lengths: a bit-reversal permutation and log⁡2N\log_2 N in-place butterfly stages, without recursion or calling np.fft. Vectorize each stage with numpy. The tests compare accuracy with np.fft.fft and check that time scales like Nlog⁡NN\log N rather than N2N^2.
import numpy as np

def fft_iterative(x):
  """DFT de x (longitud potencia de 2) con la FFT radix 2 iterativa."""
  x = np.asarray(x, dtype=complex)
  N = len(x)
  # 1) permutación por inversión de bits
  # 2) etapas de mariposas de tamaño m = 2, 4, ..., N con factores de giro exp(-2πi j/m)
  n = np.arange(N)
  return np.exp(-2j * np.pi * np.outer(n, n) / N) @ x    # DFT directa: correcta, pero O(N^2)
Shift+Enter to run

Connections

Summary

Key idea
Approximation means choosing a basis in which the function can be written with few coefficients: Chebyshev polynomials on an interval, complex exponentials on a period. The rate at which coefficients decay measures the function’s smoothness, and both bases are computed with the same tool, the FFT.
  • In an orthogonal basis, the best least-squares approximation is obtained coefficient by coefficient, without ill-conditioned systems; orthogonal polynomials are generated by a three-term recurrence because multiplication by xx is symmetric.
  • The Chebyshev series is the cosine series of f(cos⁡θ)f(\cos\theta). Its coefficients are computed with a DCT at Chebyshev points and decay like ρ−k\rho^{-k} if ff is analytic in the Bernstein ellipse EρE_\rho, and like k−ν−1k^{-\nu-1} if f(ν)f^{(\nu)} has a jump. Chebfun chooses the degree by looking for the rounding plateau.
  • The best approximation in the maximum norm equioscillates at n+2n + 2 points and is computed with Remez; truncated Chebyshev stays within a factor 1+Λn=O(log⁡n)1 + \Lambda_n = \bigO(\log n) of it, and Taylor much farther away.
  • Libraries compute exp, log and sin with range reduction (Cody–Waite, tables), a minimax polynomial on a small interval and exact reconstruction, with errors below 1 ulp.
  • The DFT is an orthogonal change of basis; the FFT computes it with butterflies in N2log⁡2N\frac N2\log_2 N multiplications and error O(log⁡N⋅u)\bigO(\log N\cdot u). The DCT is the DFT of the even extension and compacts the energy of smooth signals.
  • Sampling at fsf_s folds every frequency to [0,fs/2][0, f_s/2]; a finite window leaks energy between bins, and a smooth window controls it. FFT convolution is circular: pad to n+m−1n + m - 1.