Skip to content

Commit

Permalink
Covariance: Implement FromIterator and Extend
Browse files Browse the repository at this point in the history
  • Loading branch information
vks committed Dec 9, 2023
1 parent 19bf8da commit 8ec2dd6
Showing 1 changed file with 46 additions and 1 deletion.
47 changes: 46 additions & 1 deletion src/covariance.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use num_traits::ToPrimitive;
#[cfg(feature = "serde1")]
use serde_derive::{Deserialize, Serialize};

use crate::Merge;

/// Estimate the arithmetic mean and the covariance of a sequence of number pairs
Expand Down Expand Up @@ -179,6 +180,8 @@ impl Covariance {
}
self.sum_y_2 / self.n.to_f64().unwrap()
}

// TODO: Standard deviation and standard error
}

impl core::default::Default for Covariance {
Expand Down Expand Up @@ -229,4 +232,46 @@ impl Merge for Covariance {

self.n += other.n;
}
}
}

impl core::iter::FromIterator<(f64, f64)> for Covariance {
fn from_iter<T>(iter: T) -> Covariance
where
T: IntoIterator<Item = (f64, f64)>,
{
let mut cov = Covariance::new();
for (x, y) in iter {
cov.add(x, y);
}
cov
}
}

impl core::iter::Extend<(f64, f64)> for Covariance {
fn extend<T: IntoIterator<Item = (f64, f64)>>(&mut self, iter: T) {
for (x, y) in iter {
self.add(x, y);
}
}
}

impl<'a> core::iter::FromIterator<&'a (f64, f64)> for Covariance {
fn from_iter<T>(iter: T) -> Covariance
where
T: IntoIterator<Item = &'a (f64, f64)>,
{
let mut cov = Covariance::new();
for &(x, y) in iter {
cov.add(x, y);
}
cov
}
}

impl<'a> core::iter::Extend<&'a (f64, f64)> for Covariance {
fn extend<T: IntoIterator<Item = &'a (f64, f64)>>(&mut self, iter: T) {
for &(x, y) in iter {
self.add(x, y);
}
}
}

0 comments on commit 8ec2dd6

Please sign in to comment.