Skip to content

Instantly share code, notes, and snippets.

@bluetwin
Last active December 16, 2015 00:59
Show Gist options
  • Save bluetwin/5351560 to your computer and use it in GitHub Desktop.
Save bluetwin/5351560 to your computer and use it in GitHub Desktop.
RunningStat Class that uses Welford's Method for computing variance on a dataset
class RunningStat
attr_reader :n, :oldM, :newM, :oldS, :newS
def initialize
@n = 0
end
def clear
@n = 0
end
def push(x)
@n += 1
if(@n == 1)
@oldM = @newM = x
@oldS = 0.0
else
@newM = @oldM + (x - @oldM)/@n
@newS = @oldS + (x - @oldM)*(x - @newM)
@m_oldM = @newM
@m_oldS = @newS
end
end
def num_data_values
@n
end
def mean
(@n > 0) ? @newM : 0.0
end
def variance
( (@n > 1) ? @newS/(@n -1) : 0.0 )
end
def standard_deviation
Math.sqrt( self.variance() )
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment