From afe76e9e56097edd06dbabfacb326e418389e49f Mon Sep 17 00:00:00 2001 From: Guillaume Plique Date: Tue, 28 Feb 2017 16:34:08 +0100 Subject: [PATCH] feat(mean): subtractFromMean, a method to remove a value from the mean --- index.js | 1 + src/subtract_from_mean.js | 22 ++++++++++++++++++++++ test/subtract_from_mean.js | 15 +++++++++++++++ 3 files changed, 38 insertions(+) create mode 100644 src/subtract_from_mean.js create mode 100644 test/subtract_from_mean.js diff --git a/index.js b/index.js index b8e5c4e0..d823d05c 100644 --- a/index.js +++ b/index.js @@ -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'); diff --git a/src/subtract_from_mean.js b/src/subtract_from_mean.js new file mode 100644 index 00000000..1b77e7d3 --- /dev/null +++ b/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; diff --git a/test/subtract_from_mean.js b/test/subtract_from_mean.js new file mode 100644 index 00000000..abc6dfd5 --- /dev/null +++ b/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(); +});