Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Browse files
Browse the repository at this point in the history
feat(mean): subtractFromMean, a method to remove a value from the mean
- Loading branch information
1 parent
e452e39
commit afe76e9
Showing
3 changed files
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
'use strict'; | ||
/* @flow */ | ||
|
||
/** | ||
* When removing a value from a list, one does not have to necessary | ||
* recompute the mean of the list in linear time. They can instead use | ||
* this function to compute the new mean by providing the current mean, | ||
* the number of elements in the list that produced it and the value to remove. | ||
* | ||
* @param {number} mean current mean | ||
* @param {number} n number of items in the list | ||
* @param {number} value the value to remove | ||
* @returns {number} the new mean | ||
* | ||
* @example | ||
* subtractFromMean(20.5, 6, 53); // => 14 | ||
*/ | ||
function subtractFromMean(mean /*: number*/, n/*: number */, value/*: number */)/*: number */ { | ||
return ((mean * n) - value) / (n - 1); | ||
} | ||
|
||
module.exports = subtractFromMean; |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
/* eslint no-shadow: 0 */ | ||
'use strict'; | ||
|
||
var test = require('tap').test; | ||
var ss = require('../'); | ||
|
||
test('subtractFromMean', function(t) { | ||
t.test('can remove a single value from a mean', function(t) { | ||
var values = [13, 14, 15, 8, 20, 54]; | ||
t.equal(ss.subtractFromMean(ss.mean(values), values.length, 54), 14); | ||
t.equal(ss.subtractFromMean(ss.mean(values), values.length, 54), ss.mean(values.slice(0, -1))); | ||
t.end(); | ||
}); | ||
t.end(); | ||
}); |