Menu

[r3313]: / trunk / py4science / book / examples / fft_demo.py  Maximize  Restore  History

Download this file

45 lines (36 with data), 860 Bytes

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from pylab import *
rc('lines', linewidth=2)
dx = 0.001
x = nx.arange(0.0, 1.0, 0.001)
#s = nx.where(x<0.5, 2*x, 2*(1.-x))
s = sin(2*4*pi*x*x)
F = fft(s)
nfreq = len(s)/2+1
freqs = linspace(0, 1/(2*dx), nfreq) # the freq vector
F = F[:nfreq] # extract positive frequencies
magnitude = nx.absolute(F)/len(s)
phase = nx.arctan2(F.imag,F.real)
# make the BODE plot
figure()
subplot(211)
plot(freqs, magnitude)
xlim(0,20)
grid()
ylabel('Amplitude')
title('Bode plot')
subplot(212)
plot(freqs, phase)
xlim(0,20)
grid()
ylabel('Phase')
# now do the reconstuction
def component(i):
# scale by 2 because we are exluding negative freqs
if i==0: scale = 1
else: scale =2
return scale*magnitude[i]*cos(2*pi*freqs[i]*x + phase[i])
tot = component(0)
for i in range(1,10): tot += component(i)
figure()
plot(x, tot, 'r--', x, s, 'b-', lw=2)
show()
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.