Cumulative Moving Average in PHP

My brother needed to figure out how to do a “moving average” in some code he was writing a while ago. I’d never done this before and couldn’t find any really simple code examples so ended up on Wikipedia where I found it’s actually called a cumulative moving average.

Super simple code example follows:

<?php
$numbers = array(1,2,3,4);

// A simple function to calculate averages
function average($array)
{
	return (array_sum($array) / count($array));
}

/*
 * Simple function to calculate moving average with the following parameters
 * $datapoint - the most recently acquired new datapoint
 * $average - the current average
 * $count - the total number of items we're dealing with
 */
function cumulativeAverage($datapoint, $average, $count)
{
	return $average + (($datapoint - $average) /  $count);
}


// First let's print the average calculated normally so we can compare to the final result
print "Normal average:\t\t".average($numbers)."\n";


// $lastav stores the most recently calculated average
$lastav = 0;

// Loop through all the numbers in the array and calculate the cumulative average each time
for ($i = 0; $i<sizeof($numbers);$i++)
{
	$lastav = cumulativeAverage($numbers[$i], $lastav, $i+1);
}

print "Cumulative Average:\t".$lastav."\n";

>>

2 thoughts on “Cumulative Moving Average in PHP”

  1. Funnily enough I’ve had to use a cumulative moving average too. Here’s the method I used to calculate the average tournament bias over 1000’s of tournaments:
    AverageBiasedFinish = ((AverageBiasedFinish*(TourneyCount-1))+BiasedFinish)/TourneyCount

    Your method of finding the difference is neater, however I was also playing around with exponential moving averages like:
    AverageBiasedFinish = ((AverageBiasedFinish*9+BiasedFinish)/10

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.