Sharedmaster / Fourier_analysis.sagewsOpen in CoCalc

Fourier analysis

Code adapted from https://arachnoid.com/sage/fourier.html and https://youtu.be/TwWpewdNOpg

from sage.plot.bar_chart import BarChart
var('t')
t

Example 1

f1(t)=12sin(2π(3t))+11sin(2π(4t))+10sin(2π(5t))+9sin(2π(6t))f_{1}(t) = 12\sin(2\pi(3t)) + 11\sin(2\pi(4t)) + 10\sin(2\pi(5t)) + 9\sin(2\pi(6t))


f1(t) = 12*sin(2*pi*(3*t)) + 11*sin(2*pi*(4*t)) + 10*sin(2*pi*(5*t)) + 9*sin(2*pi*(6*t))

plot(f1, (t, -1, 2))
# Choose number of samples
size1 = 25

# Create an empty Fast Fourier Transform object
fft_data1 = FFT(size1)

# Populate it with data sampled from f1.
for t in range(size1):
    fft_data1[t] = f1(t/size1)

# Plot results
plot(fft_data1)

# Fourier transform to convert to frequency domain
# (Modifies fft_data1 in place.)
fft_data1.forward_transform()
# Create empty array for amplitudes
fft_freq1 = [0 for j in range(size1/2)]

# Populate it with the computed amplitudes
# (For technical reasons, we only have to compute this for half of the sampled frequencies)
for f in range(size1/2):
    fft_freq1[f] = abs(vector(fft_data1[f]))/(size1/2)

# Plot results
bar_chart(fft_freq1)

Example 2

f2(t)=sgn(sin(2πt))f_{2}(t) = \mathrm{sgn}\left( \sin(2\pi t) \right)

f2(t) = sgn((sin(2*pi*t)))

plot(f2, (t, -1, 2))
# Choose number of samples
size2 = 100

# Create an empty Fast Fourier Transform object
fft_data2 = FFT(size2)

# Populate it with data sampled from f2.
for t in range(size2):
    fft_data2[t] = f2(t/size2)

# Plot results
plot(fft_data2)
# Fourier transform to convert to frequency domain
# (Modifies fft_data2 in place.)
fft_data2.forward_transform()

# Create empty array for amplitudes
fft_freq2 = [0 for j in range(size2/2)]

# Populate it with the computed amplitudes
# (For technical reasons, we only have to compute this for half of the sampled frequencies)
for f in range(size2/2):
    fft_freq2[f] = N(pi/4) * abs(vector(fft_data2[f]))/(size2/2) # Not sure why the extra factor of pi/4 is necessary.

# Plot results
bar_chart(fft_freq2[0:14])