Implementing Fourier Transforms
A look at how to implement Fourier Transforms on a computer.
02 June 2017
Discrete Fourier Transforms
Analytically, the Fourier Transform is used for continuous functions. However, when we want to implement things on a computer, discreteness naturally creeps in.
Here we do the following:
- Generate a discretely sampled signal.
- Define a funcion to perform the DFT.
- Regenerate the signal as verification.
- Alter the DFT and see the result.
Generating the signal
First we generate a signal. For discrete fourier transforms,the signal is sampled at a finite number of points after regular intervals, which we attribute to the response time of the measuring apparatus. The number of samples is a power of 2 for reasons that will be clear later when we discuss the Fast Fourier Transform.
Now we create the function that will perform the discrete fourier transform.
A look into the mathematical treatment of the DFT should convince you that this is the way to go.
Taking the Discrete Fourier Transform
Regenerating the signal
Regenerating the signal shouldn’t be too difficult as it just involves the inverse of the matrix. We choose only the real part as the signal was initially also purely real.
This verifies that the DFT we obtained was correct.
Editing the fourier transform
Let’s play around with this now. It’s obvious from the above plot that the major contributors are the first and last elements in the fourier transformed coefficients. So let’s and see how that changes the signal
Regenerating the modified signal
Notice that the amplitude of the regenerated signal is a lot less than the original signal. This is attributed to the fact that when you take away the contributions due to certian frequencies, a lesser number of harmonics generate the new signal and this signal has a lower amplitude.
Fast Fourier Transform
Discrete Fourier Transforms are great but they are also horribly slow, with a time complexity of $ \mathcal{O}(n^2) $. For matrices that are large (i.e. a high sampling rate), this means it takes practically forever to perform a DFT. However, Given the nature of the matrix used to obtain the DFT, an optimization is possible. Let’s use the same signal as before.
We intend to use recursion as our friend in this one. So we’ll define a function which implements this recursion. Why we define the function this particular way will be clear if you look at the mathematical treatment for the optimization of the FFT.
Taking the Fast Fourier Transform
Time Comparison
Discrete Fourier Transform
1 loop, best of 3: 2.15 s per loop
Fast Fourier Transform
1 loop, best of 3: 104 ms per loop
The FFT is obviously faster than the DFT. It is still slower than the library functions as those are further optimized.