Alexis R Devitre
Alexis R Devitre

Reputation: 298

Numerical differentiation via numpy FFT

I am learning how to use numpy for Fast Fourier transform differentiation. In the code below, I create a simple sine function and try to get the cosine. The result is shown in the image, there seems to be a normalization factor which I do not understand despite reading the documentation and which prevents me from getting the correct results.

Can you tell me how to get rid of the normalization factor or if I am failing in a different way? Also please explain why the Nyquist frequency is not present when the array is length is odd.

x = np.arange(start=-300., stop=300.1, step=0.1)
sine = np.sin(x)

Y = np.fft.rfft(a=sine, n=len(x))
L = 2.*np.pi #period
N = size(Y)

for k, y in enumerate(Y):
    Y[k] *= 2.*np.pi*1j*k/L

# if N is even, the last entry is the Nyquist frequency.
#if N is odd, there it is not there.
if N%2 == 0:
    Y[-1] *= 0.

cosine = np.fft.irfft(a=Y, n=len(x))

Code output

Upvotes: 1

Views: 1537

Answers (1)

dkato
dkato

Reputation: 895

Can you tell me how to get rid of the normalization factor or if I am failing in a different way?

Add np.exp() for the term 2.*np.pi*1j*k/L. This term seems to be the amount of phase rotation, so their norm should be 1.

for k in range(N):
    Y[k] *= np.exp(2.*np.pi*1j*k/L)

Also please explain why the Nyquist frequency is not present when the array is length is odd.

It's a nature of discrete Fourier transformation. Briefly, when the number of sampling points N is odd, there is no integer that equals to N/2.

Upvotes: 3

Related Questions