Skip to content

Commit

Permalink
median function in statistic
Browse files Browse the repository at this point in the history
  • Loading branch information
akondas committed May 8, 2016
1 parent b0ab236 commit ed1e07e
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 3 deletions.
33 changes: 30 additions & 3 deletions src/Phpml/Math/Statistic/Mean.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,42 @@

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;
}

}
5 changes: 5 additions & 0 deletions src/Phpml/Preprocessing/Imputer/Strategy/MeanStrategy.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@

class MeanStrategy implements Strategy
{
/**
* @param array $currentAxis
*
* @return float
*/
public function replaceValue(array $currentAxis)
{
return Mean::arithmetic($currentAxis);
Expand Down
23 changes: 23 additions & 0 deletions tests/Phpml/Math/Statistic/MeanTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,27 @@ public function testArithmeticMean()
$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));
}

}

0 comments on commit ed1e07e

Please sign in to comment.