Skip to content

Instantly share code, notes, and snippets.

@hunan-rostomyan
Last active December 25, 2017 01:17
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 hunan-rostomyan/cf5c69590d3f37e64003d19757e04e72 to your computer and use it in GitHub Desktop.
Save hunan-rostomyan/cf5c69590d3f37e64003d19757e04e72 to your computer and use it in GitHub Desktop.
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