Monday, July 24, 2006

Hey, it Works!

The Problem: Creating a geometric mean function for PHP.

First Attempt: Just doing something along the lines of (p1 * p2 * ... * pn) ^ (1/n) . However, even PHP has its limits, and for high n's (we're talking along the lines of hundreds or even thousands), it would just die on us. We needed a better way!

The Solution: Logarithms, yes, logarithms. With basic identities, we find that (p1 * p2 * ... * pn) ^ (1/n) = 10 ^ (1/n * log p1 + log p2 + ... + log pn) ! Now instead of multiplying huge numbers, we're just adding them!

By the way, here's the full function - feel free to it in your own PHP experiments (courtesy myself and Mgccl):

function func_math_mean()
{
$elo = func_get_args();
$num = 0;
foreach ($elo as $value) {
if ($value == 0){
$value = 1;
}
$num = $num + log10($value);
}
$count = func_num_args();
$num = pow(10,$num / $count);
return $num;
}

No comments: