Book Image

Sage Beginner's Guide

By : Craig Finch
1 (1)
Book Image

Sage Beginner's Guide

1 (1)
By: Craig Finch

Overview of this book

Table of Contents (17 chapters)
Sage Beginner's Guide
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Time for action – computing discrete Fourier transforms


Since the discrete Fourier transform operates on an array of samples from a signal, we'll use the signal-processing tools in NumPy:

import numpy as np
import matplotlib.pyplot as plt

dt = 0.01
t = np.arange(-10, 10, dt)
f = np.sinc(t)

plt.figure(figsize=(6, 3))
plt.plot(t, f)
plt.savefig('f.png')
plt.close()

fourier_transform = np.fft.fft(f)
spectrum = np.absolute(fourier_transform)
phase = np.angle(fourier_transform)

freq = np.fft.fftfreq(t.shape[-1], d=dt)

spectrum = np.fft.fftshift(spectrum)
phase = np.fft.fftshift(phase)
freq = np.fft.fftshift(freq)

plt.figure(figsize=(6,3))
plt.plot(freq, spectrum)
plt.title('Magnitude')
plt.axis([-1.5, 1.5, spectrum.min(),spectrum.max()])
plt.savefig('spectrum.png')

plt.figure(figsize=(6,3))
plt.plot(freq, phase)
plt.title('Phase')
plt.axis([-1.5,1.5, phase.min(),phase.max()])
plt.savefig('phase.png')

plt.close()

The following plots show the function, its magnitude spectrum, and its phase...