Created
February 14, 2014 15:20
-
-
Save mindplay-dk/9002874 to your computer and use it in GitHub Desktop.
Computing weighted average from a set of values
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
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Weighted average is great for weeding out "erroneous" readings in a data set - for example:
Notice how the 99 has very little impact on the result - great for calculating average scores, ratings, prices, etc.