Created
March 8, 2013 15:04
-
-
Save eliOcs/5117025 to your computer and use it in GitHub Desktop.
Calculating averages iteratively
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
"use strict"; | |
var math = exports; | |
/** | |
* Adds a new value to a calculated average. | |
* | |
* i.e. n × average + value | |
* ------------------- = new average | |
* n + 1 | |
*/ | |
math.addToAverage = function (average, n, value) { | |
return (n * average + value) / (n + 1); | |
}; | |
/** | |
* Subtract a value from a calculated average. | |
* | |
* i.e. n × average - value | |
* ------------------- = new average | |
* n - 1 | |
*/ | |
math.subtractFromAverage = function (average, n, value) { | |
if (n < 1) { return 0; } | |
return (n * average - value) / (n - 1); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment