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 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 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 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 rather than , making it one of history’s most used algorithms.
The lesson’s halves are the same idea in two bases. On the good basis is Chebyshev polynomials; on a period, complex exponentials. They are connected: , 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 on and inner product
Seeking minimizing means seeking the orthogonal projection of onto subspace : error must be orthogonal to all . Writing in basis gives normal equations with and .
The monomial basis is disastrous. With on , is the Hilbert matrix, whose condition number grows like ; on the situation is similar. This is the numerical least-squares problem again: columns are almost parallel because for large 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:
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 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 has degree at most , because both terms are monic of degree . Since is an orthogonal basis of , with . Compute numerators. By orthogonality for , so . Crucially, multiplication by is symmetric in this inner product:
If , has degree and is orthogonal to : . Only , giving , and survive; for the latter gives and . Rearranging gives .
∎Each weight gives a family; these three are most useful (in standard, not monic, normalization):
| Family | Interval and weight | Recurrence | Use |
|---|---|---|---|
| Legendre | , | unweighted least squares, Gaussian quadrature | |
| Chebyshev | , | near-optimal maximum-norm approximation | |
| Hermite | , | expectations under a normal distribution |
Hermite polynomials turn with into a short sum, next lesson’s Gauss–Hermite quadrature. Coefficients form the tridiagonal Jacobi matrix whose eigenvalues are Gaussian quadrature nodes.
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 with , and error rises from (degree 12) to (degree 20): adding degrees worsens approximation. Legendre stays between and : 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 : for Legendre, then for monic Chebyshev, and for Hermite.
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 are zero (the three weights are symmetric), and 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 ,
Induction using verifies this, exactly recurrence . Thus oscillates between and with extrema at , and substitution makes everything on periodic on . Weight is not arbitrary: it makes , turning orthogonality of into cosine orthogonality:
With , formula says the Chebyshev series of is the Fourier cosine series of , which is even and -periodic. Everything about Fourier series carries over.
Computation by a cosine transform
The integrals do not use generic quadrature. Take Chebyshev points of the first kind, with , (zeros of , the previous lesson’s Chebyshev nodes). Cosines are discretely orthogonal there too: for not both zero. Thus the polynomial interpolating at these points, , has coefficients
This sum is a type-II discrete cosine transform, studied below and computed by FFT in . are not exactly : cosines of frequencies , , , … agree on up to sign, so interpolation adds them. Substitute the series to verify:
This is coefficient aliasing, the same phenomenon seen in signals. If have fallen below before , both sets agree to machine precision and are indistinguishable in practice.
Decay reveals smoothness
These series are useful because the decay rate of is precisely related to regularity of , in two distinct regimes.
The proof integrates by parts times in : each integration contributes factor . Thus (, has variation 2) has ; indeed . has and a jump, .
For analytic functions decay is geometric, with rate set by a geometric object. The Bernstein ellipse , , is the complex region enclosed by the image of circle under Joukowski transform : an ellipse with foci and semiaxes and summing to .
Proof
Define . Joukowski’s map takes annulus inside (each interior point except has two preimages and ), so is analytic in the annulus with . On the unit circle and . This is the Laurent series of , whose coefficients can be computed on any circle in the annulus:
Taking gives . The error bound is the geometric tail sum , because on .
∎The nearest singularity sets . A function with poles at , such as , is analytic in any ellipse excluding them; the largest passes through them, with minor semiaxis , giving . Runge’s function has : coefficient envelope falls 18 % per degree (odd coefficients vanish since the function is even), requiring about 170 to reach . An entire function such as is analytic in every ellipse and coefficients decay faster than any .
Notice the floor: below coefficients stop falling and form a rounding-noise plateau, because values are known only to relative precision . Chebfun uses this plateau to choose degree.
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, measured on the coefficient line matches to four digits, and the last coefficient above occurs at , and for , and . For singular functions log-log slopes are near , and . The aliasing line shows that with only 8 points coefficient is no longer , but equals 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 is , tiny near 0 and maximal at endpoints. Chebyshev truncation spreads error across the interval, almost like , which oscillates at constant amplitude.
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 (at ) and Chebyshev truncation’s , about a thousand times less with the same coefficient count. Truncation error is almost exactly as predicted. Quantitatively, both errors are the size of the first discarded term, but in the Taylor basis it is , equal to at , while in Chebyshev it is , and because (the leading coefficient of is ).
Best approximation: minimax and equioscillation
Least squares minimizes average error. Often the worst case matters: a math library guarantees error for all . The question becomes
The minimum exists (in finite-dimensional 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.
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 equioscillates at and exists with . Then satisfies, at each ,
because . Polynomial changes sign between consecutive points: changes, hence roots. But , so and , contradicting . Necessity follows conversely: if error alternates at fewer than 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- polynomial for is , because error equioscillates at the extrema of . 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 points and repeats two steps:
- Level. Solve the linear system of equations in unknowns . The polynomial has exactly alternating error on the reference.
- Exchange. Find local extrema of error throughout the interval, one per constant-sign segment, and use them as the new reference.
There is a free certificate. If error of alternates sign at points, no degree- polynomial can have error smaller than the smallest of those (the proof’s argument with instead of , the de la Vallée Poussin theorem). In particular,
and when both bounds agree, you are done.
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 moves from to and maximum error exceeds it by only ; second, both bounds agree to all printed digits: , with equioscillation points at , , , and . The distance between and falls from to 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: without solving anything, versus Taylor’s . This is no accident. Let be a linear operator reproducing (), such as truncation or interpolation. For any , , so
taking , with the operator’s Lebesgue constant. For truncation, since it is the Fourier partial sum of , is the Fourier-series Lebesgue constant, growing like . The cell computes it: for , for , for and for , always about above . Even at degree 1000 truncation loses at most factor versus optimal, under one decimal digit. For Chebyshev-point interpolation the constant is smaller still, order (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):
- Reduction. Write with and . Then . Subtraction is delicate: rounding to float64 multiplies error by (up to 1024). Cody and Waite’s trick splits into
ln2HI, whose last bits are zero soln2HIis exact, and correctionln2LO, computing . - Approximation. On fdlibm approximates auxiliary function with a degree-5 polynomial in obtained by “a special Remez algorithm”; its code comment bounds error by . It recovers by division.
- Reconstruction. Multiply by by adding 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 , split with , so , and approximate near 1 (fdlibm uses variable , in which is odd and well approximated on ). For reduce modulo , with , and depending on evaluate or . For enormous (, for example), reduction needs hundreds of bits of : the Payne–Hanek algorithm.
Modern libraries add a table. Arm’s exp implementation (optimized-routines, math/exp.c) reduces using , stores for in a table and leaves , an interval small enough for a degree-4 or degree-5 polynomial. Its comment bounds error by 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 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 (downward from , with and halved at the end), derived from . Integration gives if is even, 0 if odd.
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 with error , differentiates with roughly 100 times greater error (differentiation amplifies rounding in high coefficients, multiplied by in the recurrence), and integrates with error . For poles, degrees (36, 68, 164 and 646 for , , and ) follow , predicting 37, 67, 162 and 645, and grow like as poles approach the interval, because for small . With no plateau appears even at points: coefficients decay like and order points would be needed to reach . 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 , below rounding of , and Remez cannot see extrema hidden by rounding. Instead approximate what remains after the first Taylor terms:
Relative error in gives, in , error at most on reduced interval , so of suffices, easily handled in float64. Exact reference is mpmath with 40 digits.
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 has relative error , which in is at most , 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 ulp and 9.8 % of outputs are not nearest floats. Rearranging so is added once, at the end, to a small quantity (, whose rounding matters little relative to 1) lowers the maximum to ulp without changing the correctly rounded fraction. np.exp has maximum error 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 ) or inside it () forces them to enormous degrees. Ratios of polynomials, , do not have that problem: a pole is represented by a zero of .
The Padé approximant is the rational function with and whose Taylor series agrees with that of through order . It is computed using a linear system from the Taylor coefficients. For , the is
and at its error is , compared with 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,
which interpolates at the support points 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 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.
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 , 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- rational approximation to converges like , compared with 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 to signals of samples (in this section indices start at 0, as in the code and customary for the DFT). Let , a primitive -th root of unity.
Orthogonality follows from a geometric sum: for , , because . Thus the DFT is a change of basis to the orthogonal basis of exponentials , and are the coordinates of 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 as a matrix-vector product costs complex multiplications. If is even, separate the even and odd indices:
where and are the size- DFTs of the even and odd samples, because . Both have period , and , so
This pair of formulas is a butterfly: one complex multiplication by the twiddle factor , one addition and one subtraction. If , the recursion reaches size 1. The cost satisfies multiplications, giving , plus 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.
The iterative version avoids recursion. If you unroll the recursion, sample ends up at the position whose binary index is reversed (with : goes to position ), because each level separates by the least significant bit. So permute the input by bit reversal and apply in-place butterfly stages of size .
For that is not a power of 2, the idea generalizes to any factorization (Cooley and Tukey already did this), and for prime 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 for any .
The discrete cosine transform
The DFT assumes that the signal is periodic: the nonexistent is . 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 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 , , and calculate its DFT with . Pairing with ,
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 rather than . 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: is the even extension of , viewed at .
JPEG builds on this: it divides the image into blocks of 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.
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 numbers the DCT reconstructs the ramp with relative error 1.2 % and the DFT with 18 %; with , 0.08 % versus 7.8 %. The last two lines explain it: is nearly constant (decay , the jump) and is too (decay , the corner of the even extension).
Sampling and aliasing
A continuous signal is observed at times , with the sampling frequency. For a complex exponential,
frequencies differing by a multiple of give exactly the same samples. For a real signal, moreover, , so every frequency folds into the interval . This is sampling and aliasing: the apparent frequency is the distance from to the nearest multiple of ,
The limit is the Nyquist frequency, and the Nyquist–Shannon sampling theorem says it is precisely the limit: if has no frequency components , 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 Hz. That is why analog-to-digital converters use a low-pass filter before sampling.
The wheel shows something the real sinusoid hides: with a complex exponential (a rotation) the apparent frequency has a sign, , 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 corresponds to frequency , but because of aliasing are the same as the negative frequencies . np.fft.fftfreq(N, d=1/fs) returns frequencies in output order: first (for ), then the negative . np.fft.fftshift reorders them from smallest to largest for plotting, and np.fft.rfft returns only the 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 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 that smoothly brings the signal to zero at the boundaries before the DFT, such as the Hann window, : in exchange for a wider main lobe (poorer resolution between nearby tones), the sidelobes decay much faster.
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 dB and its leakage in bin 20 (9.5 bins from the tone) is dB below the peak; Hann lowers the highest sidelobe to dB and leakage to dB, and Blackman lowers them further ( and dB), at the cost of a main lobe of and bins instead of . 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 is
and the FFT diagonalizes it.
You will prove this in a guided exercise; the idea is that and the exponent matters only modulo . A linear filter invariant under circular shifts is a circulant matrix, and the theorem says that the Fourier basis diagonalizes it, with eigenvalues .
The convolutions you want are almost never circular. The linear convolution of (length ) and (length ), , has length . If you take FFTs of size and multiply, you obtain the circular convolution of size , which is the linear one folded: samples with are added to . To avoid folding, zero-pad both to . This gives FFT convolution: three FFTs of size and a product, versus the multiplications of the direct sum.
In practice 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 to the next block; this is how scipy.signal.oaconvolve works.
Lab: FFT from scratch and fast convolution
Three ways to compute the DFT
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 ; the matrix DFT has , 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 quadrupled (close to the 16 predicted by cost ), the recursive version by about 4 (it pays Python overhead for each of its calls), and the iterative version by less than 2, because at these sizes its 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 , its DFT equals in bins and zero elsewhere.
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 and and barely changes when is multiplied by 256, whereas matrix DFT error grows in proportion to , from with to with . The cause is its factors: dft_matriz computes with the unreduced argument, which reaches , and the absolute error in that argument (and hence in phase) is proportional to its size. Notice that the test signal does reduce modulo before multiplying by : without that precaution, the reference itself would have the same error and the experiment would measure nothing.
Fast convolution and its crossover point
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 yields the linear convolution to machine precision; without padding, the first 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 and FFT cost like . In the verification runs they tied around , and with 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 on an image of , direct convolution costs and the FFT costs independently of .
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, , while FFT time barely changes, so the ratio shoots up with filter size: in verification runs, with direct convolution was slightly faster, and with , between 70 and 85 times slower. Both give the same result up to . That is why CNN convolutional layers (kernels of ) are computed directly or with GEMM, and FFT only pays off for large filters.
In the libraries
| Function | What it does | Detail that matters |
|---|---|---|
numpy.polynomial.Chebyshev.interpolate(f, deg) | interpolant at first-kind Chebyshev points | returns an object with deriv, integ, roots; domain rescales to |
numpy.polynomial.chebyshev.chebfit(x, y, deg) | discrete least squares in the Chebyshev basis | well conditioned, unlike polyfit at high degree |
scipy.fft.fft, ifft | complex DFT | goes in ifft; norm="ortho" distributes it |
scipy.fft.rfft, irfft | DFT of a real signal | returns coefficients; pass n to irfft if is odd |
scipy.fft.fftfreq, rfftfreq, fftshift | frequencies of each bin | order ; fftshift centers it |
scipy.fft.dct, idct | DCT types I through IV | type=2 by default; norm="ortho" makes it orthogonal |
scipy.fft.next_fast_len(n) | convenient length | products of 2, 3, 5 (and 7, 11 in some variants) |
scipy.signal.fftconvolve, oaconvolve, convolve | FFT, block or selected convolution | mode="full", "same", "valid"; convolve selects the method |
scipy.signal.get_window | windows | periodic by default (fftbins=True), suitable for the DFT |
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
Step 1 of 3. What is the first step?
fft_iterative(x) for power-of-2 lengths: a bit-reversal permutation and 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 rather than .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)Connections
- CNN convolutions (2D discrete convolution) can be computed with FFT when filters are large; for the usual filters, direct computation wins, as you measured.
- The periodogram and Welch spectral estimation use FFTs of a time series with windows and averaging: the leakage and windows of this lesson applied to noisy data.
- Long-sequence models that turn a linear recurrence into a convolution (SSM recurrence–convolution duality) evaluate it with an FFT in , and sinusoidal positional encoding is a Fourier basis.
- Spectral methods for PDEs (Chebyshev spectral collocation, pseudospectral dealiasing) are Chebyshev and Fourier series with derivatives calculated on the coefficients, as in your Mini Chebfun.
- In graphs, spectral filters are approximated with Chebyshev polynomials of the Laplacian (Chebyshev filter approximation), and in finance, Fourier option pricing computes option prices with FFTs and cosine series.
- The next lesson closes the circle: integrating a Chebyshev series is Clenshaw–Curtis quadrature, and the trapezoidal rule for periodic functions converges exponentially because of the same coefficient decay you have seen here.
Summary
- 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 is symmetric.
- The Chebyshev series is the cosine series of . Its coefficients are computed with a DCT at Chebyshev points and decay like if is analytic in the Bernstein ellipse , and like if has a jump. Chebfun chooses the degree by looking for the rounding plateau.
- The best approximation in the maximum norm equioscillates at points and is computed with Remez; truncated Chebyshev stays within a factor 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 multiplications and error . The DCT is the DFT of the even extension and compacts the energy of smooth signals.
- Sampling at folds every frequency to ; a finite window leaks energy between bins, and a smooth window controls it. FFT convolution is circular: pad to .