2016-04-27 21:51:14 +00:00
|
|
|
<?php
|
|
|
|
|
2016-11-20 21:53:17 +00:00
|
|
|
declare(strict_types=1);
|
2016-04-27 21:51:14 +00:00
|
|
|
|
|
|
|
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:23:54 +00:00
|
|
|
* @throws InvalidArgumentException
|
2016-04-27 21:51:14 +00:00
|
|
|
*/
|
2017-11-22 21:16:10 +00:00
|
|
|
public static function arithmetic(array $numbers): float
|
2016-04-27 21:51:14 +00:00
|
|
|
{
|
2016-05-08 17:23:54 +00:00
|
|
|
self::checkArrayLength($numbers);
|
|
|
|
|
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
|
|
|
|
|
|
|
/**
|
|
|
|
* @return float|mixed
|
|
|
|
*
|
|
|
|
* @throws InvalidArgumentException
|
|
|
|
*/
|
2016-05-08 17:33:39 +00:00
|
|
|
public static function median(array $numbers)
|
|
|
|
{
|
2016-05-08 17:23:54 +00:00
|
|
|
self::checkArrayLength($numbers);
|
|
|
|
|
|
|
|
$count = count($numbers);
|
2017-08-17 06:50:37 +00:00
|
|
|
$middleIndex = (int) floor($count / 2);
|
2016-05-08 17:12:39 +00:00
|
|
|
sort($numbers, SORT_NUMERIC);
|
|
|
|
$median = $numbers[$middleIndex];
|
|
|
|
|
2017-11-22 21:16:10 +00:00
|
|
|
if ($count % 2 === 0) {
|
2016-05-08 17:12:39 +00:00
|
|
|
$median = ($median + $numbers[$middleIndex - 1]) / 2;
|
|
|
|
}
|
|
|
|
|
|
|
|
return $median;
|
|
|
|
}
|
|
|
|
|
2016-05-08 17:23:54 +00:00
|
|
|
/**
|
|
|
|
* @return mixed
|
|
|
|
*
|
|
|
|
* @throws InvalidArgumentException
|
|
|
|
*/
|
|
|
|
public static function mode(array $numbers)
|
|
|
|
{
|
|
|
|
self::checkArrayLength($numbers);
|
|
|
|
|
|
|
|
$values = array_count_values($numbers);
|
|
|
|
|
2018-02-16 06:25:24 +00:00
|
|
|
return array_search(max($values), $values, true);
|
2016-05-08 17:23:54 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @throws InvalidArgumentException
|
|
|
|
*/
|
2017-11-14 20:21:23 +00:00
|
|
|
private static function checkArrayLength(array $array): void
|
2016-05-08 17:23:54 +00:00
|
|
|
{
|
2018-10-28 06:44:52 +00:00
|
|
|
if (count($array) === 0) {
|
2018-03-03 15:03:53 +00:00
|
|
|
throw new InvalidArgumentException('The array has zero elements');
|
2016-05-08 17:23:54 +00:00
|
|
|
}
|
|
|
|
}
|
2016-04-27 21:51:14 +00:00
|
|
|
}
|