Improve lowpass filter. Thanks to ChatGPT

This commit is contained in:
Chigozirim Igweamaka 2024-06-17 11:19:09 +01:00
parent 5547fedd7c
commit 026e9398c3

View file

@ -4,34 +4,33 @@ import (
"math" "math"
) )
// LowPassFilter implements a simple first-order low-pass filter // LowPassFilter is a first-order low-pass filter using H(p) = 1 / (1 + pRC)
type LowPassFilter struct { type LowPassFilter struct {
alpha float64 // Filter coefficient alpha float64 // Filter coefficient
yPrev float64 // Previous output value yPrev float64 // Previous output value
} }
// NewLowPassFilter creates a new LowPassFilter with the specified cutoff frequency and sample rate // NewLowPassFilter creates a new low-pass filter
func NewLowPassFilter(cutoffFrequency, sampleRate float64) *LowPassFilter { func NewLowPassFilter(cutoffFrequency, sampleRate float64) *LowPassFilter {
// Calculate filter coefficient (alpha) based on cutoff frequency and sample rate rc := 1.0 / (2 * math.Pi * cutoffFrequency)
alpha := 1.0 - math.Exp(-2.0*math.Pi*cutoffFrequency/sampleRate) dt := 1.0 / sampleRate
alpha := dt / (rc + dt)
return &LowPassFilter{ return &LowPassFilter{
alpha: alpha, alpha: alpha,
yPrev: 0, yPrev: 0,
} }
} }
// Filter filters the input signal using the low-pass filter and returns the filtered output // Filter processes the input signal through the low-pass filter
func (lpf *LowPassFilter) Filter(input []float64) []float64 { func (lpf *LowPassFilter) Filter(input []float64) []float64 {
filtered := make([]float64, len(input)) filtered := make([]float64, len(input))
for i, x := range input { for i, x := range input {
// Update filter output using the single-pole low-pass filter equation if i == 0 {
output := lpf.alpha*x + (1-lpf.alpha)*lpf.yPrev filtered[i] = x * lpf.alpha
lpf.yPrev = output } else {
filtered[i] = lpf.alpha*x + (1-lpf.alpha)*lpf.yPrev
filtered[i] = output }
lpf.yPrev = filtered[i]
} }
return filtered return filtered
} }