dfdsdfsdfsd
Fixed-window moving average with constant-time updates.
use std::collections::VecDeque;
pub struct MovingAverage {
window: VecDeque<f64>,
capacity: usize,
sum: f64,
}
impl MovingAverage {
pub fn new(capacity: usize) -> Self {
Self { window: VecDeque::with_capacity(capacity), capacity, sum: 0.0 }
}
pub fn push(&mut self, value: f64) -> f64 {
if self.window.len() == self.capacity {
if let Some(old) = self.window.pop_front() {
self.sum -= old;
}
}
self.window.push_back(value);
self.sum += value;
self.sum / self.window.len() as f64
}
}
Fixed-window moving average with constant-time updates.
use std::collections::VecDeque;
pub struct MovingAverage {
window: VecDeque<f64>,
capacity: usize,
sum: f64,
}
impl MovingAverage {
pub fn new(capacity: usize) -> Self {
Self { window: VecDeque::with_capacity(capacity), capacity, sum: 0.0 }
}
pub fn push(&mut self, value: f64) -> f64 {
if self.window.len() == self.capacity {
if let Some(old) = self.window.pop_front() {
self.sum -= old;
}
}
self.window.push_back(value);
self.sum += value;
self.sum / self.window.len() as f64
}
}
Fixed-window moving average with constant-time updates.
use std::collections::VecDeque;
pub struct MovingAverage {
window: VecDeque<f64>,
capacity: usize,
sum: f64,
}
impl MovingAverage {
pub fn new(capacity: usize) -> Self {
Self { window: VecDeque::with_capacity(capacity), capacity, sum: 0.0 }
}
pub fn push(&mut self, value: f64) -> f64 {
if self.window.len() == self.capacity {
if let Some(old) = self.window.pop_front() {
self.sum -= old;
}
}
self.window.push_back(value);
self.sum += value;
self.sum / self.window.len() as f64
}
}
Feel free to fork and adapt.
Developer Discussions