How to find a running average from an int that changes every frame

I have an int (ie. external sensor value) that changes every frame.
I would like to find a running average over every 10 frames or so, because I am trying to smooth out the occasional erratic values.

What is the simplest way to do this in Unity and how do you store the changing values to calculate an average?

I would store the changing values in a Queue and calculate the average every frame.


The average of 10 values is trivial to calculate performance-wise, but if you really wanted to optimize it, once you hit 10 values and start taking things out of the queue, instead of taking the average of each value, you could subtract 1/10 of the outgoing value (from ten frames ago) from your running total and add 1/10 of the new incoming value (I can’t guarantee this won’t cause weird skewing problems from rounding errors if you do this for a long time, though).

To calculate a Moving Average per the “Cumulative moving average” formula in your link, use the following code:

using UnityEngine;

public class AverageValues : MonoBehaviour
{
    public int NewValue; //this is an example for the value to be averaged
    public int MovingAverageLength = 10; //made public in case you want to change it in the Inspector, if not, could be declared Constant

    private int count;
    private float movingAverage;

	
	// Update is called once per frame
	void Update ()
	{
	    count++;

        //This will calculate the MovingAverage AFTER the very first value of the MovingAverage
        if (count > MovingAverageLength)
	    {
	        movingAverage = movingAverage + (NewValue - movingAverage) / (MovingAverageLength + 1);

            //Debug.Log("Moving Average: " + movingAverage); //for testing purposes

	    }
	    else
	    {
            //NOTE: The MovingAverage will not have a value until at least "MovingAverageLength" values are known (10 values per your requirement)
            movingAverage += NewValue;

            //This will calculate ONLY the very first value of the MovingAverage,
            if (count == MovingAverageLength)
            {
                movingAverage = movingAverage / count;

                //Debug.Log("Moving Average: " + movingAverage); //for testing purposes
            }
        }
		
	}
}

I include the necessary code in a separate class AverageValues for demonstration purposes. Of course you can use the necessary code inside your own class.