itertools
itertools copied to clipboard
Mean of numbers
Would be great to have a helper to calculate the mean of an iterator of items which are both summable and divisable, by summing the elements and then dividing by the amount of elements.
In my case useful because I want the mean after calling filter_map, which means I now need to either collect or iterate in a for loop and count up.
This is pretty straightforward to do with std::Iterator::fold:
fn main() {
let nums = [1, 3, 5, 7, 4, 4, 4, 3];
let (total, count) = nums.into_iter()
.fold((0, 0), |(t, c), n| (t + n, c + 1));
println!("total: {}, count: {}", total, count);
println!("mean: {}", total as f64 / count as f64);
}
outputs
total: 31, count: 8
mean: 3.875
What you're asking for sounds like it should go into a crate providing specialized streaming statistics algorithms.