median function in statistic

This commit is contained in:
Arkadiusz Kondas 2016-05-08 19:12:39 +02:00
parent b0ab236ab9
commit ed1e07e803
3 changed files with 58 additions and 3 deletions

View File

@ -4,15 +4,42 @@ declare (strict_types = 1);
namespace Phpml\Math\Statistic;
use Phpml\Exception\InvalidArgumentException;
class Mean
{
/**
* @param array $a
* @param array $numbers
*
* @return float
*/
public static function arithmetic(array $a)
public static function arithmetic(array $numbers)
{
return array_sum($a) / count($a);
return array_sum($numbers) / count($numbers);
}
/**
* @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;
}
}

View File

@ -9,6 +9,11 @@ use Phpml\Math\Statistic\Mean;
class MeanStrategy implements Strategy
{
/**
* @param array $currentAxis
*
* @return float
*/
public function replaceValue(array $currentAxis)
{
return Mean::arithmetic($currentAxis);

View File

@ -15,4 +15,27 @@ class MeanTest extends \PHPUnit_Framework_TestCase
$this->assertEquals(41.16, Mean::arithmetic([43, 21, 25, 42, 57, 59]), '', $delta);
$this->assertEquals(1.7, Mean::arithmetic([0.5, 0.5, 1.5, 2.5, 3.5]), '', $delta);
}
/**
* @expectedException \Phpml\Exception\InvalidArgumentException
*/
public function testThrowExceptionOnEmptyArrayMedian()
{
Mean::median([]);
}
public function testMedianOnOddLengthArray()
{
$numbers = [5, 2, 6, 1, 3];
$this->assertEquals(3, Mean::median($numbers));
}
public function testMedianOnEvenLengthArray()
{
$numbers = [5, 2, 6, 1, 3, 4];
$this->assertEquals(3.5, Mean::median($numbers));
}
}