RosettaCodeData/Task/Averages-Simple-moving-average/00-TASK.txt

44 lines
1.9 KiB
Plaintext

Computing the [[wp:Moving_average#Simple_moving_average|simple moving average]] of a series of numbers.
;Task
Create a [[wp:Stateful|stateful]] function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
{{task heading|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.
<br>
''Stateful'' &nbsp; also means that successive calls to &nbsp; I(), &nbsp; the initializer, &nbsp; should return separate routines that do &nbsp; ''not'' &nbsp; share saved state so they could be used on two independent streams of data.
Pseudo-code for an implementation of &nbsp; SMA &nbsp; 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>
{{task heading|See also}}
{{Related tasks/Statistical measures}}
<hr>