> Anybody got a good averaging algorithm? There's some literature on this in the networking world. A non-worthless TCP implementation keeps track of an average "round trip time", as well as an average variance, and a filter of sorts to prevent assorted erronous results from being used in the caclulations. The basic algorithm is similar to what's already been discussed. First you note that an alternate formula for an average: avg = samp1/N + samp2/N + samp3/N + ... sampN/N You can rearrange this to: avg = sampN/N + (samp1/N + samp2/N...) The second part of this is VERY CLOSE to what you'd get by using N-1 "average" samples: ((N-1) * avg)/N Or (1 - 1/N) * avg So you have: new_avg = sampN/N + ( (1 - 1/N) * avg ) Of course, you can now pick N rather arbitarilly and keep a "running average" by calculating: avg = avg * (1 - 1/N) + sampN/N Now, this would normally be rather problematic to calculate without floating point, and slow to do WITH floating point, so we observe that the smallest fractional value we need to deal with is 1/N, pick N to be a nice power of two, and use what is essentially FIXED POINT fractional numbers, but we'll call keep an integer perspective by modifying the equation. Multiply both sides by N: N*avg = avg * (N-1) + sampN Or N*avg = N*avg - avg + sampN N*avg = N*avg + (sampN - avg) If we store N*avg, we now have one division (shift) and a couple adds rather than anything more complicated, and we keep log2(N) bits of fraction around. Of course, you have to remember to also divide by N whenever you want to access the actual average... Typically, N=8 and you have (c code now!): sampN -= scaledavg>>3; scaledavg += sampN; On an 8 bit microcontroller, it might make sense to use N = 256, so you can do your division by simply selecting the high byte of scaledavg instead of shifting. Hope this makes sense... References: "Round Trip Time Estimation," P. Karn & C. Partridge, ACM SIGCOMM-87, August 1987. "Congestion Avoidance and Control," V. Jacobson, ACM SIGCOMM-88, August 1988. BillW