It is used in data analysis, audio and visual data compression, and signal denoising. It is also used in calculating derivatives which in turn is used to solve PDEs and other scientific computing. Before diving into the details of the FFT, we shall take a look at Discrete Fourier Transform (DFT) as the FFT is just a faster way to calculate DFT.
We know that Fourier transform tries to approximate a continuous function into the sum of sines and cosines. But computers work with discrete data. For example, a continuous signal will be stored in a computer by taking samples from the signal at some sampling rate. These samples form the discrete data that computers work with. These samples can also be approximated as a sum of sines and cosines. DFT returns a series of transforms. It can be calculated by the following equation:
Here,
This is called fundamental frequency for
The inverse of DFT is pretty similar to the equation above. It is given as:
We are multiplying
The big matrix in the middle is just a simplified version of the equations for every
For
As mentioned earlier, FFT is just a fast way of calculating DFT. There are many implementations for this, but the most used one is the Cooley Tukey algorithm. FFT allows us to compute DFT in
For simplicity, we assume that
This divide-and-conquer algorithm recursively divides the matrix multiplication in half until it reaches the base case, which is
FFT(x):n = length(x)if n = 1return xx_e = [x_0, x_2, ..., x_n-2]x_o = [x_1, x_3, ..., x_n-1]y_e = FFT(x_e)y_o = FFT(x_o)ω_n = exp^(2*pi*i*n)y = initialize an array on n elementsfor j = 0:n/2 - 1y[j] = y_e[j] + ω_n^j * y_o[j]y[j + n/2] = y_e[j] + ω_n^(j + n/2) * y_e[j]return y
The algorithm divides the vector into two smaller vectors. One contains all the elements from the even index and the other from the odd. This division is continued until every element reaches the base case.
The real magic happens in the combining of these results. In lines 17 and 18, we are using the periodic property of sinusoids which simplifies our calculations.
Note: Even if
is not in powers of two, we can pad zeros for the calculations.
Implementing this algorithm from scratch can be tedious and prone to errors. Luckily, SciPy provides a good implementation for its calculation.
import numpy as npfrom scipy.fft import fft, ifftx = np.array([3, -9, 6, -1, -2, 4, 2])y = fft(x)x_ = ifft(y)print("Original values:", x)print("-"*75)print("DFT:", y)print("-"*75)print("inverse of DFT:", x_)
Line 5: We create a NumPy array which will be the discrete values of which we would like to calculate FFT.
Line 7: Here, we used the fft()
function to calculate the FFT. One required parameter is the x
which is an array-like object. It can also have complex values.
Line 8: The ifft()
function implements the inverse of FFT. It has the same required parameter.
Free Resources