How to explain the difference between the FFT result and the analytical Fourier transform?

130 Views Asked by At

I am learning FFT by scipy's 'fft'. And now I have the rectangle function as shown below.

enter image description here

Its analytical Fourier transform is

enter image description here

and its squared absolute value is

enter image description here

For performing FFT, I sampled the f(x) in the range 0 <= x <= 10. And the number of samples N is 2**18, such that sample interval delt is 10.0/(2**18-1). The FFT snippet is shown below.

import numpy as np
from scipy.fft import fft, ifft

# Define the analytical form of the Fourier transform
def fk(k):
    value = 2*(1-np.cos(k))/(k**2 + 0.0001)   # '0.0001' is used to aovid the singularity
    return value


N = 2**18
delt = 10.0/(N-1)                              # sample interval
y_time = np.loadtxt("data_input_b_262144.dat") # read-in the sample points
y_freq = fft(y_time)                           # perform fft
y_freq_square =(delt**2)* np.abs(y_freq)**2   # The squared absolute value of magnitude of frequencce component

# Positive frequency
k = np.linspace(0.0, 1.0/(2.0*delt), int(N/2))

# Plot the spectrum
plt.plot(k, y_freq_square[0:int(N/2)],
         k,fk(k))
plt.gca().set_xlim(0.1, np.amax(k))
plt.gca().set_ylim(0.001, 1.2)
plt.gca().set_xscale('log')
plt.gca().set_yscale('log')
plt.xlabel('k')
plt.ylabel('$\hat f(k)$')
plt.legend(['fft result', 'analytical fourier transform'])
plt.savefig('rectangle_fft.png')

The figure is

enter image description here

So my question is that why does there exist differences between these two results? In principle, they are supposed to be the same curve in the figure.