Skip to content

Instantly share code, notes, and snippets.

@mindplay-dk
Created February 14, 2014 15:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mindplay-dk/9002874 to your computer and use it in GitHub Desktop.
Save mindplay-dk/9002874 to your computer and use it in GitHub Desktop.
Computing weighted average from a set of values
function weighted_average($values) {
$sum = 0;
foreach ($values as $i => $value) {
$sum += $value;
}
$avg = $sum / count($values);
$error = array();
$max_error = 0;
foreach ($values as $i => $value) {
$error[$i] = abs($avg - $value);
$max_error = max($error[$i], $max_error);
}
$total_weight = 0;
$weighted_sum = 0;
foreach ($values as $i => $value) {
$weight = 1 - ($error[$i] / $max_error);
$weight = $weight * $weight; // square
$total_weight += $weight;
$weighted_sum += $weight * $value;
}
$weighted_average = $weighted_sum / $total_weight;
return $weighted_average;
}
@mindplay-dk
Copy link
Author

Weighted average is great for weeding out "erroneous" readings in a data set - for example:

var_dump(weighted_average(array(7,8,6,9,7,8,8,5,99))); // => ~ 7.29

Notice how the 99 has very little impact on the result - great for calculating average scores, ratings, prices, etc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment