I am trying to create a moving average that:
- Doesn't save previous values.
- Is based on time passed and not number of samples. (we can't control the amount of time inbetween each sample, it can vary based on CPU speed and such).
This is the code I've come up with:
bool init = false;
float average;
TimeDiffer differ = new TimeDiffer();
public float GetAverage(float newValue, float secondsToAverage) {
if(secondsToAverage <= 0.00001f) {
return newValue;
}
if(!init) {
average = newValue;
init = true;
return average;
}
var diff = differ.GetDiffSeconds();
var influence = diff / secondsToAverage;
if(influence >= 1f) {
return newValue;
}
average = average * (1 - influence) + newValue * influence;
return average;
}
Where secondsToAverage is the amount of time it should take for the average to completely change to a new value (this is sent to the function because I don't want to handle it as state). diff is simply the time difference since the last time we called the function.
The idea here is that we calculate how much influence the new value will have based on the time difference for that value. Then we add it together with the previous average.
I haven't found any info on this kind of computation online, so that's why I'm asking about it. I'm just wondering if this makes sense and would work, or if there is a better way to do it?
Thank you