Lesson 9 of 15

Windowing

Windowing

When computing the DFT of a finite signal, sharp edges at the start and end of the frame cause spectral leakage — energy from one frequency bin "leaks" into neighboring bins. A window function tapers the signal to zero at the edges, suppressing this effect.

The Hann Window

The Hann window (also called Hanning) is the most commonly used:

w[n]=0.5(1cos ⁣(2πnN1)),n=0,1,,N1w[n] = 0.5 \left(1 - \cos\!\left(\frac{2\pi n}{N-1}\right)\right), \quad n = 0, 1, \ldots, N-1

Properties:

  • w[0]=w[N1]=0w[0] = w[N-1] = 0 (tapers to zero at edges)
  • w[(N1)/2]=1.0w[(N-1)/2] = 1.0 (peak at center)
  • Smooth roll-off reduces leakage dramatically

Example: 4-Point Hann Window

w[0]=0.5(1cos(0))=0.0w[0] = 0.5(1 - \cos(0)) = 0.0 w[1]=0.5(1cos ⁣(2π3))=0.75w[1] = 0.5\left(1 - \cos\!\left(\frac{2\pi}{3}\right)\right) = 0.75 w[2]=0.5(1cos ⁣(4π3))=0.75w[2] = 0.5\left(1 - \cos\!\left(\frac{4\pi}{3}\right)\right) = 0.75 w[3]=0.5(1cos(2π))=0.0w[3] = 0.5\left(1 - \cos(2\pi)\right) = 0.0

Applying the Window

Windowing is an elementwise multiplication before the DFT:

xw[n]=x[n]w[n]x_w[n] = x[n] \cdot w[n]

Your Task

Implement:

  • hann_window(N) — returns [w[0],,w[N1]][w[0], \ldots, w[N-1]]
  • apply_window(x, w) — returns elementwise product [x[n]w[n]][x[n] \cdot w[n]]
import math

def hann_window(N):
    return [0.5 * (1 - math.cos(2 * math.pi * n / (N - 1))) for n in range(N)]

def apply_window(x, w):
    return [xi * wi for xi, wi in zip(x, w)]

print([round(v, 4) for v in hann_window(4)])  # [0.0, 0.75, 0.75, 0.0]
Python runtime loading...
Loading...
Click "Run" to execute your code.