Skip to content

Instantly share code, notes, and snippets.

@mloughran
Created June 2, 2010 18:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mloughran/422768 to your computer and use it in GitHub Desktop.
Save mloughran/422768 to your computer and use it in GitHub Desktop.
# 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