I have to calculate numerically the 2nd derivative of a Gaussian function:
I've read every question on this topic here, but can't come to a good result. I've chosen NumPy as my tool of choice.
The instructions from our professor :
- Get an
xarray of sizeN = 128with stepdx = 1. So,-64, -63, ..., 62, 63. Calculatef(x) - Perform FFT on
f(x)and receive the transformed arrayf_m. - Multiply
f_mby, where
is imaginary unit,
is degree of derivation and
- Perform an inverse FFT to receive the derivative.
- In some FFT implementations you may have to scale by
1/n(but that's the smallest problem now)
Now here is my code, as simple as possible.
import numpy as np
# Set some parameters
n = 128
dx = 1
a = 0.001
# Create x, calculate f(x) and its FFT
x = np.arange(-n/2, n/2) * dx
psi = np.exp(-a * x * x)
f_m = np.fft.fft(psi)
# k_m creation according to professor (point 3. in my instruction)
k_m = np.arange(-n/2, n/2, dtype=float)
k_m[:int(n / 2)] = (2 * np.pi * k_m[:int(n / 2)]) / (n * dx)
k_m[int(n / 2):] = (2 * np.pi * (k_m[int(n / 2):] - n)) / (n * dx)
# Multiply f_m by (j * k_m)^q. For q=2, this is -k_m^2
f_m *= -k_m * k_m
# Inverse FFT on the result to get the second derivative and scale by 1 / n
f_m = np.fft.ifft(f_m) / n
One thing that I can't get is the result still has imaginary part and so something is not right. Can anybody help there?
EDIT: Cris Luengo's answer works.
