Averages/Simple moving average: Difference between revisions

Line 1,391:
</lang>
 
Example: <br>
movinavg({1,2,3,4,5,6,7,8,9,10},5)<br>
 
list is the list being averaged: {1,2,3,4,5,6,7,8,9,10}<br>
p is the period: 5<br>
returns the averaged list: {1, 3/2, 2, 5/2, 3, 4, 5, 6, 7, 8}<br><br>
 
In the function:<br>
variable r - is the result (the averaged list) that will be returned<br>
variable i - is the index variable, and it points to the end of the sub-list the list being averaged.<br>
variable z - an helper variable<br>
<br>
The function uses variable i to determine which values of the list will be considered in the next average calculation.<br>
At every iteration, variable i points to the last value in the list that will be used in the average calculation. <br>
So we only need to figure out which will be the first value in the list.<br>
Usually we'll have to consider p elements, so the first element will be the one indexed by (i-p+1).<br>
However on the first iterations that calculation will usually be negative, so the following equation will avoid negative indexes: max(i-p+1,1) or, arranging the equation, max(i-p,0)+1.<br>
But the number of elements on the first iterations will also be smaller, the correct value will be (end index - begin index + 1) or (i - (max(i-p,0)+1) +1) or (i-max(i-p,0)).<br>
Variable z holds the common value (max(i-p),0) so the begin_index will be (z+1) and the number_of_elements will be (i-z)<br>
 
mid(list,z+1, i-z) will return the list of value that will be averaged<br>
sum(...) will sum them<br>
sum(...)/(i-z) will average them<br>
Anonymous user