Fourier Series Demo

In [1]:
import numpy as np
from copy import deepcopy
import matplotlib.pyplot as plt

Get a function to work with

In [2]:
# Create a step function
f = np.zeros(128)
b = 0
f[b:b+64] = 1.
plt.plot(f, 'o-')
plt.title('Step Function')
plt.axis((0, 127, -0.5, 1.5));

Look at its Fourier coefficients

(actually, it's the log of the modulus)

In [3]:
F = np.fft.fft(f)
plt.stem(np.log(np.abs(F)+1));
#plt.stem(np.abs(F));
plt.title('Modulus of Fourier Coefficients')
plt.ylabel('log Modulus'); plt.xlabel('Index');
In [4]:
F[13]
Out[4]:
(0.9999999999999929-3.0270432043177733j)

Reconstruction f using more and more Forier coefs

In [5]:
def PlotSeries(F, m):
    G = deepcopy(F)
    G[m:-m] = 0  # set all but the first (and last) m to 0
    g = np.fft.ifft(G)  # IDFT
    f = np.fft.ifft(F)  # True function
    plt.figure(figsize=(10,5))
    coefs = min(2*m+1, len(F))
    plt.subplot(1,2,1); plt.stem(np.log(np.abs(G)+1));
    plt.title(str(coefs)+' Forier Coefficients');
    plt.subplot(1,2,2); plt.plot(np.real(f), color='lightgray'); plt.plot(np.real(g));
    plt.title('Approximation with '+str(coefs)+' Coefficients');
In [6]:
PlotSeries(F, 1)
In [7]:
PlotSeries(F,9)
In [8]:
PlotSeries(F, 17)
In [9]:
PlotSeries(F, 30)
In [10]:
PlotSeries(F, 50)
In [11]:
PlotSeries(F, 64)
In [ ]: