Implement merge for Histogram

This commit is contained in:
Vinzent Steinberg 2018-07-06 13:27:26 +02:00
parent f22c7b362d
commit 0de183127e
2 changed files with 36 additions and 1 deletions

View File

@ -206,5 +206,17 @@ macro_rules! define_histogram {
}
}
}
impl $crate::Merge for $name {
fn merge(&mut self, other: &Self) {
assert_eq!(self.bin.len(), other.bin.len());
for (a, b) in self.range.iter().zip(other.range.iter()) {
assert_eq!(a, b, "Both histograms must have the same ranges");
}
for (a, b) in self.bin.iter_mut().zip(other.bin.iter()) {
*a += *b;
}
}
}
);
}

View File

@ -7,7 +7,7 @@ use core::iter::Iterator;
use rand::distributions::Distribution;
use rand::FromEntropy;
use average::Histogram;
use average::{Histogram, Merge};
define_histogram!(Histogram10, 10);
@ -202,3 +202,26 @@ fn variance() {
assert_almost_eq!(v.sqrt() / sum, poissonian_variance.sqrt() / sum, 1e-4);
}
}
#[test]
fn merge() {
let mut h = Histogram10::from_ranges(
[0., 0.1, 0.2, 0.3, 0.4, 0.5, 0.7, 0.8, 0.9, 1.0, 2.0].iter().cloned()).unwrap();
let mut h1 = h.clone();
let mut h2 = h.clone();
for &i in &[0.05, 0.7, 1.0, 1.5] {
h.add(i).unwrap();
h1.add(i).unwrap();
}
for &i in &[0., 0.3, 0.5, 0.5, 0.9] {
h.add(i).unwrap();
h2.add(i).unwrap();
}
println!("{:?}", h.bins());
println!("{:?}", h1.bins());
println!("{:?}", h2.bins());
println!();
h1.merge(&h2);
println!("{:?}", h1.bins());
assert_eq!(h.bins(), h1.bins());
}