Averages/Simple moving average: Difference between revisions

Line 4,250:
sum(...)/(i-z) → r[i] will average them and store the result in the appropriate place in the result list<br>
 
=={{header|VBA}}==
This is a "simple" moving average.
<lang vb>Class sma
'to be stored in a class module with name "sma"
Private n As Integer 'period
Private arr() As Double 'circular list
Private index As Integer 'pointer into arr
Private oldsma As Double
 
Public Sub init(size As Integer)
n = size
ReDim arr(n - 1)
index = 0
End Sub
 
Public Function sma(number As Double) As Double
sma = oldsma + (-arr(index) + number) / n
oldsma = sma
arr(index) = number
index = (index + 1) Mod n
End Function
 
Normal module
Public Sub main()
s = [{1,2,3,4,5,5,4,3,2,1}]
Dim sma3 As New sma
Dim sma5 As New sma
sma3.init 3
sma5.init 5
For i = 1 To UBound(s)
Debug.Print i, Format(sma3.sma(CDbl(s(i))), "0.00000"),
Debug.Print Format(sma5.sma(CDbl(s(i))), "0.00000")
Next i
End Sub</lang>{{out}}
<pre> 1 0,33333 0,20000
2 1,00000 0,60000
3 2,00000 1,20000
4 3,00000 2,00000
5 4,00000 3,00000
6 4,66667 3,80000
7 4,66667 4,20000
8 4,00000 4,20000
9 3,00000 3,80000
10 2,00000 3,00000</pre>
=={{header|VBScript}}==
<lang vb>data = "1,2,3,4,5,5,4,3,2,1"
255

edits