Created
June 2, 2010 18:25
-
-
Save mloughran/422768 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Easily calculate mean and standard distribution of a distribution without | |
# collecting all values in memory | |
# | |
class Distribution | |
def initialize | |
@n, @sum_x, @sum_x_2 = 0, 0, 0 | |
end | |
def <<(x) | |
@n += 1 | |
@sum_x += x | |
@sum_x_2 += x**2 | |
end | |
def stats | |
mean_x = @sum_x.to_f / @n | |
mean_x_2 = (1.0/@n) * @sum_x_2 | |
sd = Math.sqrt(mean_x_2 - mean_x**2) | |
{ | |
:count => @n, | |
:mean => mean_x, | |
:sd => sd | |
} | |
end | |
end | |
dist = Distribution.new | |
(0..10).each { |i| dist << i } | |
p dist.stats |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment