Skip to content

Commit

Permalink
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
Yomguithereal authored and tmcw committed Feb 28, 2017
1 parent e452e39 commit afe76e9
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
1 change: 1 addition & 0 deletions index.js
Expand Up @@ -55,6 +55,7 @@ ss.harmonicMean = require('./src/harmonic_mean');
ss.mean = ss.average = require('./src/mean');
ss.median = require('./src/median');
ss.medianSorted = require('./src/median_sorted');
ss.subtractFromMean = require('./src/subtract_from_mean');

ss.rootMeanSquare = ss.rms = require('./src/root_mean_square');
ss.variance = require('./src/variance');
Expand Down
22 changes: 22 additions & 0 deletions src/subtract_from_mean.js
@@ -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;
15 changes: 15 additions & 0 deletions test/subtract_from_mean.js
@@ -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();
});

0 comments on commit afe76e9

Please sign in to comment.