# Compute the Discrete Fourier Transform of the sequence of numbers l
def dft(l):
N=len(l)
output=[]
k=0
while k<=N-1:
n=0
sum=0
while n<=N-1:
sum=sum+l[n]*e^(-I*2*pi/N*k*n)
n=n+1
output.append(sum)
k=k+1
return output
# Compute the DFT of the sequence a, but just print the norms of
# the complex numbers
def norm_dft(a):
u=dft(a)
output=[]
for v in u:
x=N(v.abs())
if x<0.001:
x=0
output.append(x)
return output
f=piecewise([((0,2), 0), ((2,3), 1), ((3,5),0), ((5,6),1), ((6,8),0), ((8,9),1),((9,11),0)])
plot(f,(0,11)) # This is a function defined on [0,11], but with period 3
plot(f,(0,11))+plot(fourier_approx(f,15,11,x),(x,0,11),color='red')+plot(fourier_approx(f,4,11,x),(x,0,11),color='green')
# This function gives the coefficients in the Fourier series for f.
# Prints out [k:a_k,b_k,f_k] where a_k is the coefficient of cosine,
# b_k is the coefficient of sine, and f_k is the frequency
#
def fourier_exp(f,n,length): #compute series from k=0 to k=n
i=1
L=length/2
a0=f.fourier_series_cosine_coefficient(0)/2
output=[[0,':',a0,0,0]]
while i<=n:
a=N(f.fourier_series_cosine_coefficient(i))
if abs(a)<0.0001:
a=0
b=N(f.fourier_series_sine_coefficient(i))
if abs(b)<0.0001:
b=0
output.append([i,':',a,b,i/L*pi])
i=i+1
return output
fourier_exp(f,15,11)
# The gives the Fourier approximation function defined using a sum
# from k=0 to k=n
# Here "length" is the length of the original interval on which f
# is defined.
#
def fourier_approx(f,n,length,x):
list=fourier_exp(f,n,length)
temp=list[0][2]
i=1
while i<=n:
freq=list[i][4]
A=list[i][2]
B=list[i][3]
temp=temp+A*cos(freq*x)+B*sin(freq*x)
i=i+1
return temp
f=piecewise([ ((0,1),0),((1,2),1 ) ])
plot(f,(0,2))
plot(f,(0,2))+plot(fourier_approx(f,1,2,x),(x,0,2),color='red')
plot(f,(0,2))+plot(fourier_approx(f,5,2,x),(x,0,2),color='red')
f=[0,0,1,0,0,1,0,0,1,0,0] #Here N=11 and s=3
norm_dft(f) #Get spikes in F near 11/3 and 2*(11/3)
f=[0,0,1,0,0,1,0,0,1]
f=f+f+f # Here N=56 and s=3. Get spikes in F near
f=f+f+[0,0] # 56/3 and 2*(56/3)
norm_dft(f)
list_plot(f)+list_plot(norm_dft(f),color='red')
f=piecewise([((0,2), 0), ((2,3), 1), ((3,5),0), ((5,6),1), ((6,8),0), ((8,9),1),((9,11),0)])
fourier_exp(f,25,11) #N=11, s=3: note the biggest contributions are
#around k=11/3, 2*(11/3), 3*(11/3), 4*(11/3) and so on
# Here we show f in blue, the Fourier approx in red, and the
#"largest coefficient" terms of the Fourier approximation in green
plot(f,(0,11))+plot(fourier_approx(f,25,11,x),(0,11),color='red')+plot(3/11-0.29*cos(6/11*pi*x)+0.388*cos(8/11*pi*x)-0.22*cos(14/11*pi*x)+0.11*cos(16/11*pi*x),(0,11),color='green')
# Example of a sum of cosine and sine functions with different periods
plot(cos(3*x)+sin(5*x)+6*cos(x),(0,20))