## FFT in Python:get the correct frequency

July 5, 2011 by micropore

It happens that one uses the standard FFT routine of Python (or better to say Numy.fft) without knowing how can it return the proper frequency. In the following simple example, I show two methods to get it working correctly.

import numpy as np

from scipy import fft

import numpy, matplotlib, scipy.fftpack

from pylab import plt

num = 256

norm = 2.0 / float(num) # normalization factor

sample = 4.

time = np.arange(num) / sample

dx = time[1] – time[0]

f1 = .88

a1 = 2.

kont = a1 * np.sin(2 * np.pi * f1 * time) # the input

g = fft(kont) * norm

#————————————————–

#– Method 1

freq = np.fft.fftshift(np.fft.fftfreq(kont.shape[-1]))/dx

plt.plot(freq, abs(np.fft.fftshift(g)))

#————————————————–

#– Method 2

#freq = np.fft.fftshift(np.fft.fftfreq(kont.shape[-1]))/dx

#plt.plot(freq, abs(np.fft.fftshift(g)))

#————————————————–

plt.axvline(x=f1, linewidth=2, color=’r’)

plt.xlim(xmin=1e-6) # to have only positive frequencies

plt.xlabel(r’Frequency’)

plt.ylabel(r’Normalized amplitude’)

plt.title(‘method 1’)

plt.show()

If you have trouble due to mismatch of some characters, try the PDF version.

### Like this:

Like Loading...

*Related*

on July 26, 2012 at 9:20 pm |calvinI would like to ask some questions about using fft. Can you send me an e-mail so I can send you the info?

on August 7, 2012 at 10:20 pm |microporeYou got an answer by e-mail.