From 66dcfcf2b775a0edf01444224a591c9ba75d4bdc Mon Sep 17 00:00:00 2001 From: Arkadiusz Kondas Date: Wed, 27 Apr 2016 23:04:59 +0200 Subject: [PATCH] implement standard deviation of population function --- .../Exception/InvalidArgumentException.php | 18 ++++++++ .../Math/Statistic/StandardDeviation.php | 45 +++++++++++++++++++ src/Phpml/Regression/LeastSquares.php | 10 +++++ .../Math/Statistic/StandardDeviationTest.php | 43 ++++++++++++++++++ 4 files changed, 116 insertions(+) create mode 100644 src/Phpml/Math/Statistic/StandardDeviation.php create mode 100644 tests/Phpml/Math/Statistic/StandardDeviationTest.php diff --git a/src/Phpml/Exception/InvalidArgumentException.php b/src/Phpml/Exception/InvalidArgumentException.php index 428f637..6b10a1a 100644 --- a/src/Phpml/Exception/InvalidArgumentException.php +++ b/src/Phpml/Exception/InvalidArgumentException.php @@ -23,4 +23,22 @@ class InvalidArgumentException extends \Exception { return new self(sprintf('%s must be between 0.0 and 1.0', $name)); } + + /** + * @return InvalidArgumentException + */ + public static function arrayCantBeEmpty() + { + return new self('The array has zero elements'); + } + + /** + * @param int $minimumSize + * + * @return InvalidArgumentException + */ + public static function arraySizeToSmall($minimumSize = 2) + { + return new self(sprintf('The array must have at least %s elements', $minimumSize)); + } } diff --git a/src/Phpml/Math/Statistic/StandardDeviation.php b/src/Phpml/Math/Statistic/StandardDeviation.php new file mode 100644 index 0000000..3c57a4a --- /dev/null +++ b/src/Phpml/Math/Statistic/StandardDeviation.php @@ -0,0 +1,45 @@ +assertEquals(1.825, StandardDeviation::population($population), '', $delta); + + //http://www.stat.wmich.edu/s216/book/node126.html + $delta = 0.5; + $population = [7100, 15500, 4400, 4400, 5900, 4600, 8800, 2000, 2750, 2550, 960, 1025]; + $this->assertEquals(4079, StandardDeviation::population($population), '', $delta); + + $population = [9300, 10565, 15000, 15000, 17764, 57000, 65940, 73676, 77006, 93739, 146088, 153260]; + $this->assertEquals(50989, StandardDeviation::population($population), '', $delta); + } + + /** + * @expectedException \Phpml\Exception\InvalidArgumentException + */ + public function testThrowExceptionOnEmptyArrayIfNotSample() + { + StandardDeviation::population([], false); + } + + /** + * @expectedException \Phpml\Exception\InvalidArgumentException + */ + public function testThrowExceptionOnToSmallArray() + { + StandardDeviation::population([1]); + } + +}