Create A Running Average Without Storing Individual Values

<!---
	Create an array in which to hold our original set or
	random numbers (for which we will be finding an average).
--->
<cfset randomNumbers = [] />
 
 
<!---
	Now, let's create some random numbers to store in the array.
	We're going to keep the number relatively small since a small
	set will be influenced more per each numbers.
--->
<cfloop
	index="index"
	from="1"
	to="10"
	step="1">
 
	<!--- Add a new, random number to the collection. --->
	<cfset arrayAppend(
		randomNumbers,
		randRange( 1, 10 )
		) />
 
</cfloop>
 
 
<!---
	At this point, we have our number collection. Let's figure
	out the average of this collection, before we add anything
	new. (NOTE: getting count for use later).
--->
 
<!--- Get the number of random numbers we created. --->
<cfset randomCount = arrayLen( randomNumbers ) />
 
<!--- Get the current sum of the collection. --->
<cfset baseAverage = arrayAvg( randomNumbers ) />
 
 
<!---
	Now, let's create a new random number that we want to use
	to update our base average.
--->
<cfset newNumber = randRange( 1, 10 ) />
 
 
<!---
	At this point, we have two options:
 
	1. We can add the new number to the existing collection and
	then take a new average.
 
	2. We can take the existing average of the collection and
	then combine it with the new number in a *weighted* fashion
	such that we only need the average and the count.
--->
 
 
<!--- Method 1: Add number to the collection. --->
<cfset arrayAppend( randomNumbers, newNumber ) />
 
Method 1 Average: #arrayAvg( randomNumbers )#<br />
 
 
<!--- Method 2: Create weighted average based on count. --->
<cfset newAverage = (
	((baseAverage * randomCount) + newNumber) /
	(randomCount + 1)
	) />
 
Method 2 Average: #newAverage#<br />

For Cut-and-Paste