moving average of 3 elements by C or Python

2019-07-26 09:38发布

问题:

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]

回答1:

You could use a Python deque for doing this as follows:

from collections import deque

prices = [7.0, 9.0, 5.0, 1.0, 3.0]
moving_average = deque()
total = 0.0
days = 3
averages = []

for price in prices:
    moving_average.append(price)
    total += price

    if len(moving_average) > days:      # Length of moving average
        total -= moving_average.popleft()

    averages.append(total / float(len(moving_average)))

print averages

This would display the following output:

[7.0, 8.0, 7.0, 5.0, 3.0]

Or you could skip the initial entries as follows:

print averages[days-1:]

Giving:

[7.0, 5.0, 3.0]


回答2:

The best (and fastest, by far) way to approach this is convolution. Using numpy's convolve:

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:



回答3:

A list comprehension is a pythonic way to do this, that does not require any import:

>>> a
[7, 9, 5, 1, 3]
>>> [(a[i]+a[i+1]+a[i+2])/3.0 for i in xrange(len(a)-2)]
[7.0, 5.0, 3.0]