Created
October 5, 2017 19:35
-
-
Save vfeskov/0b1be0a7c4f60c77779570597c228de9 to your computer and use it in GitHub Desktop.
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
/** | |
* 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