pub struct Median<const N: usize> { /* private fields */ }Expand description
A median filter over the most recent N readings.
A single bad sample - a spike from electrical noise or a flaky contact - drags a mean or
an exponential average off course, because it is blended into the result. The median
ignores it: one outlier cannot move the middle value of a sorted window. That makes a
Median the right filter when the noise is occasional spikes rather than steady
jitter; for steady jitter reach for Smoother instead. Keep the
window small and odd (3, 5, 7) so there is a single middle reading; with an even N the
median is the average of the two middle readings. A wide window rejects longer bursts
and lags a real step by half its length, so a filter of 32 passes a new level 16
readings late. with_capacity keeps fewer than N.
A reading that is not a finite number, such as the NaN a failed sensor reports, is not kept.
§Examples
use pamoja_kit::Median;
let mut filtered = Median::<5>::new();
// A lone spike among steady readings is rejected.
for reading in [10.0, 10.0, 99.0, 10.0, 10.0] {
filtered.update(reading);
}
assert_eq!(filtered.median(), Some(10.0));Implementations§
Source§impl<const N: usize> Median<N>
impl<const N: usize> Median<N>
Sourcepub fn new() -> Self
pub fn new() -> Self
Creates an empty median filter over a window of N readings.
§Returns
A filter holding no readings yet.
Sourcepub fn with_capacity(capacity: usize) -> Self
pub fn with_capacity(capacity: usize) -> Self
Sourcepub fn push(&mut self, reading: f32)
pub fn push(&mut self, reading: f32)
Adds a reading to the window, evicting the oldest once it is full.
§Arguments
reading- the latest raw reading. One that is not a finite number is not kept.
Sourcepub fn capacity(&self) -> usize
pub fn capacity(&self) -> usize
Returns the most readings the filter keeps: N, or less when made with
with_capacity.