I have an array of complex numbers (waves
), which is ordered in the same way as is returned by fft
. If I call ifft
on this array, it returns an approximation of the original samples.
I would like to implement ifft
myself in python. I've found the formula of IFFT. I implemented it, but it looks a bit different from the ifft
result. I tried to fix it by looking at the ifft source, but that is a heavily optimized version, and I was not able to find out how that works
This is what I have so far:
import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import fft
# create samples
data = np.zeros(1024)
for k in range(0, 1024):
data[k] = np.sin(k/20 * np.pi*2)
# plot original samples
#plt.plot(data)
#plt.show()
# apply FFT on samples
waves = fft(data)
# plot FFT result
#plt.plot(np.imag(waves),'r')
#plt.plot(np.real(waves),'b')
#plt.ylabel('value')
#plt.xlabel('period')
#plt.show()
#
res = np.zeros(1024)
for k in range(0, 1024):
val = 0.0
for n in range(0, len(waves)-1):
# https://dsp.stackexchange.com/a/510/25943
val += waves[n]*np.exp(-1.j * 2*np.pi * n * k / len(waves)) / len(waves)
res[k] = val.real
#np implementation
res2 = np.fft.ifft(waves)
plt.plot(data, 'b') # original
plt.plot(res,'g') # my implementation
plt.plot(res2,'y') # np implementation
plt.show()
Maybe the zero frequency term and the negative frequency terms has to be handled differently. I am not sure about that, because it is not mentioned in any description of fourier transformation