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

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