pub struct Ema {
alpha: f64,
value: Option<f64>,
}Expand description
Exponential moving average (EMA) over scalar samples.
Stores a single f64 state and updates it in O(1) time with O(1) memory. This is also called
an exponentially weighted moving average; older samples are never dropped, but their influence
on the average decays exponentially.
With a new sample x, the EMA is updated as: ema = alpha * x + (1.0 - alpha) * ema_prev
alpha ∈ (0, 1) is the weight of the newest sample, whereas 1 - alpha is the weight of the
previous EMA value. alpha is called the smoothing factor: larger alpha reacts faster to
sample changes, while smaller alpha smooths the average.
You can construct this type from a half-life integer by using Ema::from_half_life. After
half_life updates, a sample contributes half as much as when it was added. With half-life
H, the most recent N samples contribute 1 - 2^(-N/H) of the total weight (once warmed
up). Example: if H = 50, newest 50 samples = 50%, 100 = 75%, 150 = 87.5%, etc.
Fields§
§alpha: f64Smoothing factor: weight of the newest sample.
value: Option<f64>Current EMA value, if any samples have been added.
Implementations§
Source§impl Ema
impl Ema
Sourcepub fn with_half_life_50() -> Self
pub fn with_half_life_50() -> Self
EMA preset: half-life 50 samples (good default for peer message latency).
Sourcepub fn with_half_life_1000() -> Self
pub fn with_half_life_1000() -> Self
EMA preset: half-life 1000 samples (low noise, good for e.g., block validation time).
Sourcepub fn from_half_life(half_life: NonZeroU16) -> Self
pub fn from_half_life(half_life: NonZeroU16) -> Self
Constructs an EMA from a half-life measured in samples.
After half_life updates, a sample’s weight is halved. This chooses:
alpha = 1 - 2^(-1/half_life).
Sourcefn new(alpha: f64) -> Self
fn new(alpha: f64) -> Self
Constructs an EMA from alpha in (0, 1). Panics if alpha is outside this range.