如何计算几何平均值(pascal或php)

I wanna solve this problem with your support. Assume that, there is an array in variable named $ar, and exist 5 numbers in this array, so i want to calculate geometric average of these numbers through Pascal or PHP programming language. How can i do ?

Here is PHP version:

function geometric_average($a) {  
   foreach($a as $i=>$n) $mul = $i == 0 ? $n : $mul*$n;  
   return pow($mul,1/count($a));  
}

//usage
echo geometric_average(array(2,8)); //Output-> 4

Possible solution in "standard" Pascal:

program GeometricAvarage;

const SIZE = 5;

function GeoAvg(A:array of real):real;
var
  avg: real;
  i: integer;

begin
avg := 1;
for i:=0 to (SIZE) do
  avg := avg * A[i];
avg :=Exp(1/SIZE*Ln(avg));
Result:=avg;
end;

begin

var
ar: array [1..SIZE] of real :=(1,2,3,4,5);

writeln('Geometric Avarage = ', GeoAvg(ar)); {Output should be =~2.605}
readln;
end.

If you want to use dynamic arrays this should be done in Delphi or ObjectPascal for example.

For someone that had an issue with this, as I have stated in the comment to the PHP answer, that answer may not be suitable for everyone, especially with ones looking to find geometric average/mean for large numbers or large number of numbers as PHP will simply not store it.

Pretty easy solution is to split the initial array into chunks, calculate mean and then multiply them:

function geometricMean(array $array)
{
    if (!count($array)) {
        return 0;
    }

    $total = count($array);
    $power = 1 / $total;

    $chunkProducts = array();
    $chunks = array_chunk($array, 10);

    foreach ($chunks as $chunk) {
        $chunkProducts[] = pow(array_product($chunk), $power);
    }

    $result = array_product($chunkProducts);
    return $result;
}

Note the 10 - it's the number of elements in a chunk, you may change that if you need to do so. If you get INF as a result, try lowering that.