discret filter in python

To discretely filter a signal in Python, you can use the lfilter function from the scipy.signal package, which is built on top of NumPy. Here's an example:

main.py
import numpy as np
from scipy.signal import lfilter

# Create a test signal
fs = 100  # sampling rate (Hz)
t = np.arange(0, 1, 1/fs)  # time vector (s)
freq = 10  # signal frequency (Hz)
x = np.sin(2*np.pi*freq*t)  # input signal

# Define a filter
fc = 15  # cutoff frequency (Hz)
order = 4  # filter order
b, a = scipy.signal.butter(order, fc/(fs/2), 'lowpass')  # construct filter coefficients

# Filter the signal
y = lfilter(b, a, x)
439 chars
17 lines

In this example, we first create a test input signal x, with a frequency of 10 Hz. We then define a lowpass Butterworth filter with a cut-off frequency of 15 Hz and order 4.

Finally, we apply the filter to the input signal using lfilter. The resulting filtered signal y has been smoothed with the lowpass filter, removing high frequency noise beyond 15 Hz.

Note that you can also use other filter types (e.g. Chebyshev, Bessel, etc.) and other filter functions (e.g. filtfilt) depending on your requirements.

gistlibby LogSnag