moving average of 3 elements by C or Python
Question: I want to calculate the moving average of 3 elements.

For example, I have a 25 elements of sales data. I need to calculate the
moving average taken from averaging these 25 elements of data.

When a real array is given as data, I want to write a program that will
determines a 3 element moving average and creates an array. The number of
elements in the array becomes 2 elements shorter than the given sequence. For
example, if I am given:

    
    
    [7.0, 9.0, 5.0, 1.0, 3.0]
    

I want to get:

    
    
    [7.0, 5.0, 3.0]
    


Answer: The best (and fastest, by far) way to approach this is
[convolution](https://en.wikipedia.org/wiki/Convolution). Using [numpy's
convolve](http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.convolve.html):

    
    
    import numpy as np
    
    x = np.asarray([7.0, 9.0, 5.0, 1.0, 3.0])
    
    # create what's known as the convolution 'kernel'
    # note that this sums to 1, which results in an average
    kernel = np.ones(3) / 3
    
    # do the convolution to compute the moving average
    moving_avg = np.convolve(x, kernel, mode='valid')
    

You can view the convolution operation as the kernel "sliding" over the data
sequence. Every point `moving_avg[k]` in the output of the convolution will be
the area under the product between your data and the kernel, when the kernel
is centered at that point `k`.

This is an animation (from the wikipedia article linked above) illustrating
the principle for the square kernel used in moving average computation:

[![enter image description
here](http://i.stack.imgur.com/9truS.gif)](http://i.stack.imgur.com/9truS.gif)

