Additive synthesis of square wave and sawtooth wave
#!/usr/bin/python3
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 2 * np.pi, 0.01)
y = np.zeros_like(x)
for n in range(1, 16, 2):
y += np.sin(n * x) / n
z = np.zeros_like(x)
for n in range(1, 9):
z += np.sin(n * x) / n
plt.figure(figsize=(10, 5))
plt.plot(x, y, label="Odd harmonics (1, 3, 5, ..., 15)")
plt.plot(x, z, color="red", label="All harmonics (1 through 8)")
plt.xlim(0, 2 * np.pi)
plt.xticks(
[0, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi],
["0", "π/2", "π", "3π/2", "2π"]
)
plt.xlabel("Radians")
plt.ylabel("Amplitude")
plt.title("Fourier Series")
plt.grid(True)
plt.legend()
plt.tight_layout()
plt.show()
