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


[ 0.54030231 -0.63332387 -0.93171798  0.05749049  0.96724906]

In [19]:
## A2P2
k = 1.0
N = 5.0
cSine = genComplexSine(k=k,N=N)
print cSine


5.0
[ 1.00000000+0.j          0.30901699-0.95105652j -0.80901699-0.58778525j
 -0.80901699+0.58778525j  0.30901699+0.95105652j]

In [36]:
## A2P3
x = np.array([1, 2, 3, 4])
X1 = DFT(x)
print X1


4.0
4.0
4.0
4.0
[ 10. +0.00000000e+00j  -2. +2.00000000e+00j  -2. -9.79717439e-16j
  -2. -2.00000000e+00j]

In [39]:
## A2P4
X = np.array([1,1,1,1])
x = IDFT(X)
print x

x1 = IDFT(X1)
print x1


4.0
4.0
4.0
4.0
[  1.00000000e+00 +0.00000000e+00j  -5.55111512e-17 +2.77555756e-17j
   0.00000000e+00 +6.12323400e-17j   8.32667268e-17 +1.11022302e-16j]
4.0
4.0
4.0
4.0
[ 1. -5.55111512e-16j  2. -3.88578059e-16j  3. -5.55111512e-17j
  4. +3.33066907e-16j]