use std::ops::Mul;
use num_traits::Float;
use crate::{Fill, FillWith};
#[derive(Copy, Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct WeightedSum<T = f64> {
sumw: T,
sumw2: T,
}
impl<T: Copy> WeightedSum<T> {
pub fn new() -> Self
where
Self: Default,
{
Self::default()
}
pub fn get(&self) -> T {
self.sum()
}
pub fn sum(&self) -> T {
self.sumw
}
pub fn variance(&self) -> T {
self.sumw2
}
pub fn standard_deviation<O>(&self) -> O
where
T: Into<O>,
O: Float,
{
self.variance().into().sqrt()
}
}
impl<T: Copy + Fill> Fill for WeightedSum<T> {
#[inline]
fn fill(&mut self) {
self.sumw.fill();
self.sumw2.fill();
}
}
impl<T, W> FillWith<W> for WeightedSum<T>
where
T: FillWith<W> + Copy,
W: Mul<Output = W> + Copy,
{
#[inline]
fn fill_with(&mut self, weight: W) {
self.sumw.fill_with(weight);
self.sumw2.fill_with(weight * weight);
}
}