Skip to content

Instantly share code, notes, and snippets.

@JustinSDK
Created May 18, 2021 03:11
Show Gist options
  • Save JustinSDK/05ca504b3f628cbac132cbce4632df83 to your computer and use it in GitHub Desktop.
Save JustinSDK/05ca504b3f628cbac132cbce4632df83 to your computer and use it in GitHub Desktop.
NumPy 一維傅立葉轉換
import numpy as np
import matplotlib.pyplot as plt
t = 2 # 取樣時間
sample_rate = 800 # 取樣率,每秒取幾個樣本
def signal(t, sample_rate):
f = 10
x = np.linspace(0, t, int(t * sample_rate), endpoint = False)
return (np.sin(f * 2 * np.pi * x) +
np.sin(3 * f * 2 * np.pi * x) / 2 +
np.sin(4 * f * 2 * np.pi * x) / 5 +
np.sin(8 * f * 2 * np.pi * x) / 3)
samples = signal(t, sample_rate)
sp = np.fft.fft(samples)
freq = np.fft.fftfreq(samples.size, d = 1 / sample_rate)
amp = np.abs(sp)
ax = plt.gca()
ax.stem(freq, amp / np.max(amp))
ax.set_xlim([np.min(freq), np.max(freq)])
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment