Skip to content

Instantly share code, notes, and snippets.

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 vfeskov/0b1be0a7c4f60c77779570597c228de9 to your computer and use it in GitHub Desktop.
Save vfeskov/0b1be0a7c4f60c77779570597c228de9 to your computer and use it in GitHub Desktop.
/**
* Calculates weighted average with latter values weighing more.
*
* Weights for each value are calculated using https://en.wikipedia.org/wiki/Weighted_arithmetic_mean#Exponentially_decreasing_weights
*
* The average itself is calculated by summing up each value multiplied by its weight: https://en.wikipedia.org/wiki/Weighted_arithmetic_mean#Convex_combination_example
*
* @param {number|Array<number>} values Values, of which to calculate average
* @param {number} delta Delta, 0 < delta < 1, basically, how much weight the latest value will have when calculating average
* @return The input multiplied by 2.
* @customfunction
*/
function WEIGHTED_AVERAGE(values, delta) {
if (!Array.isArray(values)) {
return values;
}
const w = 1 - delta;
const m = values.length;
return values.reverse().reduce(function(result, value, i) {
return result + weight(i) * value;
}, 0);
function V1() {
return (1 - Math.pow(w, m)) / (1 - w);
}
function weight(i) {
return Math.pow(w, i) / V1(w, m);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment