I wrote the following code to compute the approximate derivative of a function using FFT:
from scipy.fftpack import fft, ifft, dct, idct, dst, idst, fftshift, fftfreq
from numpy import linspace, zeros, array, pi, sin, cos, exp
import matplotlib.pyplot as plt
N = 100
x = linspace(0,2*pi,N)
dx = x[1]-x[0]
y = sin(2*x)+cos(5*x)
dydx = 2*cos(2*x)-5*sin(5*x)
k = fftfreq(N,dx)
k = fftshift(k)
dydx1 = ifft(-k*1j*fft(y)).real
plt.plot(x,dydx,'b',label='Exact value')
plt.plot(x,dydx1,'r',label='Derivative by FFT')
plt.legend()
plt.show()
However, it is giving unexpected results, which I believe is related to the incorrect input of the wavenumbers given by the array k:
I know that different implementations of the FFT handle the wavenumbers order differently, so what am I missing here? Any ideas will be very appreciated.