Skip to content

Instantly share code, notes, and snippets.

@littlemerman
Created November 30, 2011 05:58
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 littlemerman/1408219 to your computer and use it in GitHub Desktop.
Save littlemerman/1408219 to your computer and use it in GitHub Desktop.
Variance for streams
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 );
@littlemerman
Copy link
Author

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/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment