Skip to content

Instantly share code, notes, and snippets.

@yulanggong
Created October 19, 2017 03:24
Show Gist options
  • Save yulanggong/59dcf878fff455d825803000b46f7900 to your computer and use it in GitHub Desktop.
Save yulanggong/59dcf878fff455d825803000b46f7900 to your computer and use it in GitHub Desktop.
Combine variances of subsets
/**
* statistics of a set
* @typedef {object} stat
* @prop {numher} count
* @prop {number} average
* @prop {number} variance
*/
/**
* combine variances
* @param {stat[]} stats
* @returns {stat}
*/
function combineVariances(stats){
let sum = 0;
let count = 0;
let sumVariances = 0;
stats.forEach(stat => {
count += stat.count;
sum += stat.average * stat.count;
});
const average = sum / count;
stats.forEach(stat => {
sumVariances += (Math.pow(stat.average - average, 2) + stat.variance) * stat.count;
});
return {
count: count,
average: average,
variance: sumVariances / count
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment