In [2]:
import numpy as np
import matplotlib.pyplot as plt
In [7]:
## A2P1
def genSine(A, f, phi, fs, t):
"""
Inputs:
A (float) = amplitude of the sinusoid
f (float) = frequency of the sinusoid in Hz
phi (float) = initial phase of the sinusoid in radians
fs (float) = sampling frequency of the sinusoid in Hz
t (float) = duration of the sinusoid (is second)
Output:
The function should return a numpy array
x (numpy array) = The generated sinusoid (use np.cos())
"""
n = np.arange(0,t,1/fs)
x = A*np.cos(2*np.pi*f*n + phi)
return x
In [18]:
## A2P2
def genComplexSine(k, N):
"""
Inputs:
k (integer) = frequency index of the complex sinusoid of the DFT
N (integer) = length of complex sinusoid in samples
Output:
The function should return a numpy array
cSine (numpy array) = The generated complex sinusoid (length N)
"""
n = np.arange(N)/N
cSine = np.exp(-1j*2*np.pi*k*n)
return cSine
In [29]:
def DFT(x):
"""
Input:
x (numpy array) = input sequence of length N
Output:
The function should return a numpy array of length N
X (numpy array) = The N point DFT of the input sequence x
"""
X = []
for k in np.arange(x.size):
# k-th basis vector
s_k = genComplexSine(np.float(k),np.float(x.size))
X = np.append(X,np.sum(x*s_k))
return X
In [38]:
def IDFT(X):
"""
Input:
X (numpy array) = frequency spectrum (length N)
Output:
The function should return a numpy array of length N
x (numpy array) = The N point IDFT of the frequency spectrum X
"""
x = []
for n in np.arange(X.size):
#k-th basis vector
s_k = np.conjugate(genComplexSine(np.float(n), np.float(X.size)))
x = np.append(x,np.sum(X*s_k))
return x/X.size
In [10]:
## A2P1
A = 1.0
f = 10.0
phi = 1.0
fs = 50.0
t = 0.1
x = genSine(A,f,phi,fs,t)
print x
In [19]:
## A2P2
k = 1.0
N = 5.0
cSine = genComplexSine(k=k,N=N)
print cSine
In [36]:
## A2P3
x = np.array([1, 2, 3, 4])
X1 = DFT(x)
print X1
In [39]:
## A2P4
X = np.array([1,1,1,1])
x = IDFT(X)
print x
x1 = IDFT(X1)
print x1