From a761d0e8f2286b832345147fbd545c6e687615a6 Mon Sep 17 00:00:00 2001 From: Arkadiusz Kondas Date: Sun, 8 May 2016 19:23:54 +0200 Subject: [PATCH] mode (dominant) from numbers --- src/Phpml/Math/Statistic/Mean.php | 39 ++++++++++++++++++++++--- tests/Phpml/Math/Statistic/MeanTest.php | 26 ++++++++++++++++- 2 files changed, 60 insertions(+), 5 deletions(-) diff --git a/src/Phpml/Math/Statistic/Mean.php b/src/Phpml/Math/Statistic/Mean.php index 0988e01..9d87a97 100644 --- a/src/Phpml/Math/Statistic/Mean.php +++ b/src/Phpml/Math/Statistic/Mean.php @@ -12,9 +12,13 @@ class Mean * @param array $numbers * * @return float + * + * @throws InvalidArgumentException */ public static function arithmetic(array $numbers) { + self::checkArrayLength($numbers); + return array_sum($numbers) / count($numbers); } @@ -26,11 +30,10 @@ class Mean * @throws InvalidArgumentException */ public static function median(array $numbers) { - $count = count($numbers); - if (0 == $count) { - throw InvalidArgumentException::arrayCantBeEmpty(); - } + self::checkArrayLength($numbers); + + $count = count($numbers); $middleIndex = floor($count / 2); sort($numbers, SORT_NUMERIC); $median = $numbers[$middleIndex]; @@ -42,4 +45,32 @@ class Mean return $median; } + /** + * @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(); + } + } + } diff --git a/tests/Phpml/Math/Statistic/MeanTest.php b/tests/Phpml/Math/Statistic/MeanTest.php index d56f965..289f9a3 100644 --- a/tests/Phpml/Math/Statistic/MeanTest.php +++ b/tests/Phpml/Math/Statistic/MeanTest.php @@ -8,6 +8,15 @@ use Phpml\Math\Statistic\Mean; class MeanTest extends \PHPUnit_Framework_TestCase { + + /** + * @expectedException \Phpml\Exception\InvalidArgumentException + */ + public function testArithmeticThrowExceptionOnEmptyArray() + { + Mean::arithmetic([]); + } + public function testArithmeticMean() { $delta = 0.01; @@ -19,7 +28,7 @@ class MeanTest extends \PHPUnit_Framework_TestCase /** * @expectedException \Phpml\Exception\InvalidArgumentException */ - public function testThrowExceptionOnEmptyArrayMedian() + public function testMedianThrowExceptionOnEmptyArray() { Mean::median([]); } @@ -38,4 +47,19 @@ class MeanTest extends \PHPUnit_Framework_TestCase $this->assertEquals(3.5, Mean::median($numbers)); } + /** + * @expectedException \Phpml\Exception\InvalidArgumentException + */ + public function testModeThrowExceptionOnEmptyArray() + { + Mean::mode([]); + } + + public function testModeOnArray() + { + $numbers = [5, 2, 6, 1, 3, 4, 6, 6, 5]; + + $this->assertEquals(6, Mean::mode($numbers)); + } + }