DEV Community

Discussion on: Calculating a Moving Average on Streaming Data

Collapse
 
sam_ferree profile image
Sam Ferree

I might be missing something, but why not save the sum, and run the update function like so?

update(newValue) {
    this.count++;
    this.sum += newValue;
    this._mean = this.sum/this.count;
}

If you have a problem where a large accumulated value, and a desire for full precision are both in scope, then you simply use a datatype better suited to handle this than float.

Collapse
 
nestedsoftware profile image
Nested Software • Edited

Yes, if you are okay accumulating the sum like this, it’s fine. With floating point values, this approach can have issues, but if it meets your needs (e.g. using a different data type as you mentioned) then it’s okay too. Everything depends on one’s particular use case. As @edA-qa mentioned, the approach I present here can have some problems too when n gets big, so it’s not perfect either. I believe it can in turn be corrected with, for example, something like an exponential moving average, but that’s a whole other story. There are many ways to skin a cat!