Skip to content

Instantly share code, notes, and snippets.

@olly
Forked from mloughran/simple_mean_sd.rb
Created July 16, 2010 16:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olly/478592 to your computer and use it in GitHub Desktop.
Save olly/478592 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
@min, @max = nil, nil
end
def <<(x)
@n += 1
@sum_x += x
@sum_x_2 += x**2
@min = x if @min.nil? || x < @min
@max = x if @max.nil? || x > @max
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,
:min => @min,
:max => @max,
}
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