Why does the DFT matrix in numpy differ from the math definition?

287 Views Asked by At

I want to understand the DFT matrix better (starting with the real part first).

  1. I'm first computing a DFT matrix by calculating the FFT of an identity matrix ( I can do sp.linalg.dft and I get the same result anyway while the former is faster )
dft_matrix = np.fft.fft(np.eye(nelems))

  1. Second, I compute, say, the 20th row of the DFT from first principles using the cosine function
fi = 20
dotprod_row_test = np.cos(2 * np.pi * fi * np.linspace(0, 1, nelems))

If I compare the resulting values in the 20th row of these two, they don't match exactly? enter image description here

BACKGROUND: I was trying to compute the FFT through different methods and I found that the higher frequencies didn't match exactly. Backtracking, I found that the DFT matrix I "compute from first principles" is not correct.

1

There are 1 best solutions below

0
On BEST ANSWER

The below is a slightly modified version of your code which may be useful. In particular, the main change is with the line:

np.cos(2*np.pi/nelems * fi * np.linspace(0, nelems-1, nelems))

The original version was not correctly stepping from 0 to nelems-1 in the argument of the cosine. In particular, the factor should be $\frac{2 \pi}{nelems}$ with the index running from 0 to nelems-1, not 0 to nelems. Please see the code below for a running implementation.

I hope this helps.

import numpy as np
import matplotlib.pyplot as plt

nelems=128

dft_matrix = np.fft.fft(np.eye(nelems))

# First principles direct calculation
fi = 120
dotprod_row_test = np.cos(2*np.pi/nelems * fi * np.linspace(0, nelems-1, nelems))

# Plot one against the other

plt.plot(dotprod_row_test,'+')
plt.plot(np.real(dft_matrix[fi]),'x')
plt.legend(['direct DFT','numpy DFT'])
plt.show()