Here's a possible implementation of a function that computes the variance of all the values in a HashMap
:
main.rs422 chars18 lines
Here, we use the central formula for variance:
main.rs25 chars2 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