Last active
December 25, 2017 01:17
-
-
Save hunan-rostomyan/cf5c69590d3f37e64003d19757e04e72 to your computer and use it in GitHub Desktop.
Statistics (mean, variance, standard deviation, ...)
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 sum(arr) { | |
return arr.reduce((acm, cur) => acm + cur, 0); | |
} | |
function mean(xs, correction) { | |
var correction = correction || 0; | |
var total = xs.length - correction; | |
return sum(xs) / total; | |
} | |
function dispersion(xs, correction) { | |
var m = mean(xs); | |
var sq_devs = xs.map(x => Math.pow(x - m, 2)); | |
return mean(sq_devs, correction); | |
} | |
function sd(xs, correction) { | |
return Math.sqrt(dispersion(xs, correction)); | |
} | |
function z_score(x, m, sd) { | |
return (x - m) / sd; | |
} | |
// Usage | |
// ----- | |
// raw data | |
var x_str = '1 5 2 7 1 9 3 8 5 9'; | |
// processed, numerical data | |
var xs = x_str.split(' ').map(x => parseInt(x)); | |
console.log(sd(xs, 1)); |
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
import math | |
def mean(A): | |
"""Calculate the mean of A.""" | |
size = len(A) | |
if size <= 0: | |
raise TypeError('Cannot take the mean of an empty sample.') | |
return sum(A) / size | |
def variance(A, correction=False): | |
"""Calculate the variance of A.""" | |
m, size = mean(A), len(A) | |
diff_sq = [(x - m) ** 2 for x in A] | |
return sum(diff_sq) / (size - int(correction)) | |
def std(A, correction=False): | |
"""Calculate the standard deviation of A.""" | |
return math.sqrt(variance(A, correction)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment