Moving average or running mean

后端 未结 27 996
庸人自扰
庸人自扰 2020-11-22 08:37

Is there a SciPy function or NumPy function or module for Python that calculates the running mean of a 1D array given a specific window?

27条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 09:16

    If you do choose to roll your own, rather than use an existing library, please be conscious of floating point error and try to minimize its effects:

    class SumAccumulator:
        def __init__(self):
            self.values = [0]
            self.count = 0
    
        def add( self, val ):
            self.values.append( val )
            self.count = self.count + 1
            i = self.count
            while i & 0x01:
                i = i >> 1
                v0 = self.values.pop()
                v1 = self.values.pop()
                self.values.append( v0 + v1 )
    
        def get_total(self):
            return sum( reversed(self.values) )
    
        def get_size( self ):
            return self.count
    

    If all your values are roughly the same order of magnitude, then this will help to preserve precision by always adding values of roughly similar magnitudes.

提交回复
热议问题