## show how fourier analysis allows you to reconstruct a square wave ## run this in the following manner: # $ python four-sq.py > four-sq.out # $ gnuplot # plot [] [-1.2:1.2] 'four-sq.out' using 2 with lines # replot 'four-sq.out' using 3 with lines # replot 'four-sq.out' using 4 with lines # replot 'four-sq.out' using 5 with lines # replot 'four-sq.out' using 6 with lines # replot 'four-sq.out' using 7 with lines # replot 'four-sq.out' using 8 with lines # pause -1 ## or just do: # $ python four-sq.py > four-sq.out # $ gnuplot four-sq.gp import math def __main__(): for i in range(100): t = i*2*math.pi/100.0 print t, ' ', sq(t), ' ', for j in range(5): print ' ', sq_four(t, 2*j+1), print ## square wave from 0 to 2*PI def sq(t): if t <= math.pi: return 1 else: return -1 ## square wave reconstructed with fourier series def sq_four(t, n): val = 0 for k in range(n+1): if k % 2 == 1: val += (4.0/(math.pi*k)) * math.sin(t*k) return val __main__()