Last active
August 29, 2015 14:25
-
-
Save sourceperl/8b782b2a7ce1beec5dc9 to your computer and use it in GitHub Desktop.
FFT sample in Python2.7
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# build a sample array of discrete value | |
# compute the FFT and display spectral graphic | |
from scipy.fftpack import fft | |
import matplotlib.pyplot as plt | |
import numpy as np | |
import random as rd | |
# number of samples | |
Ns = 10000 | |
# second between 2 samples | |
Ts = 0.002 # 2 ms | |
# N samples, every sample is time value (in s) | |
# 0 -> t_max with Ns items | |
t_max = Ns * Ts | |
t_samples = np.linspace(0.0, t_max, Ns) | |
# sum of : | |
# 50 Hz sin 30% | |
# 80 Hz sin 100% | |
# 100 Hz sin 50% | |
# 200 Hz sin 100% | |
y_samples = 0.3 * np.sin(50.0 * 2.0 * np.pi * t_samples) \ | |
+ 1.0 * np.sin(80.0 * 2.0 * np.pi * t_samples) \ | |
+ 0.5 * np.sin(100.0 * 2.0 * np.pi * t_samples) \ | |
+ 1.0 * np.sin(200.0 * 2.0 * np.pi * t_samples) | |
# add some noise (Ns sample value between [-1.0 and 1.0]) | |
s_noise = (np.random.rand(Ns)-0.5)*2 | |
y_samples += s_noise | |
# compute FFT | |
y_freq = fft(y_samples) | |
# frequency domain max freq is (1.0/periods), periods | |
# 0 -> f_max with Ns/2 steps, xf in Hz | |
f_max = 1.0/(2.0*Ts) | |
xf = np.linspace(0.0, f_max, Ns/2) | |
# yf between 0.0 and 1.0 for every xf step | |
yf = 1.0/(Ns/2.0) * np.abs(y_freq[0:Ns/2]) | |
# build spectral graphic | |
plt.plot(xf, yf) | |
plt.grid() | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment