Skip to content

Instantly share code, notes, and snippets.

@stephanbogner
Last active July 9, 2017 20:49
Show Gist options
  • Save stephanbogner/fba4c3fbed2e7ae94d15b856c7c79b31 to your computer and use it in GitHub Desktop.
Save stephanbogner/fba4c3fbed2e7ae94d15b856c7c79b31 to your computer and use it in GitHub Desktop.
Calculating the average without knowing all previous values
var data = {};
addAverageData(data, 'averageAppleDiameter', 5);
addAverageData(data, 'averageAppleDiameter', 7);
addAverageData(data, 'averageAppleDiameter', 8);
addAverageData(data, 'averageAppleDiameter', 9);
addAverageData(data, 'averagePearDiameter', 9);
addAverageData(data, 'averagePearDiameter', 4);
addAverageData(data, 'averagePearDiameter', 6);
addAverageData(data, 'averagePearDiameter', 8);
function addAverageData(data, key, value) {
if (data[key]) {
data[key].value = addFraction(value, data[key].value, data[key].samples);
data[key].samples += 1;
} else {
data[key] = {};
data[key].value = value;
data[key].samples = 1;
}
}
function addFraction(currentValue, addValue, addValueIndex){
var indexFromOne = addValueIndex + 1;
var fraction = 1 / indexFromOne;
var fractionCurrent = (indexFromOne - 1) / indexFromOne;
currentValue = currentValue*fractionCurrent + addValue*fraction;
return currentValue;
}
function addFraction(currentValue, addValue, addValueIndex){
var indexFromOne = addValueIndex + 1;
var fraction = 1 / indexFromOne;
var fractionCurrent = (indexFromOne - 1) / indexFromOne;
currentValue = currentValue*fractionCurrent + addValue*fraction;
return currentValue;
}
var values = [0.003,5,3,2,7.323, 5.6, 8.669234, 456.45];
var total = 0;
for (var i = 0; i < values.length; i++) {
total += values[i];
};
console.log('classical: ' + total/values.length);
var total = 0;
for (var i = 0; i < values.length; i++) {
total = addFraction(total, values[i], i);
}
console.log(total);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment