Jump to content

Averages/Simple moving average: Difference between revisions

added MiniScript example
(Added Dyalect programming language)
(added MiniScript example)
Line 2,445:
 
Some notes about this solution: unless P = 0, length(L) can never be 0, as L always incorporates at least N (a step that is accomplished in the arguments to list.take_upto/3). If the implementation of the 'state' type is hidden, and if init/1 checks for P = 0, users of this code can never cause a division-by-zero error in sma/4. Although this solution doesn't try to be as stateful as the task description would like, explicit state is by far simpler and more natural and more straightforward than the alternative in Mercury. Finally, [http://www.mercury.csse.unimelb.edu.au/information/doc-release/mercury_ref/State-variables.html#State-variables state variables] (and higher-order functions that anticipate threaded state) remove much of the potential ugliness or error in threading the same state through many users.
 
=={{header|MiniScript}}==
 
We define an SMA class, which can be configured with the desired window size (P).
<lang MiniScript>SMA = {}
SMA.P = 5 // (a default; may be overridden)
SMA.buffer = null
SMA.next = function(n)
if self.buffer == null then self.buffer = []
self.buffer.push n
if self.buffer.len > self.P then self.buffer.pull
return self.buffer.sum / self.buffer.len
end function
 
sma3 = new SMA
sma3.P = 3
sma5 = new SMA
 
for i in range(10)
num = round(rnd*100)
print "num: " + num + " sma3: " + sma3.next(num) + " sma5: " + sma5.next(num)
end for</lang>
 
{{out}}
<pre>num: 81 sma3: 81 sma5: 81
num: 82 sma3: 81.5 sma5: 81.5
num: 78 sma3: 80.333333 sma5: 80.333333
num: 54 sma3: 71.333333 sma5: 73.75
num: 94 sma3: 75.333333 sma5: 77.8
num: 8 sma3: 52 sma5: 63.2
num: 40 sma3: 47.333333 sma5: 54.8
num: 98 sma3: 48.666667 sma5: 58.8
num: 48 sma3: 62 sma5: 57.6
num: 41 sma3: 62.333333 sma5: 47
num: 94 sma3: 61 sma5: 64.2</pre>
 
 
=={{header|NetRexx}}==
222

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.