Averages/Simple moving average: Difference between revisions

m
(Added Quackery.)
imported>Arakov
(11 intermediate revisions by 10 users not shown)
Line 3:
Computing the [[wp:Moving_average#Simple_moving_average|simple moving average]] of a series of numbers.
 
;Task
{{task heading}}
 
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.
Line 46:
=={{header|11l}}==
{{trans|D}}
<langsyntaxhighlight lang="11l">T SMA
[Float] data
sum = 0.0
Line 68:
 
L(e) [1, 2, 3, 4, 5, 5, 4, 3, 2, 1]
print(‘Added #., sma(3) = #.6, sma(5) = #.6’.format(e, sma3.add(e), sma5.add(e)))</langsyntaxhighlight>
{{out}}
<pre>
Line 85:
=={{header|360 Assembly}}==
{{trans|PL/I}}
<langsyntaxhighlight lang="360asm">* Averages/Simple moving average 26/08/2015
AVGSMA CSECT
USING AVGSMA,R12
Line 172:
EDMASK DC X'4020202020202021204B202020' CL13
YREGS
END AVGSMA</langsyntaxhighlight>
{{out}}
<pre>
Line 193:
 
moving.ads:
<langsyntaxhighlight Adalang="ada">generic
Max_Elements : Positive;
type Number is digits <>;
Line 200:
function Moving_Average (N : Number) return Number;
function Get_Average return Number;
end Moving;</langsyntaxhighlight>
 
moving.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Containers.Vectors;
 
package body Moving is
Line 242:
end Moving_Average;
 
end Moving;</langsyntaxhighlight>
 
main.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
with Moving;
procedure Main is
Line 263:
" into max-5: " & Float'Image (Five_Average.Moving_Average (Float (I))));
end loop;
end Main;</langsyntaxhighlight>
 
{{out}}
Line 296:
<!-- {{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8.8d.fc9.i386]}} -->
Note: This following code is a direct translation of the [[Average/Simple_moving_average#C|C]] code sample. It mimics C's var_list implementation, and so it probably isn't the most natural way of dong this actual task in '''ALGOL 68'''.
<langsyntaxhighlight Algol68lang="algol68">MODE SMAOBJ = STRUCT(
LONG REAL sma,
LONG REAL sum,
Line 383:
sma(SMAFREE(h5))
#
)</langsyntaxhighlight>
{{out}}
<pre>
Line 401:
ahk forum: [http://www.autohotkey.com/forum/post-276695.html#276695 discussion]
For Integers:
<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox % MovingAverage(5,3) ; 5, averaging length <- 3
MsgBox % MovingAverage(1) ; 3
MsgBox % MovingAverage(-3) ; 1
Line 418:
v%i% := x, i := mod(i+1,m) ; remember last m inputs, cycle insertion point
Return sum/n
}</langsyntaxhighlight>
For floating point numbers:
<langsyntaxhighlight AutoHotkeylang="autohotkey">MovingAverage(x,len="") { ; for floating point numbers
Static
Static n:=0, m:=10 ; default averaging length = 10
Line 430:
j := A_Index-1, sum += v%j%
Return sum/n
}</langsyntaxhighlight>
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk">#!/usr/bin/awk -f
# Moving average over the first column of a data file
BEGIN {
Line 445:
Z[i] = x;
print MA;
}</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> MAXPERIOD = 10
FOR n = 1 TO 5
PRINT "Number = ";n TAB(12) " SMA3 = ";FNsma(n,3) TAB(30) " SMA5 = ";FNsma(n,5)
Line 466:
index%(period%) = (index%(period%) + 1) MOD period%
IF window%(period%)<period% window%(period%) += 1
= accum(period%) / window%(period%)</langsyntaxhighlight>
{{out}}
<pre>
Line 512:
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">( ( I
= buffer
. (new$=):?freshEmptyBuffer
Line 549:
$ (str$(!k " - sma3:" pad$(sma3$!k) " sma5:" pad$(sma5$!k)))
)
);</langsyntaxhighlight>
{{out}}
<pre>1 - sma3: 1 sma5: 1
Line 564:
=={{header|Brat}}==
Object version
<langsyntaxhighlight lang="brat">
SMA = object.new
 
Line 585:
[1, 2, 3, 4, 5, 5, 4, 3, 2, 1].each { n |
p n, " - SMA3: ", sma3.add(n), " SMA5: ", sma5.add(n)
}</langsyntaxhighlight>
 
Function version
 
<langsyntaxhighlight lang="brat">sma = { period |
list = []
 
Line 605:
[1, 2, 3, 4, 5, 5, 4, 3, 2, 1].each { n |
p n, " - SMA3: ", sma3(n), " SMA5: ", sma5(n)
}</langsyntaxhighlight>
 
{{out}}
Line 620:
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
Line 688:
va_end(vl);
return r;
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="c">double v[] = { 1, 2, 3, 4, 5, 5, 4, 3, 2, 1 };
 
int main()
Line 707:
sma(SMA_FREE, h5);
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
Line 713:
{{works with|C sharp|C#|3}}
 
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 742:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 759:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <stddef.h>
Line 861:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|Clojure}}==
This version uses a persistent queue to hold the most recent ''p'' values.
Each function returned from ''init-moving-average'' has its state in an atom holding a queue value.
<langsyntaxhighlight lang="clojure">(import '[clojure.lang PersistentQueue])
 
(defn enqueue-max [q p n]
Line 877:
(let [state (atom PersistentQueue/EMPTY)]
(fn [n]
(avg (swap! state enqueue-max p n)))))</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
I = (P) ->
# The cryptic name "I" follows the problem description;
Line 925:
for i in [1..10]
console.log i, sma3(i), sma7(i), sma11(i)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 945:
This implementation uses a circular list to store the numbers within the window; at the beginning of each iteration <var>pointer</var> refers to the list cell which holds the value just moving out of the window and to be replaced with the just-added value.
 
<langsyntaxhighlight lang="lisp">(defun simple-moving-average (period &aux
(sum 0) (count 0) (values (make-list period)) (pointer values))
(setf (rest (last values)) values) ; construct circularity
Line 955:
(setf (first pointer) n)
(setf pointer (rest pointer)) ; advance pointer
(/ sum (min count period))))</langsyntaxhighlight>
 
Use
 
<langsyntaxhighlight lang="lisp">(mapcar '(simple-moving-average period) list-of-values)</langsyntaxhighlight>
 
=={{header|Crystal}}==
<langsyntaxhighlight lang="ruby">def sma(n) Proc(Float64, Float64)
a = Array(Float64).new
->(x : Float64) {
Line 976:
(1.upto(5).to_a + 5.downto(1).to_a).each do |n|
printf "%d: sma3 = %.3f - sma5 = %.3f\n", n, sma3.call(n.to_f), sma5.call(n.to_f)
end</langsyntaxhighlight>
 
<pre>
Line 994:
===Using a Closure===
Currently this <code>sma</code> can't be @nogc because it allocates a closure on the heap. Some escape analysis could remove the heap allocation.
<langsyntaxhighlight lang="d">import std.stdio, std.traits, std.algorithm;
 
auto sma(T, int period)() pure nothrow @safe {
Line 1,016:
foreach (immutable e; [1, 2, 3, 4, 5, 5, 4, 3, 2, 1])
writefln("Added %d, sma(3) = %f, sma(5) = %f", e, s3(e), s5(e));
}</langsyntaxhighlight>
{{out}}
<pre>Added 1, sma(3) = 1.000000, sma(5) = 1.000000
Line 1,033:
keeping the data in the stack frame of the main function.
Same output:
<langsyntaxhighlight lang="d">import std.stdio, std.traits, std.algorithm;
 
struct SMA(T, int period) {
Line 1,055:
foreach (immutable e; [1, 2, 3, 4, 5, 5, 4, 3, 2, 1])
writefln("Added %d, sma(3) = %f, sma(5) = %f", e, s3(e), s5(e));
}</langsyntaxhighlight>
To avoid the floating point approximations keep piling up and growing, the code could perform a periodic sum on the whole circular queue array.
=={{header|Delphi}}==
{{Trans|Pascal}}
Small variation of [[#Pascal]].
<syntaxhighlight lang="delphi">
<lang Delphi>
program Simple_moving_average;
 
Line 1,143:
 
Readln;
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 1,163:
{{trans|C#}}
 
<langsyntaxhighlight lang="dyalect">func avg(xs) {
var acc = 0.0
var c = 0
Line 1,184:
}
var nums = Iterator.Concat(1.0..5.0, 5.0^-1.0..1.0)
var sma3 = sma(3)
var sma5 = sma(5)
Line 1,190:
for n in nums {
print("\(n)\t(sma3) \(sma3(n))\t(sma5) \(sma5(n))")
}</langsyntaxhighlight>
 
=={{header|E}}==
Line 1,200:
The structure is the same as the implementation of [[Standard Deviation#E]].
 
<langsyntaxhighlight lang="e">pragma.enable("accumulator")
def makeMovingAverage(period) {
def values := ([null] * period).diverge()
Line 1,221:
return [insert, average]
}</langsyntaxhighlight>
 
<div style="overflow: auto; max-height: 12em;"><langsyntaxhighlight lang="e">? for period in [3, 5] {
> def [insert, average] := makeMovingAverage(period)
> println(`Period $period:`)
Line 1,255:
3 4.2
2 3.8
1 3.0</langsyntaxhighlight></div>
 
=={{header|EasyLang}}==
<syntaxhighlight>
prefix sma_
global p[] ind[] sum[] smpl[][] .
func new p .
p[] &= p
ind[] &= 0
sum[] &= 0
smpl[][] &= [ ]
return len p[]
.
func get id x .
ind[id] = (ind[id] + 1) mod1 p[id]
ind = ind[id]
if len smpl[id][] < ind
len smpl[id][] ind
else
sum[id] -= smpl[id][ind]
.
sum[id] += x
smpl[id][ind] = x
return sum[id] / len smpl[id][]
.
prefix
#
sma5 = sma_new 5
sma3 = sma_new 3
numfmt 2 4
for v in [ 1 2 3 4 5 5 4 3 2 1 ]
print sma_get sma3 v & " " & sma_get sma5 v
.
</syntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(lib 'tree) ;; queues operations
 
Line 1,269 ⟶ 1,302:
(// (for/sum ((x (queue->list Q))) x) (queue-length Q))))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,291 ⟶ 1,324:
 
=={{header|Elena}}==
ELENA 56.0x :
<langsyntaxhighlight lang="elena">import system'routines;
import system'collections;
import extensions;
Line 1,314 ⟶ 1,347:
count =>
0 { ^0.0r }
:! {
if (count > thePeriod)
{
theList.removeAt:(0);
count := thePeriod
Line 1,328 ⟶ 1,361:
}
}
 
// --- Program ---
 
public program()
{
var SMA3 := SMA.new:(3);
var SMA5 := SMA.new:(5);
 
for (int i := 1,; i <= 5,; i += 1) {
console.printPaddingRight(30, "sma3 + ", i, " = ", SMA3.append:(i));
console.printLine("sma5 + ", i, " = ", SMA5.append:(i))
};
 
for (int i := 5,; i >= 1,; i -= 1) {
console.printPaddingRight(30, "sma3 + ", i, " = ", SMA3.append:(i));
console.printLine("sma5 + ", i, " = ", SMA5.append:(i))
};
console.readChar()
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,363 ⟶ 1,398:
The elixir program below generates an anonymous function with an embedded period `p`, which is used as the period of the simple moving average. The `run` function reads numeric input and passes it to the newly created anonymous function, and then "inspects" the result to STDOUT.
 
<langsyntaxhighlight lang="elixir">$ cat simple-moving-avg.exs
#!/usr/bin/env elixir
 
Line 1,404 ⟶ 1,439:
end
 
SMA.run</langsyntaxhighlight>
 
<langsyntaxhighlight lang="bash">#!/bin/bash
elixir ./simple-moving-avg.exs <<EOF
1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1
2 4 6 8 10 12 14 12 10 8 6 4 2
EOF</langsyntaxhighlight>
 
The output is shown below, with the average, followed by the grouped input, forming the basis of each moving average.
Line 1,458 ⟶ 1,493:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">main() ->
SMA3 = sma(3),
SMA5 = sma(5),
Line 1,498 ⟶ 1,533:
{average, Ave} ->
Ave
end.</langsyntaxhighlight>
 
{{out}}
<langsyntaxhighlight lang="erlang">9> sma:main().
Added 1, sma(3) -> 1.000000, sma(5) -> 1.000000
Added 2, sma(3) -> 1.500000, sma(5) -> 1.500000
Line 1,512 ⟶ 1,547:
Added 2, sma(3) -> 3.000000, sma(5) -> 3.800000
Added 1, sma(3) -> 2.000000, sma(5) -> 3.000000
ok</langsyntaxhighlight>
 
Erlang has closures, but immutable variables. A solution then is to use processes and a simple message passing based API.
Line 1,520 ⟶ 1,555:
Matrix languages have routines to compute the gliding avarages for a given sequence of items.
 
<syntaxhighlight lang="euler math toolbox">
<lang Euler Math Toolbox>
>n=1000; m=100; x=random(1,n);
>x10=fold(x,ones(1,m)/m);
>x10=fftfold(x,ones(1,m)/m)[m:n]; // more efficient
</syntaxhighlight>
</lang>
 
It is less efficient to loop as in the following commands.
 
<syntaxhighlight lang="euler math toolbox">
<lang Euler Math Toolbox>
>function store (x:number, v:vector, n:index) ...
$if cols(v)<n then return v|x;
Line 1,559 ⟶ 1,594:
>v
[ 11 12 13 14 15 16 17 18 19 20 ]
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let sma period f (list:float list) =
let sma_aux queue v =
let q = Seq.truncate period (v :: queue)
Line 1,575 ⟶ 1,610:
printf "\nsma5: "
[ 1.;2.;3.;4.;5.;5.;4.;3.;2.;1.] |> sma 5 (printf "%.2f ")
printfn ""</langsyntaxhighlight>
{{out}}
<pre>sma3: 1.00 1.50 2.00 3.00 4.00 4.67 4.67 4.00 3.00 2.00
Line 1,582 ⟶ 1,617:
=={{header|Factor}}==
The <code>I</code> word creates a quotation (anonymous function) that closes over a sequence and a period. This quotation handles adding/removing numbers to the simple moving average (SMA). We can then add a number to the SMA using <code>sma-add</code> and get the SMA's sequence and mean with <code>sma-query</code>. Quotations adhere to the <code>sequence</code> protocol so we can obtain the sequence of numbers simply by calling <code>first</code> on the SMA quotation.
<langsyntaxhighlight lang="factor">USING: kernel interpolate io locals math.statistics prettyprint
random sequences ;
IN: rosetta-code.simple-moving-avg
Line 1,601 ⟶ 1,636:
] each drop ;
 
MAIN: simple-moving-average-demo</langsyntaxhighlight>
{{out}}
<pre>
Line 1,618 ⟶ 1,653:
=={{header|Fantom}}==
 
<langsyntaxhighlight lang="fantom">
class MovingAverage
{
Line 1,664 ⟶ 1,699:
}
}
</syntaxhighlight>
</lang>
 
{{out}} for a period of 5:
Line 1,681 ⟶ 1,716:
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: f+! ( f addr -- ) dup f@ f+ f! ;
: ,f0s ( n -- ) falign 0 do 0e f, loop ;
 
Line 1,707 ⟶ 1,742:
2e sma f. \ 1.5
3e sma f. \ 2.
4e sma f. \ 3.</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">program Movavg
implicit none
 
Line 1,743 ⟶ 1,778:
end function
 
end program Movavg</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Type FuncType As Function(As Double) As Double
Line 1,791 ⟶ 1,826:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,823 ⟶ 1,858:
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">MovingAverage := function(n)
local sma, buffer, pos, sum, len;
buffer := List([1 .. n], i -> 0);
Line 1,849 ⟶ 1,884:
f(3); # 4
f(2); # 3
f(1); # 2</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,882 ⟶ 1,917:
fmt.Printf("%5.3f %5.3f %5.3f\n", x, sma3(x), sma5(x))
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,900 ⟶ 1,935:
=={{header|Groovy}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="groovy">def simple_moving_average = { size ->
def nums = []
double total = 0.0
Line 1,914 ⟶ 1,949:
 
(1..5).each{ printf( "%1.1f ", ma5(it)) }
(5..1).each{ printf( "%1.1f ", ma5(it)) }</langsyntaxhighlight>
{{out}}
<pre>1.0 1.5 2.0 2.5 3.0 3.8 4.2 4.2 3.8 3.0 </pre>
Line 1,921 ⟶ 1,956:
Conform version to the requirement, function SMA called multiple times with just a number:
{{works with|GHC|6.10.4}}
<langsyntaxhighlight Haskelllang="haskell">{-# LANGUAGE BangPatterns #-}
 
import Control.Monad
Line 1,945 ⟶ 1,980:
mapM_ (str <$> pure n <*> sma3 <*> sma5) series))
where str n mm3 mm5 =
concat ["Next number = ",show n,", SMA_3 = ",show mm3,", SMA_5 = ",show mm5]</langsyntaxhighlight>
{{out}}
<pre>Next number = 1.0, SMA_3 = 1.0, SMA_5 = 1.0
Line 1,960 ⟶ 1,995:
 
{{works with|GHC|6.10.4}}
<langsyntaxhighlight Haskelllang="haskell">import Data.List
import Control.Arrow
import Control.Monad
Line 1,969 ⟶ 2,004:
 
printSMA n p = mapM_ (\(n,a) -> putStrLn $ "Next number: " ++ show n ++ " Average: " ++ show a)
. take n . sMA p $ [1..5]++[5,4..1]++[3..]</langsyntaxhighlight>
 
Stateful function using the state monad to keep track of state
 
{{works with|GHC|7.8.3}}
<syntaxhighlight lang="haskell">
<lang Haskell>
import Control.Monad
import Control.Monad.State
Line 2,001 ⟶ 2,036:
main :: IO ()
main = print $ evalState demostrateSMA []
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,009 ⟶ 2,044:
 
=={{header|HicEst}}==
<langsyntaxhighlight HicEstlang="hicest">REAL :: n=10, nums(n)
 
nums = (1,2,3,4,5, 5,4,3,2,1)
Line 2,034 ⟶ 2,069:
Past(Periods(ID)) = num
SMA = SUM(Past) / MIN( now(ID), Periods(ID) )
END</langsyntaxhighlight>
<pre>num=1 SMA3=1 SMA5=1
num=2 SMA3=1.5 SMA5=1.5
Line 2,047 ⟶ 2,082:
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight lang="unicon">procedure main(A)
sma := buildSMA(3) # Use better name than "I".
every write(sma(!A))
Line 2,064 ⟶ 2,099:
}
return (@c, c)
end</langsyntaxhighlight>
Note: This program uses Unicon specific co-expression calling syntax. It can be easily modified to run under Icon.
 
Line 2,085 ⟶ 2,120:
If the <tt>Utils</tt> package is imported from the [https://tapestry.tucson.az.us/unilib Unicon code library] then a (Unicon only) solution is:
 
<langsyntaxhighlight Uniconlang="unicon">import Utils
 
procedure main(A)
Line 2,098 ⟶ 2,133:
every (avg := 0.0) +:= !stream
return avg / *stream
end</langsyntaxhighlight>
 
with the sample run:
Line 2,122 ⟶ 2,157:
In that context, moving average is expressed very concisely in J as '''<code>(+/%#)\</code>''', though it is worth noting that this approach does not provide averages for the initial cases where not all data would be available yet:
 
<langsyntaxhighlight Jlang="j"> 5 (+/%#)\ 1 2 3 4 5 5 4 3 2 1 NB. not a solution for this task
3 3.8 4.2 4.2 3.8 3</langsyntaxhighlight>
 
In the context of the task, we need to produce a stateful function to consume streams. Since J does not have native lexical closure, we need to [http://www.jsoftware.com/jwiki/Guides/Lexical%20Closure implement it]. Thus the [[Talk:Averages/Simple_moving_average#J_Implementation|streaming solution]] is more complex:
<langsyntaxhighlight lang="j"> lex =: 1 :'(a[n__a=.m#_.[a=.18!:3$~0)&(4 :''(+/%#)(#~1-128!:5)n__x=.1|.!.y n__x'')'</langsyntaxhighlight>
'''Example:'''
<langsyntaxhighlight lang="j"> sma =: 5 lex
sma&> 1 2 3 4 5 5 4 3 2 1
1 1.5 2 2.5 3 3.8 4.2 4.2 3.8 3</langsyntaxhighlight>
Here, the <code>&></code> is analogous to the "for each" of other languages.
 
Or, a more traditional approach could be used:
 
<langsyntaxhighlight lang="j">avg=: +/ % #
SEQ=:''
moveAvg=:4 :0"0
Line 2,143 ⟶ 2,178:
 
5 moveAvg 1 2 3 4 5 5 4 3 2 1
1 1.5 2 2.5 3 3.8 4.2 4.2 3.8 3</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java5">import java.util.LinkedList;
import java.util.Queue;
 
Line 2,185 ⟶ 2,220:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>Next number = 1.0, SMA = 1.0
Line 2,211 ⟶ 2,246:
=={{header|JavaScript}}==
===Using for loop===
<langsyntaxhighlight lang="javascript">function simple_moving_averager(period) {
var nums = [];
return function(num) {
Line 2,234 ⟶ 2,269:
// using WSH
WScript.Echo("Next number = " + n + ", SMA_3 = " + sma3(n) + ", SMA_5 = " + sma5(n));
}</langsyntaxhighlight>
{{out}}
<pre>Next number = 1, SMA_3 = 1, SMA_5 = 1
Line 2,250 ⟶ 2,285:
[http://jsfiddle.net/79xe381e/ JS Fiddle]
 
<langsyntaxhighlight lang="javascript">// single-sided
Array.prototype.simpleSMA=function(N) {
return this.map(
Line 2,268 ⟶ 2,303:
console.log(g.simpleSMA(3));
console.log(g.simpleSMA(5));
console.log(g.simpleSMA(g.length));</langsyntaxhighlight>
{{out}}
<pre>
Line 2,277 ⟶ 2,312:
 
=={{header|Julia}}==
<syntaxhighlight lang ="julia">using Statistics</langsyntaxhighlight>
The function wants specified the type of the data in the buffer and, if you want, the limit of the buffer.
<langsyntaxhighlight lang="julia">function movingaverage(::Type{T} = Float64; lim::Integer = -1) where T<:Real
buffer = Vector{T}(0)
if lim == -1
Line 2,300 ⟶ 2,335:
@show test(1.0) # mean([1])
@show test(2.0) # mean([1, 2])
@show test(3.0) # mean([1, 2, 3])</langsyntaxhighlight>
 
{{out}}
Line 2,310 ⟶ 2,345:
 
Non-stateful:
<syntaxhighlight lang="k">
<lang K>
v:v,|v:1+!5
v
Line 2,320 ⟶ 2,355:
sma[v;5]
1 1.5 2 2.5 3 3.8 4.2 4.2 3.8 3
</syntaxhighlight>
</lang>
 
Stateful:
<syntaxhighlight lang="k">
<lang K>
sma:{n::x#_n; {n::1_ n,x; {avg x@&~_n~'x} n}}
sma[5]' v
1 1.5 2 2.5 3 3.8 4.2 4.2 3.8 3
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun initMovingAverage(p: Int): (Double) -> Double {
Line 2,349 ⟶ 2,384:
println("num\tsma4\tsma5\n")
for (number in numbers) println("${number}\t${sma4(number)}\t${sma5(number)}")
}</langsyntaxhighlight>
 
{{out}}
Line 2,369 ⟶ 2,404:
=={{header|Lasso}}==
{{incorrect|Lasso|routine is called with a list of multiple numbers rather than being called with individual numbers in succession.}}
<langsyntaxhighlight Lassolang="lasso">define simple_moving_average(a::array,s::integer)::decimal => {
#a->size == 0 ? return 0.00
#s == 0 ? return 0.00
Line 2,400 ⟶ 2,435:
', SMA5 is: ' + simple_moving_average(#mynumbers,5)
'\r'
^}</langsyntaxhighlight>
 
{{out}}
Line 2,421 ⟶ 2,456:
The interesting thing here is how to implement an equivalent of a stateful function.
For sample output see http://libertybasic.conforums.com/index.cgi?board=open&action=display&num=1322956720
<syntaxhighlight lang="lb">
<lang lb>
dim v$( 100) ' Each array term stores a particular SMA of period p in p*10 bytes
 
Line 2,490 ⟶ 2,525:
if k <Period then SMA =total / k else SMA =total /Period
end function
</syntaxhighlight>
</lang>
 
=={{header|Logo}}==
Line 2,499 ⟶ 2,534:
UCB Logo has a DEFINE primitive to construct functions from structured instruction lists. In addition, UCB Logo supports a compact template syntax for quoting lists (backquote "`") and replacing components of quoted lists (comma ","). These facilities can be used together in order to create templated function-defining-functions.
 
<langsyntaxhighlight lang="logo">to average :l
output quotient apply "sum :l count :l
end
Line 2,521 ⟶ 2,556:
 
; the internal queue is in the global namespace, easy to inspect
show :avg3.queue ; [3 4 5]</langsyntaxhighlight>
 
If namespace pollution is a concern, UCB Logo supplies a GENSYM command to obtain unique names in order to avoid collisions.
 
<langsyntaxhighlight lang="logo"> ...
localmake "qn word :name gensym
...
Line 2,531 ⟶ 2,566:
; list user-defined functions and variables
show procedures ; [average avg3 make.sma]
show names ; [[[] [avg3.g1]]</langsyntaxhighlight>
 
=={{header|Lua}}==
 
<langsyntaxhighlight lang="lua">function sma(period)
local t = {}
function sum(a, ...t)
sum = 0
if a then return a+sum(...) else return 0 end
for _, v in ipairs(t) do
sum = sum + v
end
return sum
end
function average(n)
if #t == period then table.remove(t, 1) end
t[#t + 1] = n
return sum(unpack(t)) / #t
end
return average
Line 2,554 ⟶ 2,593:
print("\nSMA 10")
for v=1,15 do print(sma10(v)) end
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
This version uses a list entry so it can use the built-in function.
<langsyntaxhighlight Mathematicalang="mathematica">MA[x_List, r_] := Join[Table[Mean[x[[1;;y]]],{y,r-1}], MovingAverage[x,r]]</langsyntaxhighlight>
 
This version is stateful instead.
<langsyntaxhighlight Mathematicalang="mathematica">MAData = {{}, 0};
MAS[x_, t_: Null] :=
With[{r = If[t === Null, MAData[[2]], t]},
Mean[MAData[[1]] =
If[Length[#] > (MAData[[2]] = r), #[[-r ;; -1]], #] &@
Append[MAData[[1]], x]]]</langsyntaxhighlight>
 
Tests:
Line 2,588 ⟶ 2,627:
 
Matlab and Octave provide very efficient and fast functions, that can be applied to vectors (i.e. series of data samples)
<langsyntaxhighlight Matlablang="matlab"> [m,z] = filter(ones(1,P),P,x); </langsyntaxhighlight>
m is the moving average, z returns the state at the end of the data series, which can be used to continue the moving average.
<langsyntaxhighlight Matlablang="matlab"> [m,z] = filter(ones(1,P),P,x,z); </langsyntaxhighlight>
 
=={{header|Mercury}}==
In Mercury, an idiomatic "moving averages" function would be 'stateless' - or rather, it would have ''explicit state'' that its callers would have to thread through uses of it:
 
<langsyntaxhighlight Mercurylang="mercury"> % state(period, list of floats from [newest, ..., oldest])
:- type state ---> state(int, list(float)).
 
Line 2,604 ⟶ 2,643:
sma(N, Average, state(P, L0), state(P, L)) :-
take_upto(P, [N|L0], L),
Average = foldl((+), L, 0.0) / float(length(L)).</langsyntaxhighlight>
 
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.
Line 2,611 ⟶ 2,650:
 
We define an SMA class, which can be configured with the desired window size (P).
<langsyntaxhighlight MiniScriptlang="miniscript">SMA = {}
SMA.P = 5 // (a default; may be overridden)
SMA.buffer = null
Line 2,628 ⟶ 2,667:
num = round(rnd*100)
print "num: " + num + " sma3: " + sma3.next(num) + " sma5: " + sma5.next(num)
end for</langsyntaxhighlight>
 
{{out}}
Line 2,645 ⟶ 2,684:
=={{header|NetRexx}}==
{{trans|Java}}
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 2,708 ⟶ 2,747:
run_samples(args)
return
</syntaxhighlight>
</lang>
{{out}}
<pre style="height: 25ex; overflow: scroll">
Line 2,736 ⟶ 2,775:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import deques
 
proc simplemovingaverage(period: int): auto =
Line 2,763 ⟶ 2,802:
var sma2 = simplemovingaverage(5)
for i in 1..5: echo sma2(float(i))
for i in countdown(5,1): echo sma2(float(i))</langsyntaxhighlight>
{{out}}
<pre>1.0
Line 2,789 ⟶ 2,828:
=={{header|Objeck}}==
{{trans|Java}}
<langsyntaxhighlight lang="objeck">
use Collection;
 
Line 2,835 ⟶ 2,874:
}
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,864 ⟶ 2,903:
=={{header|Objective-C}}==
 
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
@interface MovingAverage : NSObject {
Line 2,957 ⟶ 2,996:
}
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 2,985 ⟶ 3,024:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let sma (n, s, q) x =
let l = Queue.length q and s = s +. x in
Queue.push x q;
Line 3,009 ⟶ 3,048:
);
print_newline ();
) periodLst</langsyntaxhighlight>
 
{{out}}
Line 3,039 ⟶ 3,078:
 
More imperatively:
<langsyntaxhighlight lang="ocaml">let sma_create period =
let q = Queue.create ()
and sum = ref 0.0 in
Line 3,060 ⟶ 3,099:
) series;
print_newline ();
) periodLst</langsyntaxhighlight>
 
=={{header|Oforth}}==
Line 3,067 ⟶ 3,106:
The list of values is included into a channel so this code is thread-safe : multiple tasks running in parallel can call the closure returned.
 
<langsyntaxhighlight lang="oforth">import: parallel
 
: createSMA(period)
| ch |
Channel new [ ] over send drop ->ch
#[ ch receive + left(period) dup avg swap ch send drop ] ;</langsyntaxhighlight>
 
Usage:
 
<langsyntaxhighlight lang="oforth">: test
| sma3 sma5 l |
3 createSMA -> sma3
Line 3,082 ⟶ 3,121:
[ 1, 2, 3, 4, 5, 5, 4, 3, 2, 1 ] ->l
"SMA3" .cr l apply( #[ sma3 perform . ] ) printcr
"SMA5" .cr l apply( #[ sma5 perform . ] ) ;</langsyntaxhighlight>
 
{{out}}
Line 3,095 ⟶ 3,134:
=={{header|ooRexx}}==
ooRexx does not have stateful functions, but the same effect can be achieved by using object instances.
<syntaxhighlight lang="oorexx">
<lang ooRexx>
testdata = .array~of(1, 2, 3, 4, 5, 5, 4, 3, 2, 1)
 
Line 3,138 ⟶ 3,177:
-- return current queue
return sum / queue~items
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,169 ⟶ 3,208:
 
=={{header|OxygenBasic}}==
<langsyntaxhighlight lang="oxygenbasic">def max 1000
 
Class MovingAverage
Line 3,211 ⟶ 3,250:
'...
print A.average 'reult 95
</syntaxhighlight>
</lang>
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
 
fun {CreateSMA Period}
Line 3,240 ⟶ 3,279:
{System.showInfo " Number = "#I#" , SMA = "#{SMA {Int.toFloat I}}}
end
end</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
Partial implementation: does not (yet?) create different stores on each invocation.
<langsyntaxhighlight lang="parigp">sma_per(n)={
sma_v=vector(n);
sma_i = 0;
n->if(sma_i++>#sma_v,sma_v[sma_i=1]=n;0,sma_v[sma_i]=n;0)+sum(i=1,#sma_v,sma_v[i])/#sma_v
};</langsyntaxhighlight>
 
=={{header|Pascal}}==
{{works with|Free Pascal}}
Like in other implementations the sum of the last p values is only updated by subtracting the oldest value and addindg the new. To minimize rounding errors after p values the sum is corrected to the real sum.
<langsyntaxhighlight Pascallang="pascal">program sma;
type
tsma = record
Line 3,330 ⟶ 3,369:
smaAddValue(sma3,i);
writeln('100''000''000 insertions ',sma3.smaAverage:0:4);
end.</langsyntaxhighlight>
;output:
<pre>
Line 3,352 ⟶ 3,391:
Using an initializer function which returns an anonymous closure which closes over an instance ''(separate for each call to the initializer!)'' of the lexical variables <code>$period</code>, <code>@list</code>, and <code>$sum</code>:
 
<langsyntaxhighlight lang="perl">sub sma_generator {
my $period = shift;
my (@list, $sum);
Line 3,369 ⟶ 3,408:
for (1, 2, 3, 2, 7) {
printf "append $_ --> sma = %.2f (with period 3)\n", $sma->($_);
}</langsyntaxhighlight>
 
{{out}}
Line 3,382 ⟶ 3,421:
=={{header|Phix}}==
First create a separate file sma.e to encapsulate the private variables. Note in particular the complete lack of any special magic/syntax: it is just a table with some indexes.
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">sma</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span> <span style="color: #000080;font-style:italic;">-- ((period,history,circnxt)) (private to sma.e)</span>
Line 3,434 ⟶ 3,473:
<span style="color: #000000;">sma_free</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">sidx</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<!--</langsyntaxhighlight>-->
and the main file is:
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">sma</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
Line 3,449 ⟶ 3,488:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%2g: sma3=%8g, sma5=%8g\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">si</span><span style="color: #0000FF;">,</span><span style="color: #000000;">moving_average</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sma3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">si</span><span style="color: #0000FF;">),</span><span style="color: #000000;">moving_average</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sma5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">si</span><span style="color: #0000FF;">)})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 3,463 ⟶ 3,502:
1: sma3= 2, sma5= 3
</pre>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">main =>
L=[1, 2, 3, 4, 5, 5, 4, 3, 2, 1],
Map3 = new_map([p=3]),
Map5 = new_map([p=5]),
foreach(N in L)
printf("n: %-2d sma3: %-17w sma5: %-17w\n",N, sma(N,Map3), sma(N,Map5))
end.
 
sma(N,Map) = Average =>
Stream = Map.get(stream,[]) ++ [N],
if Stream.len > Map.get(p) then
Stream := Stream.tail
end,
Average = cond(Stream.len == 0,
0,
sum(Stream) / Stream.len),
Map.put(stream,Stream).</syntaxhighlight>
 
{{out}}
<pre>n: 1 sma3: 1.0 sma5: 1.0
n: 2 sma3: 1.5 sma5: 1.5
n: 3 sma3: 2.0 sma5: 2.0
n: 4 sma3: 3.0 sma5: 2.5
n: 5 sma3: 4.0 sma5: 3.0
n: 5 sma3: 4.666666666666667 sma5: 3.8
n: 4 sma3: 4.666666666666667 sma5: 4.2
n: 3 sma3: 4.0 sma5: 4.2
n: 2 sma3: 3.0 sma5: 3.8
n: 1 sma3: 2.0 sma5: 3.0</pre>
 
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de sma (@Len)
(curry (@Len (Data)) (N)
(push 'Data N)
(and (nth Data @Len) (con @)) # Truncate
(*/ (apply + Data) (length Data)) ) )</langsyntaxhighlight>
<langsyntaxhighlight PicoLisplang="picolisp">(def 'sma3 (sma 3))
(def 'sma5 (sma 5))
 
Line 3,480 ⟶ 3,551:
(format (sma3 N) *Scl)
" (sma5) "
(format (sma5 N) *Scl) ) )</langsyntaxhighlight>
{{out}}
<pre>1.00 (sma3) 1.00 (sma5) 1.00
Line 3,495 ⟶ 3,566:
=={{header|PL/I}}==
===version 1===
<langsyntaxhighlight lang="pli">SMA: procedure (N) returns (float byaddr);
declare N fixed;
declare A(*) fixed controlled,
Line 3,514 ⟶ 3,585:
A = 0;
p = 0;
end SMA;</langsyntaxhighlight>
===version 2===
{{trans|REXX}}
<langsyntaxhighlight lang="pli">*process source attributes xref;
mat: Proc Options(main);
Dcl a(10) Dec Fixed(8,6);
Line 3,561 ⟶ 3,632:
Return(s);
End;
End;</langsyntaxhighlight>
{{out}}
<pre> SMA with SMA with
Line 3,578 ⟶ 3,649:
 
=={{header|Pony}}==
<syntaxhighlight lang="pony">
<lang Pony>
class MovingAverage
let period: USize
Line 3,617 ⟶ 3,688:
end
 
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
#This version allows a user to enter numbers one at a time to figure this into the SMA calculations
 
Line 3,647 ⟶ 3,718:
"Added " + $inputs[(($inputs.Count) - 1)] + ", sma($period1) = " + (getSMA $inputs $Period1) + ", sma($period2) = " + (getSMA $inputs $period2)
}
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure.d SMA(Number, Period=0)
Static P
Static NewList L()
Line 3,668 ⟶ 3,739:
Next
ProcedureReturn sum/ListSize(L())
EndProcedure</langsyntaxhighlight>
 
=={{header|Python}}==
Line 3,674 ⟶ 3,745:
Both implementations use the [http://www.doughellmann.com/PyMOTW/collections/index.html deque] datatype.
===Procedural===
<langsyntaxhighlight lang="python">from collections import deque
 
def simplemovingaverage(period):
Line 3,690 ⟶ 3,761:
return summ / n
 
return sma</langsyntaxhighlight>
 
===Class based===
<langsyntaxhighlight lang="python">from collections import deque
 
class Simplemovingaverage():
Line 3,713 ⟶ 3,784:
average = sum( stream ) / streamlength
 
return average</langsyntaxhighlight>
 
'''Tests'''
<langsyntaxhighlight lang="python">if __name__ == '__main__':
for period in [3, 5]:
print ("\nSIMPLE MOVING AVERAGE (procedural): PERIOD =", period)
Line 3,730 ⟶ 3,801:
print (" Next number = %-2g, SMA = %g " % (i, sma(i)))
for i in range(5, 0, -1):
print (" Next number = %-2g, SMA = %g " % (i, sma(i)))</langsyntaxhighlight>
 
{{out}}
Line 3,783 ⟶ 3,854:
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ $ "bigrat.qky" loadfile ] now!
 
[ over size -
space swap of
swap join ] is justifypad ( $ n --> $ )
 
[ ' [ stack [ ] ]
Line 3,809 ⟶ 3,880:
5 make-sma sma-5 put
 
say "n sma-3 sma-5" cr cr
say "-----------------------" cr
' [ 1 2 3 4 5 5 4 3 2 1 ]
witheach
[ dup echo sp
dup sma-3 share do
7 point$ 10 justifypad echo$ sp
sma-5 share do
7 point$ 10 justifypad echo$ cr ]</lang>
</syntaxhighlight>
 
{{out}}
 
<pre>n sma-3 sma-5
 
-----------------------
1 1 1 1
2 1.5 1.5 1.5
3 2 2 2
4 3 3 2.5 2.5
5 4 4 3 3
5 4.6666667 3.8 3.8
4 4.6666667 4.2 4.2
3 4 4.2 4.2
2 3 3.8 3.8
1 2 2 3 3
</pre>
 
=={{header|R}}==
This is easiest done with two functions: one to handle the state (i.e. the numbers already entered), and one to calculate the average.
<langsyntaxhighlight Rlang="r">#concat concatenates the new values to the existing vector of values, then discards any values that are too old.
lastvalues <- local(
{
Line 3,867 ⟶ 3,938:
moving.average(-3) # 1
moving.average(8) # 2
moving.average(7) # 4</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight Racketlang="racket">#lang racket
 
(require data/queue)
Line 3,891 ⟶ 3,962:
([i '(1 2 3 4 5 5 4 3 2 1)])
(values (sma3 i) (sma5 i)))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 3,897 ⟶ 3,968:
 
{{works with|Rakudo|2016.08}}
<syntaxhighlight lang="raku" perl6line>sub sma-generator (Int $P where * > 0) {
sub ($x) {
state @a = 0 xx $P;
Line 3,910 ⟶ 3,981:
for 1, 2, 3, 2, 7 {
printf "append $_ --> sma = %.2f (with period 3)\n", sma $_;
}</langsyntaxhighlight>
 
{{out}}
Line 3,925 ⟶ 3,996:
 
The 1<sup>st</sup> and 2<sup>nd</sup> periods (number of values) were parametrized, &nbsp; as well as the total number of values.
<langsyntaxhighlight lang="rexx">/*REXX program illustrates and displays a simple moving average using a constructed list*/
parse arg p q n . /*obtain optional arguments from the CL*/
if p=='' | p=="," then p= 3 /*Not specified? Then use the default.*/
Line 3,946 ⟶ 4,017:
do k=max(1, j-p+1) to j+p for p while k<=j; i= i + 1; $= $ + @.k
end /*k*/
return $/i /*SMA ≡ simple moving average. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the generated default input numbers:}}
<pre>
Line 3,965 ⟶ 4,036:
=={{header|Ring}}==
===version 1===
<langsyntaxhighlight lang="ring">
load "stdlib.ring"
decimals(8)
Line 3,997 ⟶ 4,068:
if window[period]<period window[period] += 1 ok
return (accum[period] / window[period])
</syntaxhighlight>
</lang>
Output:
<pre>
Line 4,013 ⟶ 4,084:
 
===version 2===
<langsyntaxhighlight lang="ring">
load "stdlib.ring"
decimals(8)
Line 4,045 ⟶ 4,116:
if window[period]<period window[period] += 1 ok
return (accum[period] / window[period])
</syntaxhighlight>
</lang>
Output:
<pre>
Line 4,061 ⟶ 4,132:
 
===version 3===
<langsyntaxhighlight lang="ring">
 
### RING: Function Moving Average. Bert Mariani 2016-06-22
Line 4,133 ⟶ 4,204:
###-------------------------------------------------------------
 
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
A closure:
<langsyntaxhighlight lang="ruby">def simple_moving_average(size)
nums = []
sum = 0.0
Line 4,154 ⟶ 4,225:
printf "Next number = %d, SMA_3 = %.3f, SMA_5 = %.1f\n",
num, ma3.call(num), ma5.call(num)
end</langsyntaxhighlight>
 
A class
<langsyntaxhighlight lang="ruby">class MovingAverager
def initialize(size)
@size = size
Line 4,184 ⟶ 4,255:
printf "Next number = %d, SMA_3 = %.3f, SMA_5 = %.1f\n",
num, ma3 << num, ma5 <<num
end</langsyntaxhighlight>
 
=={{header|Run Basic}}==
<langsyntaxhighlight lang="runbasic">data 1,2,3,4,5,5,4,3,2,1
dim sd(10) ' series data
global sd ' make it global so we all see it
Line 4,205 ⟶ 4,276:
print sd(i);" sma:";p;" ";sumSd / p1
next i
end function</langsyntaxhighlight>
<pre>----- SMA:3 -----
1 sma:3 1
Line 4,231 ⟶ 4,302:
=={{header|Rust}}==
===Vector Based===
<langsyntaxhighlight lang="rust">struct SimpleMovingAverage {
period: usize,
numbers: Vec<usize>
Line 4,269 ⟶ 4,340:
}
}
}</langsyntaxhighlight>
 
===Double-ended Queue Based===
<langsyntaxhighlight lang="rust">use std::collections::VecDeque;
 
struct SimpleMovingAverage {
Line 4,312 ⟶ 4,383:
}
}
}</langsyntaxhighlight>
 
<pre>Moving average with period 3
Line 4,339 ⟶ 4,410:
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">class MovingAverage(period: Int) {
private var queue = new scala.collection.mutable.Queue[Double]()
def apply(n: Double) = {
Line 4,349 ⟶ 4,420:
override def toString = queue.mkString("(", ", ", ")")+", period "+period+", average "+(queue.sum / queue.size)
def clear = queue.clear
}</langsyntaxhighlight>
 
<pre>
Line 4,387 ⟶ 4,458:
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(define ((simple-moving-averager size . nums) num)
(set! nums (cons num (if (= (length nums) size) (reverse (cdr (reverse nums))) nums)))
(/ (apply + nums) (length nums)))
Line 4,393 ⟶ 4,464:
(define av (simple-moving-averager 3))
(map av '(1 2 3 4 5 5 4 3 2 1))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,401 ⟶ 4,472:
=={{header|Sidef}}==
Implemented with closures:
<langsyntaxhighlight lang="ruby">func simple_moving_average(period) {
 
var list = []
Line 4,422 ⟶ 4,493:
printf("Next number = %d, SMA_3 = %.3f, SMA_5 = %.1f\n",
num, ma3.call(num), ma5.call(num))
}</langsyntaxhighlight>
 
Implemented as a class:
<langsyntaxhighlight lang="ruby">class sma_generator(period, list=[], sum=0) {
 
method SMA(number) {
Line 4,443 ⟶ 4,514:
printf("Next number = %d, SMA_3 = %.3f, SMA_5 = %.1f\n",
num, ma3.SMA(num), ma5.SMA(num))
}</langsyntaxhighlight>
 
{{out}}
Line 4,462 ⟶ 4,533:
{{works with|GNU Smalltalk}}
 
<langsyntaxhighlight lang="smalltalk">Object subclass: MovingAverage [
|valueCollection period collectedNumber sum|
MovingAverage class >> newWithPeriod: thePeriod [
Line 4,492 ⟶ 4,563:
^ self sma
]
].</langsyntaxhighlight>
 
<langsyntaxhighlight lang="smalltalk">|sma3 sma5|
 
sma3 := MovingAverage newWithPeriod: 3.
Line 4,503 ⟶ 4,574:
v . (sma3 add: v) asFloat . (sma5 add: v) asFloat
}) displayNl
]</langsyntaxhighlight>
 
=={{header|Swift}}==
Line 4,509 ⟶ 4,580:
{{trans|Rust}}
 
<langsyntaxhighlight lang="swift">struct SimpleMovingAverage {
var period: Int
var numbers = [Double]()
Line 4,536 ⟶ 4,607:
print("n: \(n); average \(averager.addNumber(n))")
}
}</langsyntaxhighlight>
 
{{out}}
Line 4,565 ⟶ 4,636:
=={{header|Tcl}}==
{{works with|Tcl|8.6}} or {{libheader|TclOO}}
<langsyntaxhighlight lang="tcl">oo::class create SimpleMovingAverage {
variable vals idx
constructor {{period 3}} {
Line 4,575 ⟶ 4,646:
expr {[tcl::mathop::+ {*}$vals]/double([llength $vals])}
}
}</langsyntaxhighlight>
Demonstration:
<langsyntaxhighlight lang="tcl">SimpleMovingAverage create averager3
SimpleMovingAverage create averager5 5
foreach n {1 2 3 4 5 5 4 3 2 1} {
puts "Next number = $n, SMA_3 = [averager3 val $n], SMA_5 = [averager5 val $n]"
}</langsyntaxhighlight>
{{out}}
<pre>Next number = 1, SMA_3 = 1.0, SMA_5 = 1.0
Line 4,600 ⟶ 4,671:
Press <tt>ON</tt> to terminate the program.
 
<langsyntaxhighlight lang="ti83b">:1->C
:While 1
:Prompt I
Line 4,607 ⟶ 4,678:
:Disp mean(L1)
:1+C->C
:End</langsyntaxhighlight>
 
=={{header|TI-89 BASIC}}==
Line 4,613 ⟶ 4,684:
 
Function that returns a list containing the averaged data of the supplied argument
<langsyntaxhighlight lang="ti89b">movinavg(list,p)
Func
Local r, i, z
Line 4,624 ⟶ 4,695:
EndFunc
 
</syntaxhighlight>
</lang>
 
Program that returns a simple value at each invocation:
<langsyntaxhighlight lang="ti89b">movinav2(x_,v_)
Prgm
If getType(x_)="STR" Then
Line 4,638 ⟶ 4,709:
sum(list)/dim(list)→#v_
EndPrgm
</syntaxhighlight>
</lang>
 
Example1: Using the function<br>
Line 4,673 ⟶ 4,744:
=={{header|VBA}}==
This is a "simple" moving average.
<langsyntaxhighlight lang="vb">Class sma
'to be stored in a class module with name "sma"
Private n As Integer 'period
Line 4,704 ⟶ 4,775:
Debug.Print Format(sma5.sma(CDbl(s(i))), "0.00000")
Next i
End Sub</langsyntaxhighlight>{{out}}
<pre> 1 0,33333 0,20000
2 1,00000 0,60000
Line 4,717 ⟶ 4,788:
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vb">data = "1,2,3,4,5,5,4,3,2,1"
token = Split(data,",")
stream = ""
Line 4,753 ⟶ 4,824:
SMA = sum / (UBound(d) + 1)
End If
End Function</langsyntaxhighlight>
 
{{Out}}
Line 4,768 ⟶ 4,839:
2 3 3.8
1 2 3
</pre>
 
=={{header|V (Vlang)}}==
{{trans|Go}}
<syntaxhighlight lang="v (vlang)">fn sma(period int) fn(f64) f64 {
mut i := int(0)
mut sum := f64(0)
mut storage := []f64{len: 0, cap:period}
return fn[mut storage, mut sum, mut i, period](input f64) f64 {
if storage.len < period {
sum += input
storage << input
}
sum += input - storage[i]
storage[i], i = input, (i+1)%period
return sum / f64(storage.len)
}
}
fn main() {
sma3 := sma(3)
sma5 := sma(5)
println("x sma3 sma5")
for x in [f64(1), 2, 3, 4, 5, 5, 4, 3, 2, 1] {
println("${x:5.3f} ${sma3(x):5.3f} ${sma5(x):5.3f}")
}
}</syntaxhighlight>
 
{{out}}
<pre>
x sma3 sma5
1.000 1.000 1.000
2.000 1.500 1.500
3.000 2.000 2.000
4.000 3.000 2.500
5.000 4.000 3.000
5.000 4.667 3.800
4.000 4.667 4.200
3.000 4.000 4.200
2.000 3.000 3.800
1.000 2.000 3.000
</pre>
 
Line 4,773 ⟶ 4,887:
{{trans|Go}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for Fmt
 
var sma = Fn.new { |period|
Line 4,796 ⟶ 4,910:
for (x in [1, 2, 3, 4, 5, 5, 4, 3, 2, 1]) {
Fmt.precision = 3
SystemFmt.print("%(Fmt.f(5,$5f x)) $5f %(Fmt.f(5$5f", x, sma3.call(x))) %(Fmt.f(5, sma5.call(x)))")
}</langsyntaxhighlight>
 
{{out}}
Line 4,815 ⟶ 4,929:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn SMA(P){
fcn(n,ns,P){
sz:=ns.append(n.toFloat()).len();
Line 4,822 ⟶ 4,936:
ns.sum(0.0)/P;
}.fp1(List.createLong(P+1),P) // pre-allocate a list of length P+1
}</langsyntaxhighlight>
fp1 creates a partial application fixing the (in this case) the second and third
parameters
<langsyntaxhighlight lang="zkl">T(1,2,3,4,5,5,4,3,2,1).apply(SMA(3)).println();
T(1,2,3,4,5,5,4,3,2,1).apply(SMA(5)).println();</langsyntaxhighlight>
{{out}}
<pre>
Anonymous user