Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Statistics (mean, variance, standard deviation, ...)
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));
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