TExcelTAD
Home › Fourier Analysis & Signals › The FFT in NumPy

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 0…N/20 \ldots N/2 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
python · try it yourself
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 NN the bin N/2N/2 is the Nyquist frequency; fftfreq labels it −fs/2-f_s/2, rfftfreq labels it +fs/2+f_s/2. Both are the same bin.

From bins to amplitudes

For a real signal with a sinusoid exactly on bin kk (0<k<N/20 < k < N/2), the amplitude is 2∣X[k]∣/N2\lvert X[k] \rvert / N; the DC and Nyquist bins use ∣X[k]∣/N\lvert X[k] \rvert / N. A one-sided amplitude spectrum helper:

python · try it yourself
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 Acos⁡(2πft+φ)A\cos(2\pi f t + \varphi) exactly on bin kk, np.angle(X[k]) is φ\varphi:

python · try it yourself
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.fft has the same interface plus workers= for threads and dct/dst; it is preferred for heavy use. See SciPy FFT.
  • NumPy 2 computes float32 input in single precision; older versions always used double. Pass float64 arrays 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 ⌊N/2⌋+1\lfloor N/2 \rfloor + 1 bins: 501 for N=1001N = 1001. With odd NN there is no Nyquist bin.

Exercise 2: Bin of a frequency

At fs=8000f_s = 8000 Hz and N=1024N = 1024, which bin contains 1000 Hz?

Answer

Bin 128.

Solution

k=fN/fs=1000⋅1024/8000=128k = f N / f_s = 1000 \cdot 1024 / 8000 = 128.

Exercise 3: Dominant frequency (code)

Write peak_frequency(x, fs) returning the frequency of the largest non-DC bin, and test it on sin⁡(2π⋅37t)\sin(2\pi \cdot 37 t) sampled at 500 Hz for 1 second.

Answer

37.0 Hz.

Solution
python · try it yourself
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?

  1. at the start
  2. in the second half of the array
  3. they are dropped
  4. in a separate array

The amplitude of a real sinusoid on bin kk (not DC) is…

  1. ∣X[k]∣|X[k]|
  2. 2∣X[k]∣/N2|X[k]|/N
  3. ∣X[k]∣/N|X[k]|/N
  4. ∣X[k]∣2|X[k]|^2

Which function gives the frequencies of rfft bins?

  1. np.fft.fftfreq
  2. np.fft.rfftfreq
  3. np.fft.fftshift
  4. np.linspace