I am porting some C++ code to Python. The C++ code performs the DFT and IDFT using the FFTW library, whereas in Python, I've opted to use numpys implementation for the time being.
I have come across some strange behaviour. It seems that the forward transform is computed identically in both cases, but the inverse transform produces different results!
the relevant C++ code:
int N = 12;
auto fft_coefficients = new complex<double>[N] {
5.45, -0.54, 1.81, 1.49, 0.48, 3.98, 0.93, 3.98, 0.48, 1.49, 1.81, -0.54 };
fftw_plan plan_ifft = fftw_plan_dft_1d(
N, reinterpret_cast<fftw_complex *>(fft_coefficients),
reinterpret_cast<fftw_complex *>(fft_coefficients), FFTW_BACKWARD,
FFTW_ESTIMATE);
fftw_execute(plan_ifft);
// Results in
// [20.82, -1.98, 4.55, 1.86, 3.63, 13.68, 1.10, 13.68,, 3.63, 1.86, 4.55, -1.98]
However, when I run the same code in Python, but using numpy, I get the following:
np.fft.ifft(np.array([5.45, -0.54, 1.81, 1.49, 0.48, 3.98, 0.93, 3.98, 0.48, 1.49,
1.81, -0.54], dtype=np.complex64)).real
# array([ 1.73, -0.16, 0.38, 0.15, 0.3 , 1.14, 0.09, 1.14, 0.3 ,
# 0.15, 0.38, -0.16])
I thought I may need to add the norm='ortho'
option to numpy to do unitary IDFT, but that doesn't make them match up either.
I don't understand how these two libraries could be computing the inverse DFT differently, and not just by a little bit, drastically different results.
FFTW claims: "FFTW computes an unnormalized DFT"
That is, for ifft they compute
However, as stated on for instance wikipedia, the inverse DFT is defined as
So the fftw output is in fact incorrect and needs to be scaled.