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"
)
// 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 {
alpha float64 // Filter coefficient
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 {
// Calculate filter coefficient (alpha) based on cutoff frequency and sample rate
alpha := 1.0 - math.Exp(-2.0*math.Pi*cutoffFrequency/sampleRate)
rc := 1.0 / (2 * math.Pi * cutoffFrequency)
dt := 1.0 / sampleRate
alpha := dt / (rc + dt)
return &LowPassFilter{
alpha: alpha,
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 {
filtered := make([]float64, len(input))
for i, x := range input {
// Update filter output using the single-pole low-pass filter equation
output := lpf.alpha*x + (1-lpf.alpha)*lpf.yPrev
lpf.yPrev = output
filtered[i] = output
if i == 0 {
filtered[i] = x * lpf.alpha
} else {
filtered[i] = lpf.alpha*x + (1-lpf.alpha)*lpf.yPrev
}
lpf.yPrev = filtered[i]
}
return filtered
}