Skip to content

Commit

Permalink
refactor!: impl FromIterator<f64> for Empirical
Browse files Browse the repository at this point in the history
Also remove now redundant `Empirical::from_vec`
  • Loading branch information
FreezyLemon committed Oct 2, 2024
1 parent 993a4b5 commit 4e2e956
Showing 1 changed file with 12 additions and 10 deletions.
22 changes: 12 additions & 10 deletions src/distribution/empirical.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,14 +65,6 @@ impl Empirical {
})
}

pub fn from_vec(src: Vec<f64>) -> Empirical {
let mut empirical = Empirical::new().unwrap();
for elt in src.into_iter() {
empirical.add(elt);
}
empirical
}

pub fn add(&mut self, data_point: f64) {
if !data_point.is_nan() {
self.sum += 1.;
Expand Down Expand Up @@ -174,6 +166,16 @@ impl std::fmt::Display for Empirical {
}
}

impl FromIterator<f64> for Empirical {
fn from_iter<T: IntoIterator<Item = f64>>(iter: T) -> Self {
let mut empirical = Self::new().unwrap();
for elt in iter {
empirical.add(elt);
}
empirical
}
}

#[cfg(feature = "rand")]
#[cfg_attr(docsrs, doc(cfg(feature = "rand")))]
impl ::rand::distributions::Distribution<f64> for Empirical {
Expand Down Expand Up @@ -243,7 +245,7 @@ mod tests {
#[test]
fn test_cdf() {
let samples = vec![5.0, 10.0];
let mut empirical = Empirical::from_vec(samples);
let mut empirical = Empirical::from_iter(samples);
assert_eq!(empirical.cdf(0.0), 0.0);
assert_eq!(empirical.cdf(5.0), 0.5);
assert_eq!(empirical.cdf(5.5), 0.5);
Expand Down Expand Up @@ -271,7 +273,7 @@ mod tests {
#[test]
fn test_sf() {
let samples = vec![5.0, 10.0];
let mut empirical = Empirical::from_vec(samples);
let mut empirical = Empirical::from_iter(samples);
assert_eq!(empirical.sf(0.0), 1.0);
assert_eq!(empirical.sf(5.0), 0.5);
assert_eq!(empirical.sf(5.5), 0.5);
Expand Down

0 comments on commit 4e2e956

Please sign in to comment.