Harmonics Examples

Below are solutions to the class exercise from Friday 2/5

In [1]:
import numpy as np
import matplotlib.pyplot as plt
import IPython.display as ipd

Example 1: Sawtooth Wave

People tend to think this is like a bowed string

In [2]:
sr = 44100
t = np.arange(sr*2)/sr
f0 = 440
y = np.zeros_like(t)
for i in range(1, 11):
    y -= np.sin(2*np.pi*(f0*i)*t)/i

plt.plot(t, y)
plt.xlim([0, 0.01])
ipd.Audio(y, rate=sr)
Out[2]:
In [3]:
y2 = np.arange(sr*2) % 100
plt.plot(t, y2)
plt.xlim([0, 0.01])
ipd.Audio(y2, rate=sr)
Out[3]:

Example 2

Square wave

In [4]:
sr = 44100
t = np.arange(sr*2)/sr
f0 = 440
y = np.zeros_like(t)
a = 1.0
for i in range(1, 31):
    if i%2 == 1:
        y += a*np.cos(2*np.pi*(f0*i)*t)/i
        a *= -1

plt.plot(t, y)
plt.xlim([0, 0.01])
ipd.Audio(y, rate=sr)
Out[4]:
In [5]:
y2 = np.sign(np.cos(2*np.pi*f0*t))
plt.plot(t, y2)
plt.xlim([0, 0.01])
ipd.Audio(y2, rate=sr)
Out[5]:

Example 3

Triangle wave

In [6]:
sr = 44100
t = np.arange(sr*2)/sr
f0 = 440
y = np.zeros_like(t)
a = 1.0
for i in range(1, 21):
    if i%2 == 1:
        y += a*np.sin(2*np.pi*(f0*i)*t)/(i**2)
        a *= -1

plt.plot(t, y)
plt.xlim([0, 0.01])
ipd.Audio(y, rate=sr)
Out[6]:
In [ ]: