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

66 lines
1.3 KiB
PHP
Raw Normal View History

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
*/
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
*/
public static function median(array $numbers)
{
2016-05-08 17:23:54 +00:00
self::checkArrayLength($numbers);
$count = count($numbers);
$middleIndex = (int) floor($count / 2);
2016-05-08 17:12:39 +00:00
sort($numbers, SORT_NUMERIC);
$median = $numbers[$middleIndex];
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);
return array_search(max($values), $values);
}
/**
* @throws InvalidArgumentException
*/
private static function checkArrayLength(array $array): void
2016-05-08 17:23:54 +00:00
{
if (empty($array)) {
2016-05-08 17:23:54 +00:00
throw InvalidArgumentException::arrayCantBeEmpty();
}
}
2016-04-27 21:51:14 +00:00
}