The FFT in NumPy
np.fft is where theory meets practice. The functions are simple, but the output layout (zero frequency first, negative frequencies at the end), the scaling, and the real-input variants trip up almost everyone once. This lesson is the practical reference, with the conversions from bins to physical amplitudes that later lessons use.
The functions
| Function | Use |
|---|---|
fft(x, n=None), ifft(X) |
complex DFT and inverse, length n (pads or truncates) |
rfft(x), irfft(X, n) |
real input: returns bins only |
fftfreq(N, d), rfftfreq(N, d) |
frequency of each bin for sample spacing d |
fftshift, ifftshift |
move zero frequency to the middle (for display) |
fft2, rfft2, fftn |
2-D and N-D transforms |
import numpy as np
N, fs = 8, 8.0
print("fftfreq :", np.fft.fftfreq(N, 1 / fs).tolist())
print("shifted :", np.fft.fftshift(np.fft.fftfreq(N, 1 / fs)).tolist())
print("rfftfreq:", np.fft.rfftfreq(N, 1 / fs).tolist())
x = np.arange(N, dtype=float)
print("len fft:", len(np.fft.fft(x)), " len rfft:", len(np.fft.rfft(x)))
print("irfft(rfft(x)) == x:", np.allclose(np.fft.irfft(np.fft.rfft(x), n=N), x))fftfreq : [0.0, 1.0, 2.0, 3.0, -4.0, -3.0, -2.0, -1.0]
shifted : [-4.0, -3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0]
rfftfreq: [0.0, 1.0, 2.0, 3.0, 4.0]
len fft: 8 len rfft: 5
irfft(rfft(x)) == x: True
For even the bin is the Nyquist frequency; fftfreq labels it , rfftfreq labels it . Both are the same bin.
From bins to amplitudes
For a real signal with a sinusoid exactly on bin (), the amplitude is ; the DC and Nyquist bins use . A one-sided amplitude spectrum helper:
import numpy as np
def amplitude_spectrum(x, fs):
N = len(x)
X = np.fft.rfft(x)
A = np.abs(X) / N
A[1:(N + 1) // 2] *= 2 # double all bins except DC (and Nyquist when N is even)
return np.fft.rfftfreq(N, 1 / fs), A
fs = 1000
t = np.arange(0, 0.5, 1 / fs) # N = 500, bin spacing 2 Hz
x = 1.5 + 3 * np.cos(2 * np.pi * 50 * t) + 0.7 * np.sin(2 * np.pi * 120 * t + 1)
f, A = amplitude_spectrum(x, fs)
for fi, a in zip(f, A):
if a > 1e-6:
print(f"{fi:6.1f} Hz: amplitude {a:.4f}") 0.0 Hz: amplitude 1.5000
50.0 Hz: amplitude 3.0000
120.0 Hz: amplitude 0.7000
Phase and timing
The phase of a bin tells where the oscillation starts. For exactly on bin , np.angle(X[k]) is :
import numpy as np
fs, N = 100, 100
t = np.arange(N) / fs
for phi in (0.0, 0.5, -1.2):
X = np.fft.rfft(2 * np.cos(2 * np.pi * 7 * t + phi))
print(f"true phase {phi:+.2f}: angle(X[7]) = {round(float(np.angle(X[7])), 4) + 0.0:+.4f}")true phase +0.00: angle(X[7]) = +0.0000
true phase +0.50: angle(X[7]) = +0.5000
true phase -1.20: angle(X[7]) = -1.2000
When the frequency is not exactly on a bin, both amplitude and phase readings are biased by leakage; windows and interpolation fix that (Window Functions).
In software
scipy.ffthas the same interface plusworkers=for threads anddct/dst; it is preferred for heavy use. See SciPy FFT.- NumPy 2 computes
float32input in single precision; older versions always used double. Passfloat64arrays when precision matters.
Exercises
Exercise 1: Output length
What does np.fft.rfft return for a real signal of length 1001?
Answer
501 complex values.
Solution
rfft returns bins: 501 for . With odd there is no Nyquist bin.
Exercise 2: Bin of a frequency
At Hz and , which bin contains 1000 Hz?
Answer
Bin 128.
Solution
.
Exercise 3: Dominant frequency (code)
Write peak_frequency(x, fs) returning the frequency of the largest non-DC bin, and test it on sampled at 500 Hz for 1 second.
Answer
37.0 Hz.
Solution
import numpy as np
def peak_frequency(x, fs):
A = np.abs(np.fft.rfft(x))
A[0] = 0
return float(np.fft.rfftfreq(len(x), 1 / fs)[np.argmax(A)])
t = np.arange(0, 1, 1 / 500)
print(peak_frequency(np.sin(2 * np.pi * 37 * t), 500))37.0
Test yourself
Where does np.fft.fft put negative frequencies?
- at the start
- in the second half of the array
- they are dropped
- in a separate array
The amplitude of a real sinusoid on bin (not DC) is…
Which function gives the frequencies of rfft bins?
- np.fft.fftfreq
- np.fft.rfftfreq
- np.fft.fftshift
- np.linspace