Skip to content

Instantly share code, notes, and snippets.

@polarblau
Created January 7, 2013 16:21
Show Gist options
  • Save polarblau/4476238 to your computer and use it in GitHub Desktop.
Save polarblau/4476238 to your computer and use it in GitHub Desktop.
# http://bateru.com/news/2011/03/javascript-standard-deviation-variance-average-functions/
getNumWithSetDec = (num, numOfDec = 3) ->
pow10s = Math.pow(10, numOfDec)
(if (numOfDec) then Math.round(pow10s * num) / pow10s else num)
getAverageFromNumArr = (numArr, numOfDec) ->
return false unless _.isArray(numArr)
i = numArr.length
sum = 0
sum += numArr[i] while i--
getNumWithSetDec (sum / numArr.length), numOfDec
getVariance = (numArr, numOfDec) ->
return false unless _.isArray(numArr)
avg = getAverageFromNumArr(numArr, numOfDec)
i = numArr.length
v = 0
v += Math.pow((numArr[i] - avg), 2) while i--
v /= numArr.length
getNumWithSetDec v, numOfDec
getStandardDeviation = (numArr, numOfDec) ->
return false unless _.isArray(numArr)
stdDev = Math.sqrt(getVariance(numArr, numOfDec))
getNumWithSetDec stdDev, numOfDec
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment