我试图弄清楚如何计算随机生成的数字数组的中位数。我已设置好数组,但在组合计算函数时遇到问题。
这是我到目前为止所拥有的:
//array
$lessFifty = array();
$moreFifty = array();
//number generation
for ($i = 0; $i<=30; $i++) {
$number = rand(0, 100);
//Sorting <50>
if ($number < 50 ) {
$lessFifty[] = $number;
} else {
$moreFifty[] = $number;
}
}
echo print_r($lessFifty);
echo "<br>" ;
echo print_r($moreFifty);
//Average
echo "<p> Average of values less than fifty: </p>";
print array_sum($lessFifty) / count($lessFifty) ;
echo "<p> Average of values greater than fifty: </p>" ;
print array_sum($moreFifty) / count($moreFifty) ;
//Median
$func = function (median ($array, $output = $median)){
if(!is_array($array)){
return FALSE;
}else{
switch($output){
rsort($array);
$middle = round(count($array) 2);
$total = $array[$middle-1];
break;
return $total;
}
}
echo $func ;
我很确定我做的这个中位数部分完全错误。我只是在学习,事实证明这是一个挑战。
请注意如何编写
for()
循环。如果您想要 30 个条目,则不应使用 <=
,否则最终会得到 31 个,因为 $i
从 0 开始。
构建随机数数组,然后对它们进行排序。
然后确定是否有一个中心条目(奇数数组长度)或者是否需要平均中间两个条目(偶数数组长度)。
这是 2022 年在 CodeReview 上发布的中值方法的现代实现。
代码:(演示)
$limit = 30; // how many random numbers do you want? 30 or 31?
for ($i = 0; $i < $limit; ++$i) {
$numbers[] = rand(0, 100);
}
var_export($numbers);
//echo "\n---\nAverage: " , array_sum($numbers) / $limit;
echo "\n---\n";
sort($numbers);
$count = count($numbers); // cache the count
$index = intdiv($count, 2); // cache the index
if (!$count) {
echo "no values";
} elseif ($count & 1) { // count is odd
echo $numbers[$index];
} else { // count is even
echo ($numbers[$index-1] + $numbers[$index]) / 2;
}
可能的输出:
array (
0 => 27,
1 => 24,
2 => 84,
3 => 43,
4 => 8,
5 => 51,
6 => 60,
7 => 86,
8 => 9,
9 => 48,
10 => 67,
11 => 20,
12 => 44,
13 => 85,
14 => 6,
15 => 63,
16 => 41,
17 => 32,
18 => 64,
19 => 73,
20 => 43,
21 => 24,
22 => 15,
23 => 19,
24 => 9,
25 => 93,
26 => 88,
27 => 77,
28 => 11,
29 => 54,
)
---
43.5
排序后,元素
[14]
和[15]
分别持有43
和44
。这些“中间两个”值的平均值就是确定结果的方式。 (硬编码数字演示)
如果您想要一个简短的、不灵活的硬编码片段,那么您可以使用
30
和 14
和 15
作为您的预定大小和索引。
for ($i = 0; $i < 30; ++$i) {
$numbers[] = rand(0, 100);
}
sort($numbers);
echo ($numbers[14] + $numbers[15]) / 2;
我喜欢这个函数,因为我发现它非常可读,而且逻辑很容易理解:
function calculateMedian($array) {
if (empty($array)) {
return null;
} else {
sort($array);
$length = count($array);
$middle_index = floor(($length - 1) / 2);
if ($length % 2) {
return $array[$middle_index];
} else {
$low = $array[$middle_index];
$high = $array[$middle_index + 1];
return ($low + $high) / 2;
}
}
}
或者,这个函数更简洁,但可读性较差:
function calculateMedian($array) {
if (empty($array)) {
return null;
} else {
sort($array);
$lowMiddle = $array[floor((count($array) - 1) / 2)];
$highMiddle = $array[ceil((count($array) - 1) / 2)];
return ($lowMiddle + $highMiddle) / 2;
}
}