Created
October 19, 2017 03:24
-
-
Save yulanggong/59dcf878fff455d825803000b46f7900 to your computer and use it in GitHub Desktop.
Combine variances of subsets
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
/** | |
* 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