Example

Pad first, roll second, transform third

Convolve a 64 by 64 field with a 7 by 7 kernel through the Fourier domain, and see why the centered construction agrees with direct convolution while two naive ones do not.

For a periodic domain, convolution in space is multiplication in frequency. The catch is that the kernel’s center has to sit at the array origin first, which is where the FFT bug in this book lived. This program convolves a random field with a 7 by 7 Gaussian bump three ways: the centered construction, the naive fft2 of the raw kernel, and ifftshift before padding.

Run it

Save this as fft_neighborhood.py and run it with Python 3.11 or later. It needs NumPy only.

import numpy as np


def periodic_convolve(state, kernel):
    kh, kw = kernel.shape
    out = np.zeros_like(state, dtype=np.float64)
    for dy in range(kh):
        for dx in range(kw):
            shifted = np.roll(np.roll(state, dy - kh // 2, 0), dx - kw // 2, 1)
            out += kernel[dy, dx] * shifted

    return out


def centered_kernel_fft(kernel, shape):
    padded = np.zeros(shape, dtype=np.float64)
    kh, kw = kernel.shape
    padded[:kh, :kw] = kernel
    padded = np.roll(padded, -(kh // 2), axis=0)
    padded = np.roll(padded, -(kw // 2), axis=1)
    return np.fft.fft2(padded)


def fft_backed_step(state, kernel_f, update_fn):
    field = np.fft.ifft2(np.fft.fft2(state) * kernel_f).real
    return update_fn(state, field)


def compare(a, b):
    error = np.max(np.abs(a - b))
    print("max error:", error)


rng = np.random.default_rng(42)
state = rng.random((64, 64))

radius = 3
side = 2 * radius + 1
axis = np.arange(-radius, radius + 1)
kernel = np.exp(-(axis[:, None] ** 2 + axis[None, :] ** 2) / (2 * 1.5 ** 2))

kernel_f = centered_kernel_fft(kernel, state.shape)

field_direct = periodic_convolve(state, kernel)
field_fft = fft_backed_step(state, kernel_f, lambda s, f: f)

print(f"kernel: {side}x{side} Gaussian bump, {side * side} taps, grid 64x64")
print("centered construction:")
compare(field_direct, field_fft)

naive_f = np.fft.fft2(kernel, state.shape)
field_naive = fft_backed_step(state, naive_f, lambda s, f: f)
print("naive fft2(kernel):")
compare(field_direct, field_naive)

rolled = np.roll(np.roll(field_direct, radius, axis=0), radius, axis=1)
print("naive is the direct field rolled by", radius, ":", bool(np.allclose(rolled, field_naive)))

misplaced = np.zeros_like(state)
misplaced[:side, :side] = np.fft.ifftshift(kernel)
print("ifftshift before padding:")
compare(field_direct, fft_backed_step(state, np.fft.fft2(misplaced), lambda s, f: f))

The program is the chapter’s own code in one file: the centered kernel transform, the FFT-backed step, the compare helper, and the three constructions. The additions are periodic_convolve, a direct reference from an earlier chapter, and a Gaussian bump.

Expected outcome

kernel: 7x7 Gaussian bump, 49 taps, grid 64x64
centered construction:
max error: 7.105427357601002e-15
naive fft2(kernel):
max error: 3.4844130952720835
naive is the direct field rolled by 3 : True
ifftshift before padding:
max error: 3.0200534926090663

The centered construction agrees with the direct convolution to floating-point noise. The naive one does not: its error is not small, it is a different field, rolled by 3 cells in both directions, the kernel’s half-width.

Where the center has to go

The correct construction is three steps in a fixed order: pad the kernel to the full array size, roll its center to the origin, then transform.

def centered_kernel_fft(kernel, shape):
    padded = np.zeros(shape, dtype=np.float64)
    kh, kw = kernel.shape
    padded[:kh, :kw] = kernel
    padded = np.roll(padded, -(kh // 2), axis=0)
    padded = np.roll(padded, -(kw // 2), axis=1)
    return np.fft.fft2(padded)

Centering has to happen at full array size: a circular convolution is a circular arrangement, so the wrapped half of the kernel lands at the far end of the array, not next to the origin. Applying ifftshift before padding rotates it inside its own box and misplaces that wrapped part.

Mechanism and limitations

Documented: the chapter states that the naive fft2 of a raw kernel “is wrong for the book’s own centered kernels” and treats index (0, 0) as the center, “silently shifts the whole field”; that ifftshift applied to the small kernel before padding “misplaces wrapped elements”; and that the correct construction is to pad first and then roll the center to the origin, verified at about 4e-16 across radii 3, 7 and 15.

Observed: the run above. The centered construction matched the direct shift-multiply-add convolution with a maximum error of 7.1e-15, floating-point noise, not a modeling discrepancy. The naive construction had a maximum error of 3.48, and the program established that this is a pure shift. The ifftshift variant had a maximum error of 3.02.

Not shown. The chapter’s performance claim is not tested here: the program does no timing, so nothing supports the crossover table where direct convolution wins at radius 1 and the FFT wins from radius 7 onward. One kernel radius and one grid size are used, so the verification across radii 3, 7 and 15 is not reproduced. Only the periodic boundary is in play, and the second level of validation, “behavioral agreement over time”, is not attempted: agreement is measured for one convolution, with no rollout.

Read the chapter .

Understand this example

Copy this prompt into your AI tool. No code runs here.

Apply this example

Copy this prompt into your AI tool. No code runs here.