Lesson 8 of 15
Power Spectrum
Power Spectrum
The power spectrum shows how the power of a signal is distributed across frequencies. It is computed from the DFT magnitudes:
where is the number of samples. This normalization makes the power independent of signal length.
Frequency Resolution
For a signal sampled at Hz with samples, each bin corresponds to:
Bin 0 () is the DC component (zero frequency). The highest meaningful frequency is at (the Nyquist frequency).
Dominant Frequency
The dominant frequency is the bin with the highest power, excluding DC (bin 0). For a signal with a strong sinusoidal component, this reveals the fundamental frequency.
Example
A 4-sample signal (impulse) has flat power spectrum:
A DC signal has all power at :
Your Task
Implement:
power_spectrum(x)— returnsdominant_frequency(x, fs)— returns where maximizes for
import math
def dft(x):
N = len(x)
X = []
for k in range(N):
val = 0 + 0j
for n in range(N):
val += x[n] * math.e ** (-2j * math.pi * k * n / N)
X.append(val)
return X
def power_spectrum(x):
N = len(x)
X = dft(x)
return [abs(v)**2 / N for v in X]
def dominant_frequency(x, fs):
N = len(x)
ps = power_spectrum(x)
start = 1 if N > 1 else 0
best_k = start + ps[start:].index(max(ps[start:]))
return best_k * fs / NPython runtime loading...
Loading...
Click "Run" to execute your code.