I have an array of numbers like this in PHP:
$numbers = [
0.0021030494216614,
0.0019940179461615,
0.0079320972662613,
0.0040485829959514,
0.0079320972662613,
0.0021030494216614,
0.0019940179461615,
0.0079320972662613,
0.0040485829959514,
0.0079320972662613,
0.0021030494216614,
1.1002979145978,
85.230769230769,
6.5833333333333,
0.015673981191223
];
In PHP, I am trying to find the outliers / anomalies in this array.
As you can see, the anomalies are
1.1002979145978,
85.230769230769,
6.5833333333333,
0.015673981191223
I am trying to find and remove the anomalies in any array.
Here is my code
function remove_anomalies($dataset, $magnitude = 1) {
$count = count($dataset);
$mean = array_sum($dataset) / $count;
$deviation = sqrt(array_sum(array_map("sd_square", $dataset, array_fill(0, $count, $mean))) / $count) * $magnitude;
return array_filter($dataset, function($x) use ($mean, $deviation) { return ($x <= $mean + $deviation && $x >= $mean - $deviation); });
}
function sd_square($x, $mean) {
return pow($x - $mean, 2);
}
However, when I put my array of $numbers in, it only gives me [85.230769230769] as the outlier when there are clearly more outliers there.
I have tried fiddling with the $magnitude and that did not improve anything.