Last active
December 16, 2015 00:59
-
-
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
This file contains 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
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