如何用python编写离散傅里叶变换

2024-06-16 08:36:37 发布

您现在位置:Python中文网/ 问答频道 /正文

[我在用Python编写代码时遇到问题,我真的不知道从哪里开始。DFT版本3是粘贴在下面的版本][1]

!![1] :https://i.stack.imgur.com/0J7T0.png

!![1] :https://i.stack.imgur.com/JXR4i.png


Tags: 代码https版本compngstack粘贴imgur
1条回答
网友
1楼 · 发布于 2024-06-16 08:36:37
import numpy as np
import matplotlib.pyplot as plt

%matplotlib inline

def gen_wave(freq, amp, T, shift, sr):
    time = np.arange(0, T, T/sr)
    X = amp * np.sin(2*np.pi*freq*time+shift)
    return time, X

N = 100

time, amplitude = gen_wave(2, 3, 1, 0, N)
_, amplitude2 = gen_wave(5, 2, 1, 0, N)

amplitude3 = amplitude + amplitude2

plt.figure(figsize=[15, 5])
plt.ylim([-5, 5])
plt.grid(True, which='both')
plt.plot(time, amplitude, c="b")

plt.figure(figsize=[15, 5])
plt.ylim([-5, 5])
plt.grid(True, which='both')
plt.plot(time, amplitude2, c="b")

plt.figure(figsize=[15, 5])
plt.ylim([-5, 5])
plt.grid(True, which='both')
plt.plot(time, amplitude3, c="b")


k = np.arange(0, N)
n = np.arange(0, N)

k = k.reshape((N,1))

M = 2 * np.pi * k * n / N
Xa = np.cos(M)
Xb = 1j * np.sin(M)
X = Xa - Xb
print(X.shape)
Y = X.dot(amplitude3)
print(Y.shape)

plt.plot(k, Y.real, k, Y.imag)

使用Numpy:

gabarito = np.fft.fft(amplitude3, N)
plt.plot(k, gabarito.real, k, gabarito.imag)

参考:

https://github.com/gnascimento/dft-python/blob/master/DFT.ipynb

相关问题 更多 >