use crate::{Error, Result};
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct WeightedMean {
sum: f64,
weight: f64,
}
impl WeightedMean {
#[inline]
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn update(&mut self, sum: f64, weight: f64) -> Result<()> {
if weight < 0.0 || !weight.is_finite() {
return Err(Error::invalid_argument(
"weighted metric contributions require a finite non-negative weight",
));
}
self.sum += sum;
self.weight += weight;
Ok(())
}
pub fn merge(&mut self, other: &Self) {
self.sum += other.sum;
self.weight += other.weight;
}
#[must_use]
pub fn result(&self) -> f64 {
if self.weight == 0.0 {
f64::NAN
} else {
self.sum / self.weight
}
}
#[must_use]
pub const fn sum(&self) -> f64 {
self.sum
}
#[must_use]
pub const fn weight(&self) -> f64 {
self.weight
}
pub fn reset(&mut self) {
self.sum = 0.0;
self.weight = 0.0;
}
}