Created
November 30, 2011 05:58
-
-
Save littlemerman/1408219 to your computer and use it in GitHub Desktop.
Variance for streams
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
var stat = {}; | |
stat.variance = function(x) { | |
var counter = 0; | |
var runningMean = 0; | |
var newMean = 0; | |
var runningVariance = 0; | |
var newVariance = 0; | |
var builder; | |
builder = function(a) { | |
// Check that input is a number | |
if ( typeof a !== 'number' || isNaN(a) || !isFinite(a) ) { | |
throw 'Input Error :: ' + x + '()'; | |
} else { | |
counter++; | |
if ( counter === 1 ) { | |
runningMean = newMean = a; | |
} else { | |
newMean = runningMean + (a - runningMean)/counter; | |
newVariance = runningVariance + (a - runningMean)*(a - newMean); | |
runningMean = newMean; | |
runningVariance = newVariance; | |
} | |
} | |
// Calculate variance | |
return counter > 1 ? newVariance/(counter-1) : 0 ; | |
}; | |
return builder; | |
}; | |
var s = stat.variance(); | |
function out(b) { | |
$('#var').text(s(b)); | |
} | |
var sample = Stream.range ( 10, 99 ); | |
sample.walk( out ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Live example:
http://jsbin.com/iwiwuz/latest
Translated to idiomatic javascript from here: http://www.johndcook.com/standard_deviation.html
Credit for bringing streams to my attention (and providing the implementation used here): http://streamjs.org/