average


See On Github

Data

Contributor

Generic placeholder thumbnail

by jakobhans

in php

Tags

Source Code

<?php

    // Arithmetic Mean
    function arithmeticMean($numbers)
    {
        return (array_sum($numbers) / count($numbers));
    }

    function geometricMean($numbers)
    {
        $multiplier = 1;

        foreach ($numbers as $num) {
            $multiplier *= $num;
        }

        return (pow($multiplier, 1/count($numbers)));
    }

    function harmonicMean($numbers)
    {
        $sum = 0;

        foreach ($numbers as $num) {
            $sum += 1/$num;
        }

        return (count($numbers) / $sum);
    }

    function quadraticMean($numbers)
    {
        $sum = 0;

        foreach ($numbers as $num) {
            $sum += pow($num, 2);
        }

        return (sqrt(1/count($numbers) * $sum));
    }

    function generalizedMean($numbers, $power)
    {
        $sum = 0;

        foreach ($numbers as $num) {
            $sum += pow($num, $power);
        }

        return (pow((1/count($numbers) * $sum), 1/$power));
    }

    function weightedMean($values, $weights)
    {
        $sum = 0;

        for ($i = 0; $i < count($values); $i++) {
            $sum += $values[$i] * $weights[$i];
        }

        return ($sum / array_sum($weights));
    }

    function midrangeMean($values)
    {
        return (0.5 * (min($values) + max($values)));
    }

?>
<?php

require('Average.php');

class AverageTest extends PHPUnit_Framework_TestCase {

    private $test_array = array(3, 28, 54, 4, 98, 55, 102, 17, 39, 71);
    private $test_power = 17;
    private $test_weights = array(0.05, 0.2, 0.1, 0.05, 0.4, 0.01, 0.09, 0.03, 0.05, 0.02);

    public function testHarmonicMean()
    {
        $result = harmonicMean($this->test_array);
        $this->assertInternalType("float", $result);
    }

    public function testQuadraticMean()
    {
        $result = quadraticMean($this->test_array);
        $this->assertInternalType("float", $result);
    }

    public function testGeneralizedMean()
    {
        $result = generalizedMean($this->test_array, $this->test_power);
        $this->assertInternalType("float", $result);
    }

    public function testWeightedMean()
    {
        $result = weightedMean($this->test_array, $this->test_weights);
        $this->assertInternalType("float", $result);
    }

    public function testMidrangeMean()
    {
        $result = midrangeMean($this->test_array);
        $this->assertInternalType("float", $result);
    }
}