Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何计算几何平均值(pascal或php)_Php_Arrays_Pascal_Average - Fatal编程技术网

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

如何计算几何平均值(pascal或php),php,arrays,pascal,average,Php,Arrays,Pascal,Average,我想在你的支持下解决这个问题。 假设变量$ar中有一个数组,该数组中有5个数字,所以我想通过Pascal或PHP编程语言计算这些数字的几何平均值。我该怎么办?这里是PHP版本: function geometric_average($a) { foreach($a as $i=>$n) $mul = $i == 0 ? $n : $mul*$n; return pow($mul,1/count($a)); } //usage echo geometric_aver

我想在你的支持下解决这个问题。
假设变量$ar中有一个数组,该数组中有5个数字,所以我想通过Pascal或PHP编程语言计算这些数字的几何平均值。我该怎么办?

这里是
PHP
版本:

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
“标准”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.

如果您想使用动态数组,这应该在
Delphi
ObjectPascal
中完成。例如,

对于对此有问题的人,正如我在对PHP答案的评论中所述,该答案可能不适合所有人,特别是对于那些寻找大数或大数的几何平均数/均值的人,因为PHP根本不会存储它

非常简单的解决方案是将初始数组分割成块,计算平均值,然后将它们相乘:

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;
}

请注意
10
-它是块中的元素数,如果需要,您可以更改它。如果您得到
INF
,请尝试降低该值。

非常感谢,这对我很有用,谁能在pascal上实现它?@user1405203:如果您了解该算法,您可以用任何支持浮点数学的语言实现它。你自己试过写Pascal版本吗?注意,
N
数字的几何平均值就是所有数字乘积的第次根。我可以在php上做这个算法,但我的Pascal知识还不足以解决这个问题,据我所知,pascal上不存在foreach循环。@user1405203:经典pascal不支持动态数组(作为标准数据类型)。您可能需要详细说明如何在Pascal中向函数传递参数。(和/或,也许,指定您正在寻找解决方案的Pascal的味道。)