Created
January 21, 2018 13:29
Высчитываение средней медианы
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Высчитываение средней медианы | |
@params array массив чисел | |
*/ | |
function array_median($array) { | |
// perhaps all non numeric values should filtered out of $array here? | |
$iCount = count($array); | |
if ($iCount == 0) { | |
throw new Exception('Median of an empty array is undefined'); | |
} | |
// if we're down here it must mean $array | |
// has at least 1 item in the array. | |
$middle_index = floor($iCount / 2); | |
sort($array, SORT_NUMERIC); | |
$median = $array[$middle_index]; // assume an odd # of items | |
// Handle the even case by averaging the middle 2 items | |
if ($iCount % 2 == 0) { | |
$median = ($median + $array[$middle_index - 1]) / 2; | |
} | |
return $median; | |
} | |
// пример | |
echo array_median([12, 16, 80, 70, 11, 14, 13, 20, 10]); // => 14 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment