I am trying to utilize Numpy's fft function, however when I give the function a simple gausian function the fft of that gausian function is not a gausian, its close but its halved so that each half is at either end of the x axis.
The Gaussian function I'm calculating is y = exp(-x^2)
Here is my code:
from cmath import *
from numpy import multiply
from numpy.fft import fft
from pylab import plot, show
""" Basically the standard range() function but with float support """
def frange (min_value, max_value, step):
value = float(min_value)
array = []
while value < float(max_value):
array.append(value)
value += float(step)
return array
N = 256.0 # number of steps
y = []
x = frange(-5, 5, 10/N)
# fill array y with values of the Gaussian function
cache = -multiply(x, x)
for i in cache: y.append(exp(i))
Y = fft(y)
# plot the fft of the gausian function
plot(x, abs(Y))
show()
The result is not quite right, cause the FFT of a Gaussian function should be a Gaussian function itself...
The Fourier transform of a Gaussian function of x is a Gaussian function of k. The standard deviation of is inversely proportional to the standard deviation of . If the function is an even function, its Fourier transform can be a Fourier cosine transform: (11.39)
gauss() gauss() is an inbuilt method of the random module. It is used to return a random floating point number with gaussian distribution. Example 2: We can generate the number multiple times and plot a graph to observe the gaussian distribution.
fft. fftfreq. Return the Discrete Fourier Transform sample frequencies.
np.fft.fft
returns a result in so-called "standard order": (from the docs)
If
A = fft(a, n)
, thenA[0]
contains the zero-frequency term (the mean of the signal), which is always purely real for real inputs. ThenA[1:n/2]
contains the positive-frequency terms, andA[n/2+1:]
contains the negative-frequency terms, in order of decreasingly negative frequency.
The function np.fft.fftshift
rearranges the result into the order most humans expect (and which is good for plotting):
The routine
np.fft.fftshift(A)
shifts transforms and their frequencies to put the zero-frequency components in the middle...
So using np.fft.fftshift
:
import matplotlib.pyplot as plt
import numpy as np
N = 128
x = np.arange(-5, 5, 10./(2 * N))
y = np.exp(-x * x)
y_fft = np.fft.fftshift(np.abs(np.fft.fft(y))) / np.sqrt(len(y))
plt.plot(x,y)
plt.plot(x,y_fft)
plt.show()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With