Implementing DFT
Copyright 2019 Allen Downey, MIT License
Let's start with a known result. The DFT of an impulse is a constant.
Literal translation
The usual way the DFT is expressed is as a summation. Following the notation on Wikipedia:
Here's a straightforward translation of that formula into Python.
Wrapping this code in a function makes the roles of k
and n
clearer, where k
is a free parameter and n
is the bound variable of the summation.
Of course, we usually we compute all at once, so we can wrap this function in another function:
And the results check out.
DFT as a matrix operation
It is also common to express the DFT as a matrix operation:
with
and
If we recognize the construction of as an outer product, we can use np.outer
to compute it.
Here's an implementation of DFT using outer product to construct the DFT matrix, and dot product to compute the DFT.
And the results check out.
Implementing FFT
Finally, we can implement the FFT by translating from math notation:
Where is the FFT of the even elements of and is the DFT of the odd elements of .
Here's what that looks like in code.
The length of and is half the length of , so I use np.tile
to double them up.
And the results check out.