Last active
July 12, 2016 20:59
-
-
Save stekhn/1254b2f799b1f6da4bf1736424102c8e to your computer and use it in GitHub Desktop.
Discrete random variable standard deviation in JavaScript
This file contains hidden or 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
function weightedStdDev(values, weights) { | |
var avg = weightedMean(values, weights); | |
var result = values.map(function (value, i) { | |
var weight = weights[i]; | |
var diff = value - avg; | |
var sqrDiff = weight * Math.pow(diff, 2); | |
return [sqrDiff, weight]; | |
}).reduce(function (previous, current) { | |
return [previous[0] + current[0], previous[1] + current[1]]; | |
}, [0, 0]); | |
return Math.sqrt(result[0] / result[1]); | |
} | |
function weightedMean(values, weights) { | |
var result = values.map(function (value, i) { | |
var weight = weights[i]; | |
var sum = value * weight; | |
return [sum, weight]; | |
}).reduce(function (previous, current) { | |
return [previous[0] + current[0], previous[1] + current[1]]; | |
}, [0, 0]); | |
return result[0] / result[1]; | |
} | |
weightedStdDev([251, 360, 210, 900, 425, 12], [0.1, 0.5, 0.7, 0.3, 0.4, 0.1]); | |
// => 236.5988980294558 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment