This code creates a noisy sine wave and applies a simple IIR low-pass filter to reduce noise. The plot shows the original noisy signal and the smoother filtered signal.
import numpy as np
import matplotlib.pyplot as plt
# Sample input signal: noisy sine wave
fs = 100 # Sampling frequency
f = 5 # Signal frequency
t = np.arange(0, 1, 1/fs)
x = np.sin(2 * np.pi * f * t) + 0.5 * np.random.randn(len(t))
# IIR filter coefficients (simple low-pass)
b = [0.2929, 0.2929] # feedforward coefficients
a = [-0.4142] # feedback coefficients
# Initialize output array
y = np.zeros_like(x)
# Apply IIR filter
for n in range(len(x)):
x_n = x[n]
x_n_1 = x[n-1] if n-1 >= 0 else 0
y_n_1 = y[n-1] if n-1 >= 0 else 0
y[n] = b[0]*x_n + b[1]*x_n_1 - a[0]*y_n_1
# Plot input and filtered output
plt.plot(t, x, label='Noisy Input')
plt.plot(t, y, label='Filtered Output')
plt.legend()
plt.xlabel('Time (seconds)')
plt.title('IIR Filter Example')
plt.show()