Averages/Simple moving average: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 3: Line 3:
Computing the [[wp:Moving_average#Simple_moving_average|simple moving average]] of a series of numbers.
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.
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: Line 46:
=={{header|11l}}==
=={{header|11l}}==
{{trans|D}}
{{trans|D}}
<syntaxhighlight lang=11l>T SMA
<syntaxhighlight lang="11l">T SMA
[Float] data
[Float] data
sum = 0.0
sum = 0.0
Line 85: Line 85:
=={{header|360 Assembly}}==
=={{header|360 Assembly}}==
{{trans|PL/I}}
{{trans|PL/I}}
<syntaxhighlight lang=360asm>* Averages/Simple moving average 26/08/2015
<syntaxhighlight lang="360asm">* Averages/Simple moving average 26/08/2015
AVGSMA CSECT
AVGSMA CSECT
USING AVGSMA,R12
USING AVGSMA,R12
Line 193: Line 193:


moving.ads:
moving.ads:
<syntaxhighlight lang=Ada>generic
<syntaxhighlight lang="ada">generic
Max_Elements : Positive;
Max_Elements : Positive;
type Number is digits <>;
type Number is digits <>;
Line 203: Line 203:


moving.adb:
moving.adb:
<syntaxhighlight lang=Ada>with Ada.Containers.Vectors;
<syntaxhighlight lang="ada">with Ada.Containers.Vectors;


package body Moving is
package body Moving is
Line 245: Line 245:


main.adb:
main.adb:
<syntaxhighlight lang=Ada>with Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO;
with Moving;
with Moving;
procedure Main is
procedure Main is
Line 296: 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]}} -->
<!-- {{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'''.
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'''.
<syntaxhighlight lang=Algol68>MODE SMAOBJ = STRUCT(
<syntaxhighlight lang="algol68">MODE SMAOBJ = STRUCT(
LONG REAL sma,
LONG REAL sma,
LONG REAL sum,
LONG REAL sum,
Line 401: Line 401:
ahk forum: [http://www.autohotkey.com/forum/post-276695.html#276695 discussion]
ahk forum: [http://www.autohotkey.com/forum/post-276695.html#276695 discussion]
For Integers:
For Integers:
<syntaxhighlight lang=AutoHotkey>MsgBox % MovingAverage(5,3) ; 5, averaging length <- 3
<syntaxhighlight lang="autohotkey">MsgBox % MovingAverage(5,3) ; 5, averaging length <- 3
MsgBox % MovingAverage(1) ; 3
MsgBox % MovingAverage(1) ; 3
MsgBox % MovingAverage(-3) ; 1
MsgBox % MovingAverage(-3) ; 1
Line 420: Line 420:
}</syntaxhighlight>
}</syntaxhighlight>
For floating point numbers:
For floating point numbers:
<syntaxhighlight lang=AutoHotkey>MovingAverage(x,len="") { ; for floating point numbers
<syntaxhighlight lang="autohotkey">MovingAverage(x,len="") { ; for floating point numbers
Static
Static
Static n:=0, m:=10 ; default averaging length = 10
Static n:=0, m:=10 ; default averaging length = 10
Line 433: Line 433:


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang=awk>#!/usr/bin/awk -f
<syntaxhighlight lang="awk">#!/usr/bin/awk -f
# Moving average over the first column of a data file
# Moving average over the first column of a data file
BEGIN {
BEGIN {
Line 449: Line 449:
=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang=bbcbasic> MAXPERIOD = 10
<syntaxhighlight lang="bbcbasic"> MAXPERIOD = 10
FOR n = 1 TO 5
FOR n = 1 TO 5
PRINT "Number = ";n TAB(12) " SMA3 = ";FNsma(n,3) TAB(30) " SMA5 = ";FNsma(n,5)
PRINT "Number = ";n TAB(12) " SMA3 = ";FNsma(n,3) TAB(30) " SMA5 = ";FNsma(n,5)
Line 512: Line 512:


=={{header|Bracmat}}==
=={{header|Bracmat}}==
<syntaxhighlight lang=bracmat>( ( I
<syntaxhighlight lang="bracmat">( ( I
= buffer
= buffer
. (new$=):?freshEmptyBuffer
. (new$=):?freshEmptyBuffer
Line 564: Line 564:
=={{header|Brat}}==
=={{header|Brat}}==
Object version
Object version
<syntaxhighlight lang=brat>
<syntaxhighlight lang="brat">
SMA = object.new
SMA = object.new


Line 589: Line 589:
Function version
Function version


<syntaxhighlight lang=brat>sma = { period |
<syntaxhighlight lang="brat">sma = { period |
list = []
list = []


Line 620: Line 620:


=={{header|C}}==
=={{header|C}}==
<syntaxhighlight lang=c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdarg.h>
Line 690: Line 690:
}</syntaxhighlight>
}</syntaxhighlight>


<syntaxhighlight lang=c>double v[] = { 1, 2, 3, 4, 5, 5, 4, 3, 2, 1 };
<syntaxhighlight lang="c">double v[] = { 1, 2, 3, 4, 5, 5, 4, 3, 2, 1 };


int main()
int main()
Line 713: Line 713:
{{works with|C sharp|C#|3}}
{{works with|C sharp|C#|3}}


<syntaxhighlight lang=csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Linq;
Line 759: Line 759:


=={{header|C++}}==
=={{header|C++}}==
<syntaxhighlight lang=cpp>
<syntaxhighlight lang="cpp">
#include <iostream>
#include <iostream>
#include <stddef.h>
#include <stddef.h>
Line 866: Line 866:
This version uses a persistent queue to hold the most recent ''p'' values.
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.
Each function returned from ''init-moving-average'' has its state in an atom holding a queue value.
<syntaxhighlight lang=clojure>(import '[clojure.lang PersistentQueue])
<syntaxhighlight lang="clojure">(import '[clojure.lang PersistentQueue])


(defn enqueue-max [q p n]
(defn enqueue-max [q p n]
Line 880: Line 880:


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
<syntaxhighlight lang=coffeescript>
<syntaxhighlight lang="coffeescript">
I = (P) ->
I = (P) ->
# The cryptic name "I" follows the problem description;
# The cryptic name "I" follows the problem description;
Line 945: 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.
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.


<syntaxhighlight lang=lisp>(defun simple-moving-average (period &aux
<syntaxhighlight lang="lisp">(defun simple-moving-average (period &aux
(sum 0) (count 0) (values (make-list period)) (pointer values))
(sum 0) (count 0) (values (make-list period)) (pointer values))
(setf (rest (last values)) values) ; construct circularity
(setf (rest (last values)) values) ; construct circularity
Line 959: Line 959:
Use
Use


<syntaxhighlight lang=lisp>(mapcar '(simple-moving-average period) list-of-values)</syntaxhighlight>
<syntaxhighlight lang="lisp">(mapcar '(simple-moving-average period) list-of-values)</syntaxhighlight>


=={{header|Crystal}}==
=={{header|Crystal}}==
<syntaxhighlight lang=ruby>def sma(n) Proc(Float64, Float64)
<syntaxhighlight lang="ruby">def sma(n) Proc(Float64, Float64)
a = Array(Float64).new
a = Array(Float64).new
->(x : Float64) {
->(x : Float64) {
Line 994: Line 994:
===Using a Closure===
===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.
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.
<syntaxhighlight lang=d>import std.stdio, std.traits, std.algorithm;
<syntaxhighlight lang="d">import std.stdio, std.traits, std.algorithm;


auto sma(T, int period)() pure nothrow @safe {
auto sma(T, int period)() pure nothrow @safe {
Line 1,033: Line 1,033:
keeping the data in the stack frame of the main function.
keeping the data in the stack frame of the main function.
Same output:
Same output:
<syntaxhighlight lang=d>import std.stdio, std.traits, std.algorithm;
<syntaxhighlight lang="d">import std.stdio, std.traits, std.algorithm;


struct SMA(T, int period) {
struct SMA(T, int period) {
Line 1,060: Line 1,060:
{{Trans|Pascal}}
{{Trans|Pascal}}
Small variation of [[#Pascal]].
Small variation of [[#Pascal]].
<syntaxhighlight lang=Delphi>
<syntaxhighlight lang="delphi">
program Simple_moving_average;
program Simple_moving_average;


Line 1,163: Line 1,163:
{{trans|C#}}
{{trans|C#}}


<syntaxhighlight lang=dyalect>func avg(xs) {
<syntaxhighlight lang="dyalect">func avg(xs) {
var acc = 0.0
var acc = 0.0
var c = 0
var c = 0
Line 1,200: Line 1,200:
The structure is the same as the implementation of [[Standard Deviation#E]].
The structure is the same as the implementation of [[Standard Deviation#E]].


<syntaxhighlight lang=e>pragma.enable("accumulator")
<syntaxhighlight lang="e">pragma.enable("accumulator")
def makeMovingAverage(period) {
def makeMovingAverage(period) {
def values := ([null] * period).diverge()
def values := ([null] * period).diverge()
Line 1,223: Line 1,223:
}</syntaxhighlight>
}</syntaxhighlight>


<div style="overflow: auto; max-height: 12em;"><syntaxhighlight lang=e>? for period in [3, 5] {
<div style="overflow: auto; max-height: 12em;"><syntaxhighlight lang="e">? for period in [3, 5] {
> def [insert, average] := makeMovingAverage(period)
> def [insert, average] := makeMovingAverage(period)
> println(`Period $period:`)
> println(`Period $period:`)
Line 1,258: Line 1,258:


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<syntaxhighlight lang=scheme>
<syntaxhighlight lang="scheme">
(lib 'tree) ;; queues operations
(lib 'tree) ;; queues operations


Line 1,292: Line 1,292:
=={{header|Elena}}==
=={{header|Elena}}==
ELENA 5.0 :
ELENA 5.0 :
<syntaxhighlight lang=elena>import system'routines;
<syntaxhighlight lang="elena">import system'routines;
import system'collections;
import system'collections;
import extensions;
import extensions;
Line 1,363: Line 1,363:
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.
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.


<syntaxhighlight lang=elixir>$ cat simple-moving-avg.exs
<syntaxhighlight lang="elixir">$ cat simple-moving-avg.exs
#!/usr/bin/env elixir
#!/usr/bin/env elixir


Line 1,406: Line 1,406:
SMA.run</syntaxhighlight>
SMA.run</syntaxhighlight>


<syntaxhighlight lang=bash>#!/bin/bash
<syntaxhighlight lang="bash">#!/bin/bash
elixir ./simple-moving-avg.exs <<EOF
elixir ./simple-moving-avg.exs <<EOF
1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1
Line 1,458: Line 1,458:


=={{header|Erlang}}==
=={{header|Erlang}}==
<syntaxhighlight lang=erlang>main() ->
<syntaxhighlight lang="erlang">main() ->
SMA3 = sma(3),
SMA3 = sma(3),
SMA5 = sma(5),
SMA5 = sma(5),
Line 1,501: Line 1,501:


{{out}}
{{out}}
<syntaxhighlight lang=erlang>9> sma:main().
<syntaxhighlight lang="erlang">9> sma:main().
Added 1, sma(3) -> 1.000000, sma(5) -> 1.000000
Added 1, sma(3) -> 1.000000, sma(5) -> 1.000000
Added 2, sma(3) -> 1.500000, sma(5) -> 1.500000
Added 2, sma(3) -> 1.500000, sma(5) -> 1.500000
Line 1,520: Line 1,520:
Matrix languages have routines to compute the gliding avarages for a given sequence of items.
Matrix languages have routines to compute the gliding avarages for a given sequence of items.


<syntaxhighlight lang=Euler Math Toolbox>
<syntaxhighlight lang="euler math toolbox">
>n=1000; m=100; x=random(1,n);
>n=1000; m=100; x=random(1,n);
>x10=fold(x,ones(1,m)/m);
>x10=fold(x,ones(1,m)/m);
Line 1,528: Line 1,528:
It is less efficient to loop as in the following commands.
It is less efficient to loop as in the following commands.


<syntaxhighlight lang=Euler Math Toolbox>
<syntaxhighlight lang="euler math toolbox">
>function store (x:number, v:vector, n:index) ...
>function store (x:number, v:vector, n:index) ...
$if cols(v)<n then return v|x;
$if cols(v)<n then return v|x;
Line 1,562: Line 1,562:


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang=fsharp>let sma period f (list:float list) =
<syntaxhighlight lang="fsharp">let sma period f (list:float list) =
let sma_aux queue v =
let sma_aux queue v =
let q = Seq.truncate period (v :: queue)
let q = Seq.truncate period (v :: queue)
Line 1,582: Line 1,582:
=={{header|Factor}}==
=={{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.
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.
<syntaxhighlight lang=factor>USING: kernel interpolate io locals math.statistics prettyprint
<syntaxhighlight lang="factor">USING: kernel interpolate io locals math.statistics prettyprint
random sequences ;
random sequences ;
IN: rosetta-code.simple-moving-avg
IN: rosetta-code.simple-moving-avg
Line 1,618: Line 1,618:
=={{header|Fantom}}==
=={{header|Fantom}}==


<syntaxhighlight lang=fantom>
<syntaxhighlight lang="fantom">
class MovingAverage
class MovingAverage
{
{
Line 1,681: Line 1,681:


=={{header|Forth}}==
=={{header|Forth}}==
<syntaxhighlight lang=forth>: f+! ( f addr -- ) dup f@ f+ f! ;
<syntaxhighlight lang="forth">: f+! ( f addr -- ) dup f@ f+ f! ;
: ,f0s ( n -- ) falign 0 do 0e f, loop ;
: ,f0s ( n -- ) falign 0 do 0e f, loop ;


Line 1,711: Line 1,711:
=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
{{works with|Fortran|90 and later}}
<syntaxhighlight lang=fortran>program Movavg
<syntaxhighlight lang="fortran">program Movavg
implicit none
implicit none


Line 1,746: Line 1,746:


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<syntaxhighlight lang=freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Type FuncType As Function(As Double) As Double
Type FuncType As Function(As Double) As Double
Line 1,823: Line 1,823:


=={{header|GAP}}==
=={{header|GAP}}==
<syntaxhighlight lang=gap>MovingAverage := function(n)
<syntaxhighlight lang="gap">MovingAverage := function(n)
local sma, buffer, pos, sum, len;
local sma, buffer, pos, sum, len;
buffer := List([1 .. n], i -> 0);
buffer := List([1 .. n], i -> 0);
Line 1,852: Line 1,852:


=={{header|Go}}==
=={{header|Go}}==
<syntaxhighlight lang=go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 1,900: Line 1,900:
=={{header|Groovy}}==
=={{header|Groovy}}==
{{trans|Ruby}}
{{trans|Ruby}}
<syntaxhighlight lang=groovy>def simple_moving_average = { size ->
<syntaxhighlight lang="groovy">def simple_moving_average = { size ->
def nums = []
def nums = []
double total = 0.0
double total = 0.0
Line 1,921: Line 1,921:
Conform version to the requirement, function SMA called multiple times with just a number:
Conform version to the requirement, function SMA called multiple times with just a number:
{{works with|GHC|6.10.4}}
{{works with|GHC|6.10.4}}
<syntaxhighlight lang=Haskell>{-# LANGUAGE BangPatterns #-}
<syntaxhighlight lang="haskell">{-# LANGUAGE BangPatterns #-}


import Control.Monad
import Control.Monad
Line 1,960: Line 1,960:


{{works with|GHC|6.10.4}}
{{works with|GHC|6.10.4}}
<syntaxhighlight lang=Haskell>import Data.List
<syntaxhighlight lang="haskell">import Data.List
import Control.Arrow
import Control.Arrow
import Control.Monad
import Control.Monad
Line 1,974: Line 1,974:


{{works with|GHC|7.8.3}}
{{works with|GHC|7.8.3}}
<syntaxhighlight lang=Haskell>
<syntaxhighlight lang="haskell">
import Control.Monad
import Control.Monad
import Control.Monad.State
import Control.Monad.State
Line 2,009: Line 2,009:


=={{header|HicEst}}==
=={{header|HicEst}}==
<syntaxhighlight lang=HicEst>REAL :: n=10, nums(n)
<syntaxhighlight lang="hicest">REAL :: n=10, nums(n)


nums = (1,2,3,4,5, 5,4,3,2,1)
nums = (1,2,3,4,5, 5,4,3,2,1)
Line 2,047: Line 2,047:


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
<syntaxhighlight lang=unicon>procedure main(A)
<syntaxhighlight lang="unicon">procedure main(A)
sma := buildSMA(3) # Use better name than "I".
sma := buildSMA(3) # Use better name than "I".
every write(sma(!A))
every write(sma(!A))
Line 2,085: Line 2,085:
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:
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:


<syntaxhighlight lang=Unicon>import Utils
<syntaxhighlight lang="unicon">import Utils


procedure main(A)
procedure main(A)
Line 2,122: Line 2,122:
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:
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:


<syntaxhighlight lang=J> 5 (+/%#)\ 1 2 3 4 5 5 4 3 2 1 NB. not a solution for this task
<syntaxhighlight lang="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</syntaxhighlight>
3 3.8 4.2 4.2 3.8 3</syntaxhighlight>


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:
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:
<syntaxhighlight lang=j> lex =: 1 :'(a[n__a=.m#_.[a=.18!:3$~0)&(4 :''(+/%#)(#~1-128!:5)n__x=.1|.!.y n__x'')'</syntaxhighlight>
<syntaxhighlight lang="j"> lex =: 1 :'(a[n__a=.m#_.[a=.18!:3$~0)&(4 :''(+/%#)(#~1-128!:5)n__x=.1|.!.y n__x'')'</syntaxhighlight>
'''Example:'''
'''Example:'''
<syntaxhighlight lang=j> sma =: 5 lex
<syntaxhighlight lang="j"> sma =: 5 lex
sma&> 1 2 3 4 5 5 4 3 2 1
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</syntaxhighlight>
1 1.5 2 2.5 3 3.8 4.2 4.2 3.8 3</syntaxhighlight>
Line 2,135: Line 2,135:
Or, a more traditional approach could be used:
Or, a more traditional approach could be used:


<syntaxhighlight lang=j>avg=: +/ % #
<syntaxhighlight lang="j">avg=: +/ % #
SEQ=:''
SEQ=:''
moveAvg=:4 :0"0
moveAvg=:4 :0"0
Line 2,147: Line 2,147:
=={{header|Java}}==
=={{header|Java}}==
{{works with|Java|1.5+}}
{{works with|Java|1.5+}}
<syntaxhighlight lang=java5>import java.util.LinkedList;
<syntaxhighlight lang="java5">import java.util.LinkedList;
import java.util.Queue;
import java.util.Queue;


Line 2,211: Line 2,211:
=={{header|JavaScript}}==
=={{header|JavaScript}}==
===Using for loop===
===Using for loop===
<syntaxhighlight lang=javascript>function simple_moving_averager(period) {
<syntaxhighlight lang="javascript">function simple_moving_averager(period) {
var nums = [];
var nums = [];
return function(num) {
return function(num) {
Line 2,250: Line 2,250:
[http://jsfiddle.net/79xe381e/ JS Fiddle]
[http://jsfiddle.net/79xe381e/ JS Fiddle]


<syntaxhighlight lang=javascript>// single-sided
<syntaxhighlight lang="javascript">// single-sided
Array.prototype.simpleSMA=function(N) {
Array.prototype.simpleSMA=function(N) {
return this.map(
return this.map(
Line 2,277: Line 2,277:


=={{header|Julia}}==
=={{header|Julia}}==
<syntaxhighlight lang=julia>using Statistics</syntaxhighlight>
<syntaxhighlight lang="julia">using Statistics</syntaxhighlight>
The function wants specified the type of the data in the buffer and, if you want, the limit of the buffer.
The function wants specified the type of the data in the buffer and, if you want, the limit of the buffer.
<syntaxhighlight lang=julia>function movingaverage(::Type{T} = Float64; lim::Integer = -1) where T<:Real
<syntaxhighlight lang="julia">function movingaverage(::Type{T} = Float64; lim::Integer = -1) where T<:Real
buffer = Vector{T}(0)
buffer = Vector{T}(0)
if lim == -1
if lim == -1
Line 2,310: Line 2,310:


Non-stateful:
Non-stateful:
<syntaxhighlight lang=K>
<syntaxhighlight lang="k">
v:v,|v:1+!5
v:v,|v:1+!5
v
v
Line 2,323: Line 2,323:


Stateful:
Stateful:
<syntaxhighlight lang=K>
<syntaxhighlight lang="k">
sma:{n::x#_n; {n::1_ n,x; {avg x@&~_n~'x} n}}
sma:{n::x#_n; {n::1_ n,x; {avg x@&~_n~'x} n}}
Line 2,331: Line 2,331:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<syntaxhighlight lang=scala>// version 1.0.6
<syntaxhighlight lang="scala">// version 1.0.6


fun initMovingAverage(p: Int): (Double) -> Double {
fun initMovingAverage(p: Int): (Double) -> Double {
Line 2,369: Line 2,369:
=={{header|Lasso}}==
=={{header|Lasso}}==
{{incorrect|Lasso|routine is called with a list of multiple numbers rather than being called with individual numbers in succession.}}
{{incorrect|Lasso|routine is called with a list of multiple numbers rather than being called with individual numbers in succession.}}
<syntaxhighlight lang=Lasso>define simple_moving_average(a::array,s::integer)::decimal => {
<syntaxhighlight lang="lasso">define simple_moving_average(a::array,s::integer)::decimal => {
#a->size == 0 ? return 0.00
#a->size == 0 ? return 0.00
#s == 0 ? return 0.00
#s == 0 ? return 0.00
Line 2,421: Line 2,421:
The interesting thing here is how to implement an equivalent of a stateful function.
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
For sample output see http://libertybasic.conforums.com/index.cgi?board=open&action=display&num=1322956720
<syntaxhighlight lang=lb>
<syntaxhighlight lang="lb">
dim v$( 100) ' Each array term stores a particular SMA of period p in p*10 bytes
dim v$( 100) ' Each array term stores a particular SMA of period p in p*10 bytes


Line 2,499: Line 2,499:
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.
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.


<syntaxhighlight lang=logo>to average :l
<syntaxhighlight lang="logo">to average :l
output quotient apply "sum :l count :l
output quotient apply "sum :l count :l
end
end
Line 2,525: Line 2,525:
If namespace pollution is a concern, UCB Logo supplies a GENSYM command to obtain unique names in order to avoid collisions.
If namespace pollution is a concern, UCB Logo supplies a GENSYM command to obtain unique names in order to avoid collisions.


<syntaxhighlight lang=logo> ...
<syntaxhighlight lang="logo"> ...
localmake "qn word :name gensym
localmake "qn word :name gensym
...
...
Line 2,535: Line 2,535:
=={{header|Lua}}==
=={{header|Lua}}==


<syntaxhighlight lang=lua>function sma(period)
<syntaxhighlight lang="lua">function sma(period)
local t = {}
local t = {}
function sum(a, ...)
function sum(a, ...)
Line 2,558: Line 2,558:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
This version uses a list entry so it can use the built-in function.
This version uses a list entry so it can use the built-in function.
<syntaxhighlight lang=Mathematica>MA[x_List, r_] := Join[Table[Mean[x[[1;;y]]],{y,r-1}], MovingAverage[x,r]]</syntaxhighlight>
<syntaxhighlight lang="mathematica">MA[x_List, r_] := Join[Table[Mean[x[[1;;y]]],{y,r-1}], MovingAverage[x,r]]</syntaxhighlight>


This version is stateful instead.
This version is stateful instead.
<syntaxhighlight lang=Mathematica>MAData = {{}, 0};
<syntaxhighlight lang="mathematica">MAData = {{}, 0};
MAS[x_, t_: Null] :=
MAS[x_, t_: Null] :=
With[{r = If[t === Null, MAData[[2]], t]},
With[{r = If[t === Null, MAData[[2]], t]},
Line 2,588: Line 2,588:


Matlab and Octave provide very efficient and fast functions, that can be applied to vectors (i.e. series of data samples)
Matlab and Octave provide very efficient and fast functions, that can be applied to vectors (i.e. series of data samples)
<syntaxhighlight lang=Matlab> [m,z] = filter(ones(1,P),P,x); </syntaxhighlight>
<syntaxhighlight lang="matlab"> [m,z] = filter(ones(1,P),P,x); </syntaxhighlight>
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.
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.
<syntaxhighlight lang=Matlab> [m,z] = filter(ones(1,P),P,x,z); </syntaxhighlight>
<syntaxhighlight lang="matlab"> [m,z] = filter(ones(1,P),P,x,z); </syntaxhighlight>


=={{header|Mercury}}==
=={{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:
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:


<syntaxhighlight lang=Mercury> % state(period, list of floats from [newest, ..., oldest])
<syntaxhighlight lang="mercury"> % state(period, list of floats from [newest, ..., oldest])
:- type state ---> state(int, list(float)).
:- type state ---> state(int, list(float)).


Line 2,611: Line 2,611:


We define an SMA class, which can be configured with the desired window size (P).
We define an SMA class, which can be configured with the desired window size (P).
<syntaxhighlight lang=MiniScript>SMA = {}
<syntaxhighlight lang="miniscript">SMA = {}
SMA.P = 5 // (a default; may be overridden)
SMA.P = 5 // (a default; may be overridden)
SMA.buffer = null
SMA.buffer = null
Line 2,645: Line 2,645:
=={{header|NetRexx}}==
=={{header|NetRexx}}==
{{trans|Java}}
{{trans|Java}}
<syntaxhighlight lang=NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
options replace format comments java crossref symbols nobinary


Line 2,736: Line 2,736:


=={{header|Nim}}==
=={{header|Nim}}==
<syntaxhighlight lang=nim>import deques
<syntaxhighlight lang="nim">import deques


proc simplemovingaverage(period: int): auto =
proc simplemovingaverage(period: int): auto =
Line 2,789: Line 2,789:
=={{header|Objeck}}==
=={{header|Objeck}}==
{{trans|Java}}
{{trans|Java}}
<syntaxhighlight lang=objeck>
<syntaxhighlight lang="objeck">
use Collection;
use Collection;


Line 2,864: Line 2,864:
=={{header|Objective-C}}==
=={{header|Objective-C}}==


<syntaxhighlight lang=objc>#import <Foundation/Foundation.h>
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h>


@interface MovingAverage : NSObject {
@interface MovingAverage : NSObject {
Line 2,985: Line 2,985:


=={{header|OCaml}}==
=={{header|OCaml}}==
<syntaxhighlight lang=ocaml>let sma (n, s, q) x =
<syntaxhighlight lang="ocaml">let sma (n, s, q) x =
let l = Queue.length q and s = s +. x in
let l = Queue.length q and s = s +. x in
Queue.push x q;
Queue.push x q;
Line 3,039: Line 3,039:


More imperatively:
More imperatively:
<syntaxhighlight lang=ocaml>let sma_create period =
<syntaxhighlight lang="ocaml">let sma_create period =
let q = Queue.create ()
let q = Queue.create ()
and sum = ref 0.0 in
and sum = ref 0.0 in
Line 3,067: Line 3,067:
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.
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.


<syntaxhighlight lang=oforth>import: parallel
<syntaxhighlight lang="oforth">import: parallel


: createSMA(period)
: createSMA(period)
Line 3,076: Line 3,076:
Usage:
Usage:


<syntaxhighlight lang=oforth>: test
<syntaxhighlight lang="oforth">: test
| sma3 sma5 l |
| sma3 sma5 l |
3 createSMA -> sma3
3 createSMA -> sma3
Line 3,095: Line 3,095:
=={{header|ooRexx}}==
=={{header|ooRexx}}==
ooRexx does not have stateful functions, but the same effect can be achieved by using object instances.
ooRexx does not have stateful functions, but the same effect can be achieved by using object instances.
<syntaxhighlight lang=ooRexx>
<syntaxhighlight lang="oorexx">
testdata = .array~of(1, 2, 3, 4, 5, 5, 4, 3, 2, 1)
testdata = .array~of(1, 2, 3, 4, 5, 5, 4, 3, 2, 1)


Line 3,169: Line 3,169:


=={{header|OxygenBasic}}==
=={{header|OxygenBasic}}==
<syntaxhighlight lang=oxygenbasic>def max 1000
<syntaxhighlight lang="oxygenbasic">def max 1000


Class MovingAverage
Class MovingAverage
Line 3,214: Line 3,214:


=={{header|Oz}}==
=={{header|Oz}}==
<syntaxhighlight lang=oz>declare
<syntaxhighlight lang="oz">declare


fun {CreateSMA Period}
fun {CreateSMA Period}
Line 3,244: Line 3,244:
=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
Partial implementation: does not (yet?) create different stores on each invocation.
Partial implementation: does not (yet?) create different stores on each invocation.
<syntaxhighlight lang=parigp>sma_per(n)={
<syntaxhighlight lang="parigp">sma_per(n)={
sma_v=vector(n);
sma_v=vector(n);
sma_i = 0;
sma_i = 0;
Line 3,253: Line 3,253:
{{works with|Free 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.
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.
<syntaxhighlight lang=Pascal>program sma;
<syntaxhighlight lang="pascal">program sma;
type
type
tsma = record
tsma = record
Line 3,352: Line 3,352:
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>:
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>:


<syntaxhighlight lang=perl>sub sma_generator {
<syntaxhighlight lang="perl">sub sma_generator {
my $period = shift;
my $period = shift;
my (@list, $sum);
my (@list, $sum);
Line 3,382: Line 3,382:
=={{header|Phix}}==
=={{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.
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.
<!--<syntaxhighlight lang=Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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>
<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,436: Line 3,436:
<!--</syntaxhighlight>-->
<!--</syntaxhighlight>-->
and the main file is:
and the main file is:
<!--<syntaxhighlight lang=Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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>
<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,465: Line 3,465:


=={{header|Picat}}==
=={{header|Picat}}==
<syntaxhighlight lang=Picat>main =>
<syntaxhighlight lang="picat">main =>
L=[1, 2, 3, 4, 5, 5, 4, 3, 2, 1],
L=[1, 2, 3, 4, 5, 5, 4, 3, 2, 1],
Map3 = new_map([p=3]),
Map3 = new_map([p=3]),
Line 3,497: Line 3,497:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<syntaxhighlight lang=PicoLisp>(de sma (@Len)
<syntaxhighlight lang="picolisp">(de sma (@Len)
(curry (@Len (Data)) (N)
(curry (@Len (Data)) (N)
(push 'Data N)
(push 'Data N)
(and (nth Data @Len) (con @)) # Truncate
(and (nth Data @Len) (con @)) # Truncate
(*/ (apply + Data) (length Data)) ) )</syntaxhighlight>
(*/ (apply + Data) (length Data)) ) )</syntaxhighlight>
<syntaxhighlight lang=PicoLisp>(def 'sma3 (sma 3))
<syntaxhighlight lang="picolisp">(def 'sma3 (sma 3))
(def 'sma5 (sma 5))
(def 'sma5 (sma 5))


Line 3,527: Line 3,527:
=={{header|PL/I}}==
=={{header|PL/I}}==
===version 1===
===version 1===
<syntaxhighlight lang=pli>SMA: procedure (N) returns (float byaddr);
<syntaxhighlight lang="pli">SMA: procedure (N) returns (float byaddr);
declare N fixed;
declare N fixed;
declare A(*) fixed controlled,
declare A(*) fixed controlled,
Line 3,549: Line 3,549:
===version 2===
===version 2===
{{trans|REXX}}
{{trans|REXX}}
<syntaxhighlight lang=pli>*process source attributes xref;
<syntaxhighlight lang="pli">*process source attributes xref;
mat: Proc Options(main);
mat: Proc Options(main);
Dcl a(10) Dec Fixed(8,6);
Dcl a(10) Dec Fixed(8,6);
Line 3,610: Line 3,610:


=={{header|Pony}}==
=={{header|Pony}}==
<syntaxhighlight lang=Pony>
<syntaxhighlight lang="pony">
class MovingAverage
class MovingAverage
let period: USize
let period: USize
Line 3,652: Line 3,652:


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<syntaxhighlight lang=PowerShell>
<syntaxhighlight lang="powershell">
#This version allows a user to enter numbers one at a time to figure this into the SMA calculations
#This version allows a user to enter numbers one at a time to figure this into the SMA calculations


Line 3,682: Line 3,682:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<syntaxhighlight lang=PureBasic>Procedure.d SMA(Number, Period=0)
<syntaxhighlight lang="purebasic">Procedure.d SMA(Number, Period=0)
Static P
Static P
Static NewList L()
Static NewList L()
Line 3,706: Line 3,706:
Both implementations use the [http://www.doughellmann.com/PyMOTW/collections/index.html deque] datatype.
Both implementations use the [http://www.doughellmann.com/PyMOTW/collections/index.html deque] datatype.
===Procedural===
===Procedural===
<syntaxhighlight lang=python>from collections import deque
<syntaxhighlight lang="python">from collections import deque


def simplemovingaverage(period):
def simplemovingaverage(period):
Line 3,725: Line 3,725:


===Class based===
===Class based===
<syntaxhighlight lang=python>from collections import deque
<syntaxhighlight lang="python">from collections import deque


class Simplemovingaverage():
class Simplemovingaverage():
Line 3,748: Line 3,748:


'''Tests'''
'''Tests'''
<syntaxhighlight lang=python>if __name__ == '__main__':
<syntaxhighlight lang="python">if __name__ == '__main__':
for period in [3, 5]:
for period in [3, 5]:
print ("\nSIMPLE MOVING AVERAGE (procedural): PERIOD =", period)
print ("\nSIMPLE MOVING AVERAGE (procedural): PERIOD =", period)
Line 3,815: Line 3,815:
=={{header|Quackery}}==
=={{header|Quackery}}==


<syntaxhighlight lang=Quackery> [ $ "bigrat.qky" loadfile ] now!
<syntaxhighlight lang="quackery"> [ $ "bigrat.qky" loadfile ] now!


[ over size -
[ over size -
Line 3,869: Line 3,869:
=={{header|R}}==
=={{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.
This is easiest done with two functions: one to handle the state (i.e. the numbers already entered), and one to calculate the average.
<syntaxhighlight lang=R>#concat concatenates the new values to the existing vector of values, then discards any values that are too old.
<syntaxhighlight lang="r">#concat concatenates the new values to the existing vector of values, then discards any values that are too old.
lastvalues <- local(
lastvalues <- local(
{
{
Line 3,902: Line 3,902:


=={{header|Racket}}==
=={{header|Racket}}==
<syntaxhighlight lang=Racket>#lang racket
<syntaxhighlight lang="racket">#lang racket


(require data/queue)
(require data/queue)
Line 3,929: Line 3,929:


{{works with|Rakudo|2016.08}}
{{works with|Rakudo|2016.08}}
<syntaxhighlight lang=perl6>sub sma-generator (Int $P where * > 0) {
<syntaxhighlight lang="raku" line>sub sma-generator (Int $P where * > 0) {
sub ($x) {
sub ($x) {
state @a = 0 xx $P;
state @a = 0 xx $P;
Line 3,957: Line 3,957:


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.
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.
<syntaxhighlight lang=rexx>/*REXX program illustrates and displays a simple moving average using a constructed list*/
<syntaxhighlight 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*/
parse arg p q n . /*obtain optional arguments from the CL*/
if p=='' | p=="," then p= 3 /*Not specified? Then use the default.*/
if p=='' | p=="," then p= 3 /*Not specified? Then use the default.*/
Line 3,997: Line 3,997:
=={{header|Ring}}==
=={{header|Ring}}==
===version 1===
===version 1===
<syntaxhighlight lang=ring>
<syntaxhighlight lang="ring">
load "stdlib.ring"
load "stdlib.ring"
decimals(8)
decimals(8)
Line 4,045: Line 4,045:


===version 2===
===version 2===
<syntaxhighlight lang=ring>
<syntaxhighlight lang="ring">
load "stdlib.ring"
load "stdlib.ring"
decimals(8)
decimals(8)
Line 4,093: Line 4,093:


===version 3===
===version 3===
<syntaxhighlight lang=ring>
<syntaxhighlight lang="ring">


### RING: Function Moving Average. Bert Mariani 2016-06-22
### RING: Function Moving Average. Bert Mariani 2016-06-22
Line 4,169: Line 4,169:
=={{header|Ruby}}==
=={{header|Ruby}}==
A closure:
A closure:
<syntaxhighlight lang=ruby>def simple_moving_average(size)
<syntaxhighlight lang="ruby">def simple_moving_average(size)
nums = []
nums = []
sum = 0.0
sum = 0.0
Line 4,189: Line 4,189:


A class
A class
<syntaxhighlight lang=ruby>class MovingAverager
<syntaxhighlight lang="ruby">class MovingAverager
def initialize(size)
def initialize(size)
@size = size
@size = size
Line 4,219: Line 4,219:


=={{header|Run Basic}}==
=={{header|Run Basic}}==
<syntaxhighlight lang=runbasic>data 1,2,3,4,5,5,4,3,2,1
<syntaxhighlight lang="runbasic">data 1,2,3,4,5,5,4,3,2,1
dim sd(10) ' series data
dim sd(10) ' series data
global sd ' make it global so we all see it
global sd ' make it global so we all see it
Line 4,263: Line 4,263:
=={{header|Rust}}==
=={{header|Rust}}==
===Vector Based===
===Vector Based===
<syntaxhighlight lang=rust>struct SimpleMovingAverage {
<syntaxhighlight lang="rust">struct SimpleMovingAverage {
period: usize,
period: usize,
numbers: Vec<usize>
numbers: Vec<usize>
Line 4,304: Line 4,304:


===Double-ended Queue Based===
===Double-ended Queue Based===
<syntaxhighlight lang=rust>use std::collections::VecDeque;
<syntaxhighlight lang="rust">use std::collections::VecDeque;


struct SimpleMovingAverage {
struct SimpleMovingAverage {
Line 4,371: Line 4,371:


=={{header|Scala}}==
=={{header|Scala}}==
<syntaxhighlight lang=scala>class MovingAverage(period: Int) {
<syntaxhighlight lang="scala">class MovingAverage(period: Int) {
private var queue = new scala.collection.mutable.Queue[Double]()
private var queue = new scala.collection.mutable.Queue[Double]()
def apply(n: Double) = {
def apply(n: Double) = {
Line 4,419: Line 4,419:


=={{header|Scheme}}==
=={{header|Scheme}}==
<syntaxhighlight lang=scheme>(define ((simple-moving-averager size . nums) num)
<syntaxhighlight lang="scheme">(define ((simple-moving-averager size . nums) num)
(set! nums (cons num (if (= (length nums) size) (reverse (cdr (reverse nums))) nums)))
(set! nums (cons num (if (= (length nums) size) (reverse (cdr (reverse nums))) nums)))
(/ (apply + nums) (length nums)))
(/ (apply + nums) (length nums)))
Line 4,433: Line 4,433:
=={{header|Sidef}}==
=={{header|Sidef}}==
Implemented with closures:
Implemented with closures:
<syntaxhighlight lang=ruby>func simple_moving_average(period) {
<syntaxhighlight lang="ruby">func simple_moving_average(period) {


var list = []
var list = []
Line 4,457: Line 4,457:


Implemented as a class:
Implemented as a class:
<syntaxhighlight lang=ruby>class sma_generator(period, list=[], sum=0) {
<syntaxhighlight lang="ruby">class sma_generator(period, list=[], sum=0) {


method SMA(number) {
method SMA(number) {
Line 4,494: Line 4,494:
{{works with|GNU Smalltalk}}
{{works with|GNU Smalltalk}}


<syntaxhighlight lang=smalltalk>Object subclass: MovingAverage [
<syntaxhighlight lang="smalltalk">Object subclass: MovingAverage [
|valueCollection period collectedNumber sum|
|valueCollection period collectedNumber sum|
MovingAverage class >> newWithPeriod: thePeriod [
MovingAverage class >> newWithPeriod: thePeriod [
Line 4,526: Line 4,526:
].</syntaxhighlight>
].</syntaxhighlight>


<syntaxhighlight lang=smalltalk>|sma3 sma5|
<syntaxhighlight lang="smalltalk">|sma3 sma5|


sma3 := MovingAverage newWithPeriod: 3.
sma3 := MovingAverage newWithPeriod: 3.
Line 4,541: Line 4,541:
{{trans|Rust}}
{{trans|Rust}}


<syntaxhighlight lang=swift>struct SimpleMovingAverage {
<syntaxhighlight lang="swift">struct SimpleMovingAverage {
var period: Int
var period: Int
var numbers = [Double]()
var numbers = [Double]()
Line 4,597: Line 4,597:
=={{header|Tcl}}==
=={{header|Tcl}}==
{{works with|Tcl|8.6}} or {{libheader|TclOO}}
{{works with|Tcl|8.6}} or {{libheader|TclOO}}
<syntaxhighlight lang=tcl>oo::class create SimpleMovingAverage {
<syntaxhighlight lang="tcl">oo::class create SimpleMovingAverage {
variable vals idx
variable vals idx
constructor {{period 3}} {
constructor {{period 3}} {
Line 4,609: Line 4,609:
}</syntaxhighlight>
}</syntaxhighlight>
Demonstration:
Demonstration:
<syntaxhighlight lang=tcl>SimpleMovingAverage create averager3
<syntaxhighlight lang="tcl">SimpleMovingAverage create averager3
SimpleMovingAverage create averager5 5
SimpleMovingAverage create averager5 5
foreach n {1 2 3 4 5 5 4 3 2 1} {
foreach n {1 2 3 4 5 5 4 3 2 1} {
Line 4,632: Line 4,632:
Press <tt>ON</tt> to terminate the program.
Press <tt>ON</tt> to terminate the program.


<syntaxhighlight lang=ti83b>:1->C
<syntaxhighlight lang="ti83b">:1->C
:While 1
:While 1
:Prompt I
:Prompt I
Line 4,645: Line 4,645:


Function that returns a list containing the averaged data of the supplied argument
Function that returns a list containing the averaged data of the supplied argument
<syntaxhighlight lang=ti89b>movinavg(list,p)
<syntaxhighlight lang="ti89b">movinavg(list,p)
Func
Func
Local r, i, z
Local r, i, z
Line 4,659: Line 4,659:


Program that returns a simple value at each invocation:
Program that returns a simple value at each invocation:
<syntaxhighlight lang=ti89b>movinav2(x_,v_)
<syntaxhighlight lang="ti89b">movinav2(x_,v_)
Prgm
Prgm
If getType(x_)="STR" Then
If getType(x_)="STR" Then
Line 4,705: Line 4,705:
=={{header|VBA}}==
=={{header|VBA}}==
This is a "simple" moving average.
This is a "simple" moving average.
<syntaxhighlight lang=vb>Class sma
<syntaxhighlight lang="vb">Class sma
'to be stored in a class module with name "sma"
'to be stored in a class module with name "sma"
Private n As Integer 'period
Private n As Integer 'period
Line 4,749: Line 4,749:


=={{header|VBScript}}==
=={{header|VBScript}}==
<syntaxhighlight lang=vb>data = "1,2,3,4,5,5,4,3,2,1"
<syntaxhighlight lang="vb">data = "1,2,3,4,5,5,4,3,2,1"
token = Split(data,",")
token = Split(data,",")
stream = ""
stream = ""
Line 4,804: Line 4,804:
=={{header|Vlang}}==
=={{header|Vlang}}==
{{trans|Go}}
{{trans|Go}}
<syntaxhighlight lang=vlang>fn sma(period int) fn(f64) f64 {
<syntaxhighlight lang="vlang">fn sma(period int) fn(f64) f64 {
mut i := int(0)
mut i := int(0)
mut sum := f64(0)
mut sum := f64(0)
Line 4,848: Line 4,848:
{{trans|Go}}
{{trans|Go}}
{{libheader|Wren-fmt}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang=ecmascript>import "/fmt" for Fmt
<syntaxhighlight lang="ecmascript">import "/fmt" for Fmt


var sma = Fn.new { |period|
var sma = Fn.new { |period|
Line 4,890: Line 4,890:


=={{header|zkl}}==
=={{header|zkl}}==
<syntaxhighlight lang=zkl>fcn SMA(P){
<syntaxhighlight lang="zkl">fcn SMA(P){
fcn(n,ns,P){
fcn(n,ns,P){
sz:=ns.append(n.toFloat()).len();
sz:=ns.append(n.toFloat()).len();
Line 4,900: Line 4,900:
fp1 creates a partial application fixing the (in this case) the second and third
fp1 creates a partial application fixing the (in this case) the second and third
parameters
parameters
<syntaxhighlight lang=zkl>T(1,2,3,4,5,5,4,3,2,1).apply(SMA(3)).println();
<syntaxhighlight 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();</syntaxhighlight>
T(1,2,3,4,5,5,4,3,2,1).apply(SMA(5)).println();</syntaxhighlight>
{{out}}
{{out}}