TExcelTAD
Home › Fourier Analysis & Signals › Fourier & Signals Exercises

Fourier & Signals Exercises

Time to practise the whole course. Each exercise has a starter program that runs but does not do the job yet. Replace the TODO parts, press ▶ Run, and compare your result with the expected output. The output block under each starter shows what the unfinished starter prints.

Tip: Test every function on a signal whose answer you know: a delta, a constant, or a sinusoid that fits the frame exactly. Print a few values with np.round(..., 4).tolist() before trusting a whole spectrum.

# Exercise Practises
1 A DFT from the definition the DFT formula, complex exponentials
2 Read an amplitude spectrum rfft, rfftfreq, scaling
3 Predict aliases sampling, folding
4 Linear convolution with the FFT the convolution theorem, zero padding
5 Measure window sidelobes leakage, Hann window
6 Zeros of a moving average frequency response
7 A one-pole IIR filter difference equations, step response
8 Blur an image in frequency 2-D FFT, Gaussian filter

Exercise 1: A DFT from the definition

Implement X[k]=∑nx[n]e−2πikn/NX[k] = \sum_n x[n] e^{-2\pi i k n/N} with a loop (or a matrix) and compare with np.fft.fft (The Discrete Fourier Transform).

python · try it yourself
import numpy as np

def dft(x):
    N = len(x)
    X = np.zeros(N, dtype=complex)
    for k in range(N):
        pass                              # TODO: X[k] = sum over n of x[n] * exp(-2j*pi*k*n/N)
    return X

x = np.array([1.0, 2.0, 0.0, -1.0, 3.0, 0.5])
print("matches np.fft.fft:", np.allclose(dft(x), np.fft.fft(x)))
print("X[1] =", complex(np.round(dft(x)[1], 4)))
matches np.fft.fft: False
X[1] = 0j

Expected output when solved:

text
matches np.fft.fft: True
X[1] = (1.75+1.299j)
Solution
python · try it yourself
import numpy as np

def dft(x):
    N = len(x)
    n = np.arange(N)
    X = np.zeros(N, dtype=complex)
    for k in range(N):
        X[k] = np.sum(x * np.exp(-2j * np.pi * k * n / N))
    return X

x = np.array([1.0, 2.0, 0.0, -1.0, 3.0, 0.5])
print("matches np.fft.fft:", np.allclose(dft(x), np.fft.fft(x)))
print("X[1] =", complex(np.round(dft(x)[1], 4)))
matches np.fft.fft: True
X[1] = (1.75+1.299j)

Exercise 2: Read an amplitude spectrum

A recording contains a few sinusoids. Convert the rfft output into amplitudes and print each component's frequency and amplitude (The FFT in NumPy).

python · try it yourself
import numpy as np

fs = 400
t = np.arange(0, 1, 1 / fs)
x = 0.8 * np.cos(2 * np.pi * 25 * t) + 1.7 * np.sin(2 * np.pi * 60 * t) + 0.4 * np.cos(2 * np.pi * 130 * t + 1)

X = np.fft.rfft(x)
f = np.fft.rfftfreq(len(x), 1 / fs)
A = np.abs(X)                             # TODO: scale to amplitudes (factor 2/N for 0 < f < fs/2)
for fi, a in zip(f, A):
    if a > 0.1:
        print(f"{fi:5.1f} Hz: {a:.3f}")
 25.0 Hz: 160.000
 60.0 Hz: 340.000
130.0 Hz: 80.000

Expected output when solved:

text
 25.0 Hz: 0.800
 60.0 Hz: 1.700
130.0 Hz: 0.400
Solution
python · try it yourself
import numpy as np

fs = 400
t = np.arange(0, 1, 1 / fs)
x = 0.8 * np.cos(2 * np.pi * 25 * t) + 1.7 * np.sin(2 * np.pi * 60 * t) + 0.4 * np.cos(2 * np.pi * 130 * t + 1)

X = np.fft.rfft(x)
f = np.fft.rfftfreq(len(x), 1 / fs)
A = 2 * np.abs(X) / len(x)
for fi, a in zip(f, A):
    if a > 0.1:
        print(f"{fi:5.1f} Hz: {a:.3f}")
 25.0 Hz: 0.800
 60.0 Hz: 1.700
130.0 Hz: 0.400

Exercise 3: Predict aliases

Write alias(f, fs) returning the apparent frequency in [0,fs/2][0, f_s/2] (Aliasing), then confirm each prediction with an FFT.

python · try it yourself
import numpy as np

def alias(f, fs):
    return f                              # TODO: fold f into [0, fs/2]

fs = 1000
for f in (120, 880, 1130, 1960):
    t = np.arange(0, 1, 1 / fs)
    seen = np.fft.rfftfreq(fs, 1 / fs)[np.argmax(np.abs(np.fft.rfft(np.cos(2 * np.pi * f * t))))]
    print(f"{f:5d} Hz: predicted {alias(f, fs):5.0f} Hz, FFT shows {seen:5.0f} Hz")
  120 Hz: predicted   120 Hz, FFT shows   120 Hz
  880 Hz: predicted   880 Hz, FFT shows   120 Hz
 1130 Hz: predicted  1130 Hz, FFT shows   130 Hz
 1960 Hz: predicted  1960 Hz, FFT shows    40 Hz

Expected output when solved:

text
  120 Hz: predicted   120 Hz, FFT shows   120 Hz
  880 Hz: predicted   120 Hz, FFT shows   120 Hz
 1130 Hz: predicted   130 Hz, FFT shows   130 Hz
 1960 Hz: predicted    40 Hz, FFT shows    40 Hz
Solution
python · try it yourself
import numpy as np

def alias(f, fs):
    return abs(f - fs * round(f / fs))

fs = 1000
for f in (120, 880, 1130, 1960):
    t = np.arange(0, 1, 1 / fs)
    seen = np.fft.rfftfreq(fs, 1 / fs)[np.argmax(np.abs(np.fft.rfft(np.cos(2 * np.pi * f * t))))]
    print(f"{f:5d} Hz: predicted {alias(f, fs):5.0f} Hz, FFT shows {seen:5.0f} Hz")
  120 Hz: predicted   120 Hz, FFT shows   120 Hz
  880 Hz: predicted   120 Hz, FFT shows   120 Hz
 1130 Hz: predicted   130 Hz, FFT shows   130 Hz
 1960 Hz: predicted    40 Hz, FFT shows    40 Hz

Exercise 4: Linear convolution with the FFT

Complete fft_convolve so it pads correctly and matches np.convolve (Circular and Fast Convolution).

python · try it yourself
import numpy as np

def fft_convolve(x, h):
    N = max(len(x), len(h))               # TODO: N must be at least len(x) + len(h) - 1
    y = np.fft.irfft(np.fft.rfft(x, N) * np.fft.rfft(h, N), N)
    return y[:len(x) + len(h) - 1]

x = np.array([1.0, 2.0, 3.0, 4.0, 5.0])
h = np.array([1.0, 0.0, -1.0])
print("fft :", (np.round(fft_convolve(x, h), 6) + 0.0).tolist())
print("true:", np.convolve(x, h).tolist())
fft : [-3.0, -3.0, 2.0, 2.0, 2.0]
true: [1.0, 2.0, 2.0, 2.0, 2.0, -4.0, -5.0]

Expected output when solved:

text
fft : [1.0, 2.0, 2.0, 2.0, 2.0, -4.0, -5.0]
true: [1.0, 2.0, 2.0, 2.0, 2.0, -4.0, -5.0]
Solution
python · try it yourself
import numpy as np

def fft_convolve(x, h):
    N = len(x) + len(h) - 1
    y = np.fft.irfft(np.fft.rfft(x, N) * np.fft.rfft(h, N), N)
    return y[:len(x) + len(h) - 1]

x = np.array([1.0, 2.0, 3.0, 4.0, 5.0])
h = np.array([1.0, 0.0, -1.0])
print("fft :", (np.round(fft_convolve(x, h), 6) + 0.0).tolist())
print("true:", np.convolve(x, h).tolist())
fft : [1.0, 2.0, 2.0, 2.0, 2.0, -4.0, -5.0]
true: [1.0, 2.0, 2.0, 2.0, 2.0, -4.0, -5.0]

Exercise 5: Measure window sidelobes

Compute the highest sidelobe (in dB relative to the main peak) of the rectangular and periodic Hann windows of length 64 (Window Functions). Zero-pad heavily so the curve is well sampled.

python · try it yourself
import numpy as np

N, pad = 64, 64 * 64
n = np.arange(N)
for name, w in (("rectangular", np.ones(N)), ("hann", np.ones(N))):   # TODO: the Hann window 0.5 - 0.5 cos(2 pi n / N)
    W = np.abs(np.fft.rfft(w, pad))
    W_db = 20 * np.log10(W / W[0] + 1e-15)
    first_null = np.argmax(np.diff(W) > 0)
    print(f"{name:12s} highest sidelobe {W_db[first_null:].max():6.1f} dB")
rectangular  highest sidelobe  -13.3 dB
hann         highest sidelobe  -13.3 dB

Expected output when solved:

text
rectangular  highest sidelobe  -13.3 dB
hann         highest sidelobe  -31.5 dB
Solution
python · try it yourself
import numpy as np

N, pad = 64, 64 * 64
n = np.arange(N)
for name, w in (("rectangular", np.ones(N)), ("hann", 0.5 - 0.5 * np.cos(2 * np.pi * n / N))):
    W = np.abs(np.fft.rfft(w, pad))
    W_db = 20 * np.log10(W / W[0] + 1e-15)
    first_null = np.argmax(np.diff(W) > 0)
    print(f"{name:12s} highest sidelobe {W_db[first_null:].max():6.1f} dB")
rectangular  highest sidelobe  -13.3 dB
hann         highest sidelobe  -31.5 dB

Exercise 6: Zeros of a moving average

Compute the frequency response of a 10-point moving average at fs=1000f_s = 1000 Hz and list the frequencies up to 500 Hz where the gain is (numerically) zero (The Moving-Average Filter).

python · try it yourself
import numpy as np

M, fs = 10, 1000
h = np.ones(M) / M
f = np.arange(0, 501, 10)
gain = np.ones(len(f))                    # TODO: |sum h[k] exp(-2j pi f k / fs)| for each f
print("zero-gain frequencies:", f[gain < 1e-9].tolist())
zero-gain frequencies: []

Expected output when solved:

text
zero-gain frequencies: [100, 200, 300, 400, 500]
Solution
python · try it yourself
import numpy as np

M, fs = 10, 1000
h = np.ones(M) / M
f = np.arange(0, 501, 10)
k = np.arange(M)
gain = np.abs(np.array([np.sum(h * np.exp(-2j * np.pi * fi * k / fs)) for fi in f]))
print("zero-gain frequencies:", f[gain < 1e-9].tolist())
zero-gain frequencies: [100, 200, 300, 400, 500]

The zeros sit at multiples of fs/M=100f_s / M = 100 Hz.

Exercise 7: A one-pole IIR filter

Implement y[n]=(1−a)x[n]+a y[n−1]y[n] = (1 - a)x[n] + a\,y[n-1] and report how many samples the step response needs to reach 95 % for a=0.9a = 0.9 (IIR Filters and Feedback).

python · try it yourself
import numpy as np

def one_pole(x, a):
    y = np.zeros(len(x))
    prev = 0.0
    for n in range(len(x)):
        prev = x[n]                       # TODO: the difference equation
        y[n] = prev
    return y

step = one_pole(np.ones(100), 0.9)
print("first values:", np.round(step[:4], 4).tolist())
print("samples to reach 95 %:", int(np.argmax(step >= 0.95)) + 1)
first values: [1.0, 1.0, 1.0, 1.0]
samples to reach 95 %: 1

Expected output when solved:

text
first values: [0.1, 0.19, 0.271, 0.3439]
samples to reach 95 %: 29
Solution
python · try it yourself
import numpy as np

def one_pole(x, a):
    y = np.zeros(len(x))
    prev = 0.0
    for n in range(len(x)):
        prev = (1 - a) * x[n] + a * prev
        y[n] = prev
    return y

step = one_pole(np.ones(100), 0.9)
print("first values:", np.round(step[:4], 4).tolist())
print("samples to reach 95 %:", int(np.argmax(step >= 0.95)) + 1)
first values: [0.1, 0.19, 0.271, 0.3439]
samples to reach 95 %: 29

The step response is 1−0.9n+11 - 0.9^{n+1}, which first exceeds 0.95 when 0.9n+1≤0.050.9^{n+1} \le 0.05, at the 29th sample.

Exercise 8: Blur an image in frequency

Blur a small image with a Gaussian by multiplying its 2-D FFT by e−2π2σ2(u2+v2)e^{-2\pi^2\sigma^2(u^2 + v^2)} (Filtering Images). A blur must keep the mean brightness and must not create values outside the original range.

python · try it yourself
import numpy as np

M = 32
img = np.zeros((M, M)); img[8:24, 12:20] = 1.0
u = np.fft.fftfreq(M)[:, None]
v = np.fft.fftfreq(M)[None, :]
sigma = 2.0
H = np.ones((M, M))                       # TODO: the Gaussian frequency response
out = np.real(np.fft.ifft2(np.fft.fft2(img) * H))
print(f"mean before {img.mean():.4f}, after {out.mean():.4f}")
print(f"range after: {round(float(out.min()), 4) + 0.0:.4f} .. {out.max():.4f}")
print("center row, columns 8..15:", (np.round(out[16, 8:16], 3) + 0.0).tolist())
mean before 0.1250, after 0.1250
range after: 0.0000 .. 1.0000
center row, columns 8..15: [0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0]

Expected output when solved:

text
mean before 0.1250, after 0.1250
range after: 0.0000 .. 0.9499
center row, columns 8..15: [0.038, 0.103, 0.224, 0.4, 0.6, 0.775, 0.894, 0.95]
Solution
python · try it yourself
import numpy as np

M = 32
img = np.zeros((M, M)); img[8:24, 12:20] = 1.0
u = np.fft.fftfreq(M)[:, None]
v = np.fft.fftfreq(M)[None, :]
sigma = 2.0
H = np.exp(-2 * np.pi ** 2 * sigma ** 2 * (u ** 2 + v ** 2))
out = np.real(np.fft.ifft2(np.fft.fft2(img) * H))
print(f"mean before {img.mean():.4f}, after {out.mean():.4f}")
print(f"range after: {round(float(out.min()), 4) + 0.0:.4f} .. {out.max():.4f}")
print("center row, columns 8..15:", (np.round(out[16, 8:16], 3) + 0.0).tolist())
mean before 0.1250, after 0.1250
range after: 0.0000 .. 0.9499
center row, columns 8..15: [0.038, 0.103, 0.224, 0.4, 0.6, 0.775, 0.894, 0.95]

H(0,0)=1H(0, 0) = 1 keeps the mean, and the Gaussian kernel is positive, so no ringing.

Test yourself

To get linear (not circular) convolution of lengths LL and MM from FFTs, the FFT length must be at least…

  1. max⁡(L,M)\max(L, M)
  2. L+M−1L + M - 1
  3. LML M
  4. 2L2^{L}

A 25 Hz cosine sampled for 1 s at 400 Hz has rfft magnitude at bin 25 equal to…

  1. 25
  2. 200 (that is N/2N/2) times its amplitude
  3. 1
  4. 400

Which filter has exact zeros at multiples of fs/Mf_s / M?

  1. a one-pole IIR
  2. an MM-point moving average
  3. a Gaussian blur
  4. an ideal low-pass