Skip to content

Commit

Permalink
Add docs and improvement to median filter
Browse files Browse the repository at this point in the history
  • Loading branch information
jhalterman committed Feb 5, 2025
1 parent 6311965 commit 4538983
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 11 deletions.
8 changes: 4 additions & 4 deletions pkg/util/math/median.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
package math

import (
"sort"
"slices"
)

// MedianFilter provides the median value over a rolling window.
Expand All @@ -23,6 +23,7 @@ func NewMedianFilter(size int) *MedianFilter {
}
}

// Add adds a value to the filter, sorts the values, and returns the current median.
func (f *MedianFilter) Add(value float64) float64 {
f.values[f.index] = value
f.index = (f.index + 1) % len(f.values)
Expand All @@ -33,12 +34,11 @@ func (f *MedianFilter) Add(value float64) float64 {
}

copy(f.sorted, f.values)
sort.Slice(f.sorted, func(i, j int) bool {
return f.sorted[i] < f.sorted[j]
})
slices.Sort(f.sorted)
return f.Median()
}

// Median returns the current median, else 0 if the filter isn't full yet.
func (f *MedianFilter) Median() float64 {
if f.size < len(f.values)-1 {
return 0
Expand Down
14 changes: 7 additions & 7 deletions pkg/util/math/median_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ import (
)

func TestMedianFilter(t *testing.T) {
t.Run("single value", func(t *testing.T) {
t.Run("not full window", func(t *testing.T) {
filter := NewMedianFilter(3)
result := filter.Add(5.0)
assert.Equal(t, 5.0, result)
median := filter.Add(5.0)
assert.Equal(t, 5.0, median)
assert.Equal(t, 0.0, filter.Median())
})

Expand All @@ -29,8 +29,8 @@ func TestMedianFilter(t *testing.T) {
filter.Add(1.0)
filter.Add(2.0)
filter.Add(3.0)
result := filter.Add(4.0)
assert.Equal(t, 3.0, result)
median := filter.Add(4.0)
assert.Equal(t, 3.0, median)
})

t.Run("unsorted input", func(t *testing.T) {
Expand All @@ -39,7 +39,7 @@ func TestMedianFilter(t *testing.T) {
filter.Add(2.0)
filter.Add(8.0)
filter.Add(1.0)
result := filter.Add(9.0)
assert.Equal(t, 5.0, result)
median := filter.Add(9.0)
assert.Equal(t, 5.0, median)
})
}

0 comments on commit 4538983

Please sign in to comment.