为什么numpy的fft的每一秒系数都应该是倒数?

时间:2018-08-02 03:26:35

标签: python numpy fft

这是我尝试使用numpy获取单位脉冲的DFT的方式(该图显示了单位脉冲):

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np

def plot_complex(space, arr):
    plt.figure()
    plt.plot(space, arr.real, label="real")
    plt.plot(space, arr.imag, label="imag")
    plt.legend(loc='upper left')

f = lambda x: 1 if abs(x) < 0.5 else 0
lo = -10
hi = 10
num_samples = 1000
sample_freq = num_samples/(hi-lo)
linspace = np.linspace(lo, hi, num_samples)
array = np.vectorize(f)(linspace)

coeff = np.fft.fft(array, num_samples)

# we need to shift the coefficients because otherwise negative frequencies are in the right half of the array
coeff_shifted = np.fft.fftshift(coeff)

plot_complex(linspace, array)
plt.title("The unit pulse")

Unit pulse plot

这似乎是可行的,因为使用逆fft可以恢复原始单位脉冲:

icoeff = np.fft.ifft(coeff)

plot_complex(linspace, icoeff)
plt.title("The recovered signal")

Recovered pulse plot

但是,当看信号时,它看起来不像我从看连续傅立叶变换时所期望的sinc函数:

freqspace = np.vectorize(lambda x: x * sample_freq)(np.fft.fftshift(np.fft.fftfreq(1000)))
plot_complex(freqspace, coeff_shifted)
plt.title("DFT coefficients")

plot_complex(freqspace[450:550], coeff_shifted[450:550])
plt.title("Zoomed in")

Plot of the coefficients

Zoomed in plot

每秒钟系数乘以-1只能看起来像sinc函数:

# multiplies every second number in the array by -1
def flip_seconds(coeff):
    return np.array([(1 if i%2 == 0 else -1) * s for (i,s) in enumerate(coeff)])

plot_complex(freqspace, flip_seconds(coeff_shifted))

Plot of the altered coefficients

这是为什么?

1 个答案:

答案 0 :(得分:1)

这有点麻烦,也许其他人想用数学方法将其冲洗掉:),但基本上,您已经将“脉冲域”的窗口设置为[-X / 2,X / 2],而fft希望它窗口[0,X]。区别在于“脉冲域”中的偏移,这导致频域中的相移。因为您已将窗口恰好偏移了一半,所以相移恰好是exp(-pi * f * i / sampling_freq)(或类似的东西),因此,每隔一个项乘以exp(-pi * i),它就会显示出来。您可以在应用fft之前通过移动“脉冲空间”来解决此问题。

import matplotlib.pyplot as plt
import numpy as np

def plot_complex(space, arr):
    plt.figure()
    plt.plot(space, arr.real, label="real")
    plt.plot(space, arr.imag, label="imag")
    plt.legend(loc='upper left')

lo = -10
hi = 10
num_samples = 1000
sample_freq = num_samples/(hi-lo)
linspace = np.linspace(lo, hi, num_samples)
array = abs(linspace) < .5
array_shifted = np.fft.fftshift(array)

coeff = np.fft.fft(array_shifted, num_samples)

# we need to shift the coefficients because otherwise negative frequencies are in the right half of the array
coeff_shifted = np.fft.fftshift(coeff)

plot_complex(linspace, array_shifted)
plt.title("The unit pulse (shifted)")

icoeff = np.ftt.ifftshift(np.fft.ifft(coeff))

plot_complex(linspace, icoeff)
plt.title("The recovered signal")

freqspace = np.fft.fftshift(np.fft.fftfreq(1000)) * sample_freq
plot_complex(freqspace, coeff_shifted)
plt.title("DFT coefficients")

plot_complex(freqspace[450:550], coeff_shifted[450:550])
plt.title("Zoomed in")


def flip_seconds(coeff):
    return np.array([(1 if i%2 == 0 else -1) * s for (i,s) in enumerate(coeff)])

plot_complex(freqspace, flip_seconds(coeff_shifted))
plt.show()