📚 The CoCalc Library - books, templates and other resources
License: OTHER
""" Code example from Complexity and Computation, a book about1exploring complexity science with Python. Available free from23http://greenteapress.com/complexity45Copyright 2011 Allen B. Downey.6Distributed under the GNU General Public License at gnu.org/licenses/gpl.html.7"""89# importing cmath makes exp and other math functions handle10# complex numbers11from cmath import *1213import numpy14import matplotlib.pyplot as pyplot151617def fft(h):18"""Computes the discrete Fourier transform of the sequence h.19Assumes that len(h) is a power of two.20"""21N = len(h)2223# the Fourier transform of a single value is itself24if N == 1: return h2526# recursively compute the FFT of the even and odd values27He = fft(h[0:N:2])28Ho = fft(h[1:N:2])2930# merge the half-FFTs31i = complex(0,1)32W = exp(2*pi*i/N)33ws = [pow(W,k) for k in range(N)]34H = [e + w*o for w, e, o in zip(ws, He+He, Ho+Ho)]35return H3637def psd(H, N):38p = [Hn * Hn.conjugate() for Hn in H]39freqs = range(N/2 + 1)40p = [p[f].real for f in freqs]41return freqs, p4243def main(script, use_numpy=False):44# make a signal with two sine components, f=6 and f=1245N = 12846t = [1.0*n/N for n in range(N)]47h = [sin(2*pi*6*tn) + sin(2*pi*12*tn) for tn in t]4849# compute the Fourier transform50if use_numpy:51H = numpy.fft.fft(h)52else:53H = fft(h)5455# compute the power spectral density56freqs, p = psd(H, N)5758# plot the real part59pyplot.bar(freqs, p)60pyplot.xlabel('frequency')61pyplot.ylabel('amplitude')62pyplot.show()6364# estimate the power spectral density by Welches average65# periodogram method using the psd function provided by pylab.66pyplot.show()6768if __name__ == '__main__':69import sys70main(*sys.argv)71727374