Calculating exponential moving averages I'm wanting to calculate exponential moving averages of a variable, distance. Is the logic (and math) correct in the below code?

time and lastTime are millisecond-precise timestamps in seconds – the former is the current time, the latter is the time of the last calculations.

lastA etc are the exponential moving averages from the last calculations.

a etc will be left with the calculated exponential moving averages.

var distance = ...;
var a = Math.pow(1.16, -(time-lastTime)),
    b = Math.pow(1.19, -(time-lastTime)),
    c = Math.pow(1.22, -(time-lastTime)),
    d = Math.pow(1.26, -(time-lastTime)),
    e = Math.pow(1.30, -(time-lastTime)),
    f = Math.pow(1.35, -(time-lastTime)),
    g = Math.pow(1.40, -(time-lastTime));
a = a*lastA + (1-a)*distance;
b = b*lastB + (1-b)*distance;
c = c*lastC + (1-c)*distance;
d = d*lastD + (1-d)*distance;
e = e*lastE + (1-e)*distance;
f = f*lastF + (1-f)*distance;
g = g*lastG + (1-g)*distance;
This is border line a bad question, as not enough code is given to properly review it.

The variables a -> g look terrible, I would create an array with the numbers you need:

var dataPoints = [1.16,1.19,1.22,1.26,1.30,1.35,1.40];


Then I would would loop over those points and create an averages object

var averages = {},
    value, x;
for(var i = 0, length = dataPoints.length ; i &lt; length ; i++ ){
  value = dataPoints[i];
  x = Math.pow(value, -(time-lastTime));
  averages[value] = x * lastAverages[value] + (1-x) * distance;
}


I cannot tell whether the math is correct, if it is not correct, then this question does not belong here :)