Discrete Fourier transforms with Numpy

Here is how to generate the Fourier transform of the sine wave in Eq. ([*]) using the numpy package in Python. Let's do it in interactive mode. So start by running

/usr/bin/python3

in your terminal window. Then type the commands below.



>>> import numpy as np

>>> N = 8
>>> t = np.arange(N)
>>> f = np.sin(2*np.pi * t/N)

>>> ft = np.fft.fft(f)
>>> print ft

You should get the result

[  1.14423775e-17 +0.00000000e+00j  -3.55271772e-15 -4.00000000e+00j
   1.22464680e-16 -1.11022302e-16j   3.10186197e-16 -8.88178420e-16j
   2.33486982e-16 +0.00000000e+00j  -4.04453250e-21 -8.88178420e-16j
   1.22464680e-16 +1.11022302e-16j   2.75267685e-15 +4.00000000e+00j]

This is a list of complex numbers with $j$ indicating the imaginary part. Ignore the tiny numbers that come from tiny roundoff errors. Only two nonzero values appear, namely $ft[1] = -4j$ and $ft[7] = 4j$. As explained in the Fourier transform notes, from periodicity, for a real signal, we have $ft[7] = ft[-1] = f[1]^*$.

Here is a line-by-line explanation of the script.



>>> import numpy as np

This command loads the Numpy package and sets np as the short name of the package.



>>> t = np.arange(N)

The np.arange(N) generates a vector of integers ranging from 0 to N-1. More generally, np.arange(xfirst,xlast,xincr) generates a vector with sequential values starting at xfirst, increasing by xincr and ending just before xlast. The numbers can be floats, but be careful of roundoff errors. So this command sets t equal to the one-dimensional array, i.e. the vector, $[ 0, 1, 2, 3, 4, 5, 6, 7]$.



>>> f = np.sin(2*np.pi * t/N)

This command operates on the numpy vector of integers t, component by component, calculating $\sin(2 \pi t/N)$. So f is assigned to be a vector with eight elements. Try the command print f to see the result.



>>> ft = np.fft.fft(f)

The np.fft package has a bunch of Fourier transform procedures. The one that actually does the Fourier transform is np.fft.fft. The command performs the discrete Fourier transform on f and assigns the result to ft. The Fourier components ft[m] belong to the discrete frequencies $\nu_m = 2\pi m/N$.