Skip to content

Instantly share code, notes, and snippets.

@kumanna
Created October 13, 2025 14:19
Show Gist options
  • Select an option

  • Save kumanna/bfa8e10595cf98239608d505e6bb2c83 to your computer and use it in GitHub Desktop.

Select an option

Save kumanna/bfa8e10595cf98239608d505e6bb2c83 to your computer and use it in GitHub Desktop.
import numpy as np
import matplotlib.pyplot as plt
import scipy
np.set_printoptions(edgeitems=30, linewidth=100000, formatter=dict(float=lambda x: "%.3g" % x))
# We will create an ideal truncated filter
Ts = 44100
# 0.5 seconds
t = np.arange(0, 0.01, 1/44100)
my_signal = np.cos(2 * np.pi * 10000 * t) + 0.4 * np.cos(2 * np.pi * 17000 * t)
plt.plot(my_signal);plt.show()
# We want only the 10 kHz signal. We need to design a filter that will
# isolate it.
# 2pi === fs = 44100 Hz
# -pi === -fs/2 = -22050 Hz
# pi === fs/2 = 22050 Hz
# 2 * pi * 10000 / 44100 === 10 kHz
# We will create a band-pass filter around 10 kHz
# Ideal low-pass filter:
# sin(omega_c n) / pi / n
# = sin(omega_c n / pi * pi) / (pi * n)
# = sinc(omega_c / pi * n) * omega_c / pi
n = np.arange(-len(t) // 2, len(t) // 2)
omega_c = 0.1 * np.pi
h = np.sinc(omega_c / np.pi * n) * omega_c / np.pi
[W, H] = scipy.signal.freqz(h, worN = 8192, whole=True)
plt.plot(W, 20*np.log10(np.abs(H)));plt.show()
# We want a band-pass filter at 2 * pi * 10000 / 44100
h_bp = h * np.cos(2 * np.pi * 10000 / 44100 * n)
[W, H] = scipy.signal.freqz(h_bp, worN = 8192, whole=True)
plt.plot(W, 20*np.log10(np.abs(H)));plt.show()
output = np.convolve(my_signal, h_bp)
plt.plot(output)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment