Averages/Simple moving average: Difference between revisions

Content added Content deleted
(Add to description.)
Line 2: Line 2:
Computing the [[wp:Moving_average#Simple_moving_average|simple moving average]] of a series of numbers.
Computing the [[wp:Moving_average#Simple_moving_average|simple moving average]] of a series of numbers.


The task is to:
Create a [[wp:Stateful|stateful]] function/class/instance that takes a number as argument and returns a simple moving average of its arguments so far.
''Create a [[wp:Stateful|stateful]] function/class/instance that takes a number as argument and returns a simple moving average of its arguments so far.''

'''Description'''
A simple moving average is a method for computing an average of a stream of numbers by only averaging the last P numbers from the stream, where P is known as the period. It can be implemented by calling an initialing routine with P as its argument, I(P), which should then return a routine that when called with individual, successive members of a stream of numbers, computes the mean of (up to), the last P of them, lets call this SMA().

The word stateful in the task description refers to the need for SMA() to remember certain information between calls to it:
* The period, P
* An ordered container of at least the last P numbers from each of its individual calls.
Stateful also means that successive calls to I(), the initializer, should return separate routines that do ''not'' share saved state so they could be used on two independent streams of data.

Psudocode for an implementation of SMA is:
<pre>
function SMA(number: N):
stateful integer: P
stateful list: stream
number: average

stream.append_last(N)
if stream.length() > P:
# Only average the last P elements of the stream
stream.delete_first()
if stream.length() == 0:
average = 0
else:
average = sum( stream.values() ) / stream.length()
return average
</pre>


Note that the moving average has a period and numbers beyond the period must be dropped from the calculation of the average. (See the Python example, amongst others, for a correct implementation) .


See also: [[Standard Deviation]]
See also: [[Standard Deviation]]