ndeblauw wrote a reply+100 XP
5mos ago
Weighted average => what's the easiest and more performant way ?
I would go for a simpler approach...
$collection = collect([
['value' => 10, 'coefficient' => 2],
['value' => 20, 'coefficient' => 3],
['value' => 30, 'coefficient' => 4],
]);
$temp = $collection->map( fn($x) => [
'weight' => $x['coefficient'],
'weighted_value' => $x['value'] * $x['coefficient']
]);
$weightedAverage = $temp->sum('weighted_value') / $temp->sum('weight');
echo $weightedAverage; // Output: 22.222222222
Not sure whether it is computationally more heavy or not (please comment @larry), but from readability it is more clear. And the output is correct ;-)