Skip to content

Instantly share code, notes, and snippets.

@mvaz
Forked from endolith/Perfect_FFT.py
Created February 27, 2013 21:08
Show Gist options
  • Save mvaz/5051730 to your computer and use it in GitHub Desktop.
Save mvaz/5051730 to your computer and use it in GitHub Desktop.

This is just a note to self, for remembering the little details about NumPy's FFT implementation.

  • To get the FFT bins to line up perfectly, without any "skirts" or spectral leakage, you need to make a perfect cycle, where the next sample after this chunk lines up with the first. (In other words, the first and last samples should not be the same.)
  • To get a sinusoid of amplitude 1 to produce 2 complex exponentials of amplitude 0.5, you need to divide the fft() results by the number of samples.
  • The fft() output is from 0 Hz to Nyquist frequency to sampling rate. To plot the spectrum from negative Nyquist frequency to positive Nyquist frequency, with 0 in the center, either use fftshift() on the ampl variable, or use fftfreq() to generate a horizontal axis for plotting.
from __future__ import division
from pylab import *
# Sampling rate
fs = 128 # Hz
# Time is from 0 to 1 seconds, but leave off the endpoint, so that 1.0 seconds is the first sample of the *next* chunk
length = 1 # second
N = fs * length
t = linspace(0, length, num = N, endpoint = False)
# Generate a sinusoid at frequency f
f = 10 # Hz
a = cos(2 * pi * f * t)
# Use FFT to get the amplitude of the spectrum
ampl = 1/N * abs(fft(a))
# FFT frequency bins
freqs = fftfreq(N, 1/fs)
# Plot unshifted data on a shifted axis
stem(freqs, ampl)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment