find the variance of all keys in a map in rust

Here's a possible implementation of a function that computes the variance of all the values in a HashMap:

main.rs
use std::collections::HashMap;

fn variance(map: &HashMap<&str, f64>) -> Option<f64> {
    let n = map.len() as f64;
    if n <= 1.0 {
        return None
    }
    
    // Compute the mean
    let sum = map.values().sum::<f64>();
    let mean = sum / n;
    
    // Compute the sum of squared differences from the mean
    let ssd = map.values().map(|x| (x - mean).powi(2)).sum::<f64>();
    
    Some(ssd / (n - 1.0))
}
422 chars
18 lines

Here, we use the central formula for variance:

main.rs
Var(X) = E[(X – E[X])^2]
25 chars
2 lines

where E[X] is the mean and E[...] denotes the expected value. We compute the mean and the sum of squared differences in a single pass over the values of the map, using the .sum() and .map() iterator methods, respectively.

If the length of the map is 0 or 1, we return None, as the variance is undefined. Otherwise, we return the sample variance, which is the sum of squared differences divided by n-1; the -1 corrects for the fact that we are estimating the variance from a sample, rather than the population. The result is wrapped in an Option, as it may be undefined.

gistlibby LogSnag