php-ml/src/Phpml/Math/Statistic/Mean.php

46 lines
901 B
PHP
Raw Normal View History

2016-04-27 21:51:14 +00:00
<?php
declare (strict_types = 1);
namespace Phpml\Math\Statistic;
2016-05-08 17:12:39 +00:00
use Phpml\Exception\InvalidArgumentException;
2016-04-27 21:51:14 +00:00
class Mean
{
/**
2016-05-08 17:12:39 +00:00
* @param array $numbers
2016-04-27 21:51:14 +00:00
*
* @return float
*/
2016-05-08 17:12:39 +00:00
public static function arithmetic(array $numbers)
2016-04-27 21:51:14 +00:00
{
2016-05-08 17:12:39 +00:00
return array_sum($numbers) / count($numbers);
2016-04-27 21:51:14 +00:00
}
2016-05-08 17:12:39 +00:00
/**
* @param array $numbers
*
* @return float|mixed
*
* @throws InvalidArgumentException
*/
public static function median(array $numbers) {
$count = count($numbers);
if (0 == $count) {
throw InvalidArgumentException::arrayCantBeEmpty();
}
$middleIndex = floor($count / 2);
sort($numbers, SORT_NUMERIC);
$median = $numbers[$middleIndex];
if (0 == $count % 2) {
$median = ($median + $numbers[$middleIndex - 1]) / 2;
}
return $median;
}
2016-04-27 21:51:14 +00:00
}