Skip to content

Mean of numbers #977

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
xeruf opened this issue Aug 1, 2024 · 1 comment
Open

Mean of numbers #977

xeruf opened this issue Aug 1, 2024 · 1 comment

Comments

@xeruf
Copy link

xeruf commented Aug 1, 2024

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.

@solarretrace
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants