Jump to content

Averages/Simple moving average: Difference between revisions

m
Automated syntax highlighting fixup (second round - minor fixes)
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
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}}
<syntaxhighlight lang="11l">T SMA
[Float] data
sum = 0.0
Line 85:
=={{header|360 Assembly}}==
{{trans|PL/I}}
<syntaxhighlight lang="360asm">* Averages/Simple moving average 26/08/2015
AVGSMA CSECT
USING AVGSMA,R12
Line 193:
 
moving.ads:
<syntaxhighlight lang=Ada"ada">generic
Max_Elements : Positive;
type Number is digits <>;
Line 203:
 
moving.adb:
<syntaxhighlight lang=Ada"ada">with Ada.Containers.Vectors;
 
package body Moving is
Line 245:
 
main.adb:
<syntaxhighlight lang=Ada"ada">with Ada.Text_IO;
with Moving;
procedure Main is
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'''.
<syntaxhighlight lang=Algol68"algol68">MODE SMAOBJ = STRUCT(
LONG REAL sma,
LONG REAL sum,
Line 401:
ahk forum: [http://www.autohotkey.com/forum/post-276695.html#276695 discussion]
For Integers:
<syntaxhighlight lang=AutoHotkey"autohotkey">MsgBox % MovingAverage(5,3) ; 5, averaging length <- 3
MsgBox % MovingAverage(1) ; 3
MsgBox % MovingAverage(-3) ; 1
Line 420:
}</syntaxhighlight>
For floating point numbers:
<syntaxhighlight lang=AutoHotkey"autohotkey">MovingAverage(x,len="") { ; for floating point numbers
Static
Static n:=0, m:=10 ; default averaging length = 10
Line 433:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">#!/usr/bin/awk -f
# Moving average over the first column of a data file
BEGIN {
Line 449:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<syntaxhighlight 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 512:
 
=={{header|Bracmat}}==
<syntaxhighlight lang="bracmat">( ( I
= buffer
. (new$=):?freshEmptyBuffer
Line 564:
=={{header|Brat}}==
Object version
<syntaxhighlight lang="brat">
SMA = object.new
 
Line 589:
Function version
 
<syntaxhighlight lang="brat">sma = { period |
list = []
 
Line 620:
 
=={{header|C}}==
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
Line 690:
}</syntaxhighlight>
 
<syntaxhighlight lang="c">double v[] = { 1, 2, 3, 4, 5, 5, 4, 3, 2, 1 };
 
int main()
Line 713:
{{works with|C sharp|C#|3}}
 
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 759:
 
=={{header|C++}}==
<syntaxhighlight lang="cpp">
#include <iostream>
#include <stddef.h>
Line 866:
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.
<syntaxhighlight lang="clojure">(import '[clojure.lang PersistentQueue])
 
(defn enqueue-max [q p n]
Line 880:
 
=={{header|CoffeeScript}}==
<syntaxhighlight lang="coffeescript">
I = (P) ->
# The cryptic name "I" follows the problem description;
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.
 
<syntaxhighlight 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 959:
Use
 
<syntaxhighlight lang="lisp">(mapcar '(simple-moving-average period) list-of-values)</syntaxhighlight>
 
=={{header|Crystal}}==
<syntaxhighlight lang="ruby">def sma(n) Proc(Float64, Float64)
a = Array(Float64).new
->(x : Float64) {
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.
<syntaxhighlight lang="d">import std.stdio, std.traits, std.algorithm;
 
auto sma(T, int period)() pure nothrow @safe {
Line 1,033:
keeping the data in the stack frame of the main function.
Same output:
<syntaxhighlight lang="d">import std.stdio, std.traits, std.algorithm;
 
struct SMA(T, int period) {
Line 1,060:
{{Trans|Pascal}}
Small variation of [[#Pascal]].
<syntaxhighlight lang=Delphi"delphi">
program Simple_moving_average;
 
Line 1,163:
{{trans|C#}}
 
<syntaxhighlight lang="dyalect">func avg(xs) {
var acc = 0.0
var c = 0
Line 1,200:
The structure is the same as the implementation of [[Standard Deviation#E]].
 
<syntaxhighlight lang="e">pragma.enable("accumulator")
def makeMovingAverage(period) {
def values := ([null] * period).diverge()
Line 1,223:
}</syntaxhighlight>
 
<div style="overflow: auto; max-height: 12em;"><syntaxhighlight lang="e">? for period in [3, 5] {
> def [insert, average] := makeMovingAverage(period)
> println(`Period $period:`)
Line 1,258:
 
=={{header|EchoLisp}}==
<syntaxhighlight lang="scheme">
(lib 'tree) ;; queues operations
 
Line 1,292:
=={{header|Elena}}==
ELENA 5.0 :
<syntaxhighlight lang="elena">import system'routines;
import system'collections;
import extensions;
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.
 
<syntaxhighlight lang="elixir">$ cat simple-moving-avg.exs
#!/usr/bin/env elixir
 
Line 1,406:
SMA.run</syntaxhighlight>
 
<syntaxhighlight 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
Line 1,458:
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">main() ->
SMA3 = sma(3),
SMA5 = sma(5),
Line 1,501:
 
{{out}}
<syntaxhighlight 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,520:
Matrix languages have routines to compute the gliding avarages for a given sequence of items.
 
<syntaxhighlight lang=Euler"euler Mathmath Toolboxtoolbox">
>n=1000; m=100; x=random(1,n);
>x10=fold(x,ones(1,m)/m);
Line 1,528:
It is less efficient to loop as in the following commands.
 
<syntaxhighlight lang=Euler"euler Mathmath Toolboxtoolbox">
>function store (x:number, v:vector, n:index) ...
$if cols(v)<n then return v|x;
Line 1,562:
 
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">let sma period f (list:float list) =
let sma_aux queue v =
let q = Seq.truncate period (v :: queue)
Line 1,582:
=={{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.
<syntaxhighlight lang="factor">USING: kernel interpolate io locals math.statistics prettyprint
random sequences ;
IN: rosetta-code.simple-moving-avg
Line 1,618:
=={{header|Fantom}}==
 
<syntaxhighlight lang="fantom">
class MovingAverage
{
Line 1,681:
 
=={{header|Forth}}==
<syntaxhighlight lang="forth">: f+! ( f addr -- ) dup f@ f+ f! ;
: ,f0s ( n -- ) falign 0 do 0e f, loop ;
 
Line 1,711:
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<syntaxhighlight lang="fortran">program Movavg
implicit none
 
Line 1,746:
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Type FuncType As Function(As Double) As Double
Line 1,823:
 
=={{header|GAP}}==
<syntaxhighlight lang="gap">MovingAverage := function(n)
local sma, buffer, pos, sum, len;
buffer := List([1 .. n], i -> 0);
Line 1,852:
 
=={{header|Go}}==
<syntaxhighlight lang="go">package main
 
import "fmt"
Line 1,900:
=={{header|Groovy}}==
{{trans|Ruby}}
<syntaxhighlight lang="groovy">def simple_moving_average = { size ->
def nums = []
double total = 0.0
Line 1,921:
Conform version to the requirement, function SMA called multiple times with just a number:
{{works with|GHC|6.10.4}}
<syntaxhighlight lang=Haskell"haskell">{-# LANGUAGE BangPatterns #-}
 
import Control.Monad
Line 1,960:
 
{{works with|GHC|6.10.4}}
<syntaxhighlight lang=Haskell"haskell">import Data.List
import Control.Arrow
import Control.Monad
Line 1,974:
 
{{works with|GHC|7.8.3}}
<syntaxhighlight lang=Haskell"haskell">
import Control.Monad
import Control.Monad.State
Line 2,009:
 
=={{header|HicEst}}==
<syntaxhighlight lang=HicEst"hicest">REAL :: n=10, nums(n)
 
nums = (1,2,3,4,5, 5,4,3,2,1)
Line 2,047:
 
=={{header|Icon}} and {{header|Unicon}}==
<syntaxhighlight lang="unicon">procedure main(A)
sma := buildSMA(3) # Use better name than "I".
every write(sma(!A))
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:
 
<syntaxhighlight lang=Unicon"unicon">import Utils
 
procedure main(A)
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:
 
<syntaxhighlight lang=J"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>
 
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>
'''Example:'''
<syntaxhighlight 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</syntaxhighlight>
Line 2,135:
Or, a more traditional approach could be used:
 
<syntaxhighlight lang="j">avg=: +/ % #
SEQ=:''
moveAvg=:4 :0"0
Line 2,147:
=={{header|Java}}==
{{works with|Java|1.5+}}
<syntaxhighlight lang="java5">import java.util.LinkedList;
import java.util.Queue;
 
Line 2,211:
=={{header|JavaScript}}==
===Using for loop===
<syntaxhighlight lang="javascript">function simple_moving_averager(period) {
var nums = [];
return function(num) {
Line 2,250:
[http://jsfiddle.net/79xe381e/ JS Fiddle]
 
<syntaxhighlight lang="javascript">// single-sided
Array.prototype.simpleSMA=function(N) {
return this.map(
Line 2,277:
 
=={{header|Julia}}==
<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.
<syntaxhighlight lang="julia">function movingaverage(::Type{T} = Float64; lim::Integer = -1) where T<:Real
buffer = Vector{T}(0)
if lim == -1
Line 2,310:
 
Non-stateful:
<syntaxhighlight lang=K"k">
v:v,|v:1+!5
v
Line 2,323:
 
Stateful:
<syntaxhighlight lang=K"k">
sma:{n::x#_n; {n::1_ n,x; {avg x@&~_n~'x} n}}
Line 2,331:
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.0.6
 
fun initMovingAverage(p: Int): (Double) -> Double {
Line 2,369:
=={{header|Lasso}}==
{{incorrect|Lasso|routine is called with a list of multiple numbers rather than being called with individual numbers in succession.}}
<syntaxhighlight lang=Lasso"lasso">define simple_moving_average(a::array,s::integer)::decimal => {
#a->size == 0 ? return 0.00
#s == 0 ? return 0.00
Line 2,421:
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">
dim v$( 100) ' Each array term stores a particular SMA of period p in p*10 bytes
 
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.
 
<syntaxhighlight lang="logo">to average :l
output quotient apply "sum :l count :l
end
Line 2,525:
If namespace pollution is a concern, UCB Logo supplies a GENSYM command to obtain unique names in order to avoid collisions.
 
<syntaxhighlight lang="logo"> ...
localmake "qn word :name gensym
...
Line 2,535:
=={{header|Lua}}==
 
<syntaxhighlight lang="lua">function sma(period)
local t = {}
function sum(a, ...)
Line 2,558:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
This version uses a list entry so it can use the built-in function.
<syntaxhighlight lang=Mathematica"mathematica">MA[x_List, r_] := Join[Table[Mean[x[[1;;y]]],{y,r-1}], MovingAverage[x,r]]</syntaxhighlight>
 
This version is stateful instead.
<syntaxhighlight lang=Mathematica"mathematica">MAData = {{}, 0};
MAS[x_, t_: Null] :=
With[{r = If[t === Null, MAData[[2]], t]},
Line 2,588:
 
Matlab and Octave provide very efficient and fast functions, that can be applied to vectors (i.e. series of data samples)
<syntaxhighlight lang=Matlab"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.
<syntaxhighlight lang=Matlab"matlab"> [m,z] = filter(ones(1,P),P,x,z); </syntaxhighlight>
 
=={{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:
 
<syntaxhighlight lang=Mercury"mercury"> % state(period, list of floats from [newest, ..., oldest])
:- type state ---> state(int, list(float)).
 
Line 2,611:
 
We define an SMA class, which can be configured with the desired window size (P).
<syntaxhighlight lang=MiniScript"miniscript">SMA = {}
SMA.P = 5 // (a default; may be overridden)
SMA.buffer = null
Line 2,645:
=={{header|NetRexx}}==
{{trans|Java}}
<syntaxhighlight lang=NetRexx"netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 2,736:
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">import deques
 
proc simplemovingaverage(period: int): auto =
Line 2,789:
=={{header|Objeck}}==
{{trans|Java}}
<syntaxhighlight lang="objeck">
use Collection;
 
Line 2,864:
=={{header|Objective-C}}==
 
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
@interface MovingAverage : NSObject {
Line 2,985:
 
=={{header|OCaml}}==
<syntaxhighlight lang="ocaml">let sma (n, s, q) x =
let l = Queue.length q and s = s +. x in
Queue.push x q;
Line 3,039:
 
More imperatively:
<syntaxhighlight lang="ocaml">let sma_create period =
let q = Queue.create ()
and sum = ref 0.0 in
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.
 
<syntaxhighlight lang="oforth">import: parallel
 
: createSMA(period)
Line 3,076:
Usage:
 
<syntaxhighlight lang="oforth">: test
| sma3 sma5 l |
3 createSMA -> sma3
Line 3,095:
=={{header|ooRexx}}==
ooRexx does not have stateful functions, but the same effect can be achieved by using object instances.
<syntaxhighlight lang=ooRexx"oorexx">
testdata = .array~of(1, 2, 3, 4, 5, 5, 4, 3, 2, 1)
 
Line 3,169:
 
=={{header|OxygenBasic}}==
<syntaxhighlight lang="oxygenbasic">def max 1000
 
Class MovingAverage
Line 3,214:
 
=={{header|Oz}}==
<syntaxhighlight lang="oz">declare
 
fun {CreateSMA Period}
Line 3,244:
=={{header|PARI/GP}}==
Partial implementation: does not (yet?) create different stores on each invocation.
<syntaxhighlight lang="parigp">sma_per(n)={
sma_v=vector(n);
sma_i = 0;
Line 3,253:
{{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.
<syntaxhighlight lang=Pascal"pascal">program sma;
type
tsma = record
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>:
 
<syntaxhighlight lang="perl">sub sma_generator {
my $period = shift;
my (@list, $sum);
Line 3,382:
=={{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.
<!--<syntaxhighlight lang=Phix"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,436:
<!--</syntaxhighlight>-->
and the main file is:
<!--<syntaxhighlight lang=Phix"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,465:
 
=={{header|Picat}}==
<syntaxhighlight lang=Picat"picat">main =>
L=[1, 2, 3, 4, 5, 5, 4, 3, 2, 1],
Map3 = new_map([p=3]),
Line 3,497:
 
=={{header|PicoLisp}}==
<syntaxhighlight lang=PicoLisp"picolisp">(de sma (@Len)
(curry (@Len (Data)) (N)
(push 'Data N)
(and (nth Data @Len) (con @)) # Truncate
(*/ (apply + Data) (length Data)) ) )</syntaxhighlight>
<syntaxhighlight lang=PicoLisp"picolisp">(def 'sma3 (sma 3))
(def 'sma5 (sma 5))
 
Line 3,527:
=={{header|PL/I}}==
===version 1===
<syntaxhighlight lang="pli">SMA: procedure (N) returns (float byaddr);
declare N fixed;
declare A(*) fixed controlled,
Line 3,549:
===version 2===
{{trans|REXX}}
<syntaxhighlight lang="pli">*process source attributes xref;
mat: Proc Options(main);
Dcl a(10) Dec Fixed(8,6);
Line 3,610:
 
=={{header|Pony}}==
<syntaxhighlight lang=Pony"pony">
class MovingAverage
let period: USize
Line 3,652:
 
=={{header|PowerShell}}==
<syntaxhighlight lang=PowerShell"powershell">
#This version allows a user to enter numbers one at a time to figure this into the SMA calculations
 
Line 3,682:
 
=={{header|PureBasic}}==
<syntaxhighlight lang=PureBasic"purebasic">Procedure.d SMA(Number, Period=0)
Static P
Static NewList L()
Line 3,706:
Both implementations use the [http://www.doughellmann.com/PyMOTW/collections/index.html deque] datatype.
===Procedural===
<syntaxhighlight lang="python">from collections import deque
 
def simplemovingaverage(period):
Line 3,725:
 
===Class based===
<syntaxhighlight lang="python">from collections import deque
 
class Simplemovingaverage():
Line 3,748:
 
'''Tests'''
<syntaxhighlight lang="python">if __name__ == '__main__':
for period in [3, 5]:
print ("\nSIMPLE MOVING AVERAGE (procedural): PERIOD =", period)
Line 3,815:
=={{header|Quackery}}==
 
<syntaxhighlight lang=Quackery"quackery"> [ $ "bigrat.qky" loadfile ] now!
 
[ over size -
Line 3,869:
=={{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.
<syntaxhighlight lang=R"r">#concat concatenates the new values to the existing vector of values, then discards any values that are too old.
lastvalues <- local(
{
Line 3,902:
 
=={{header|Racket}}==
<syntaxhighlight lang=Racket"racket">#lang racket
 
(require data/queue)
Line 3,929:
 
{{works with|Rakudo|2016.08}}
<syntaxhighlight lang=perl6"raku" line>sub sma-generator (Int $P where * > 0) {
sub ($x) {
state @a = 0 xx $P;
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.
<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*/
if p=='' | p=="," then p= 3 /*Not specified? Then use the default.*/
Line 3,997:
=={{header|Ring}}==
===version 1===
<syntaxhighlight lang="ring">
load "stdlib.ring"
decimals(8)
Line 4,045:
 
===version 2===
<syntaxhighlight lang="ring">
load "stdlib.ring"
decimals(8)
Line 4,093:
 
===version 3===
<syntaxhighlight lang="ring">
 
### RING: Function Moving Average. Bert Mariani 2016-06-22
Line 4,169:
=={{header|Ruby}}==
A closure:
<syntaxhighlight lang="ruby">def simple_moving_average(size)
nums = []
sum = 0.0
Line 4,189:
 
A class
<syntaxhighlight lang="ruby">class MovingAverager
def initialize(size)
@size = size
Line 4,219:
 
=={{header|Run Basic}}==
<syntaxhighlight 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,263:
=={{header|Rust}}==
===Vector Based===
<syntaxhighlight lang="rust">struct SimpleMovingAverage {
period: usize,
numbers: Vec<usize>
Line 4,304:
 
===Double-ended Queue Based===
<syntaxhighlight lang="rust">use std::collections::VecDeque;
 
struct SimpleMovingAverage {
Line 4,371:
 
=={{header|Scala}}==
<syntaxhighlight lang="scala">class MovingAverage(period: Int) {
private var queue = new scala.collection.mutable.Queue[Double]()
def apply(n: Double) = {
Line 4,419:
 
=={{header|Scheme}}==
<syntaxhighlight 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,433:
=={{header|Sidef}}==
Implemented with closures:
<syntaxhighlight lang="ruby">func simple_moving_average(period) {
 
var list = []
Line 4,457:
 
Implemented as a class:
<syntaxhighlight lang="ruby">class sma_generator(period, list=[], sum=0) {
 
method SMA(number) {
Line 4,494:
{{works with|GNU Smalltalk}}
 
<syntaxhighlight lang="smalltalk">Object subclass: MovingAverage [
|valueCollection period collectedNumber sum|
MovingAverage class >> newWithPeriod: thePeriod [
Line 4,526:
].</syntaxhighlight>
 
<syntaxhighlight lang="smalltalk">|sma3 sma5|
 
sma3 := MovingAverage newWithPeriod: 3.
Line 4,541:
{{trans|Rust}}
 
<syntaxhighlight lang="swift">struct SimpleMovingAverage {
var period: Int
var numbers = [Double]()
Line 4,597:
=={{header|Tcl}}==
{{works with|Tcl|8.6}} or {{libheader|TclOO}}
<syntaxhighlight lang="tcl">oo::class create SimpleMovingAverage {
variable vals idx
constructor {{period 3}} {
Line 4,609:
}</syntaxhighlight>
Demonstration:
<syntaxhighlight lang="tcl">SimpleMovingAverage create averager3
SimpleMovingAverage create averager5 5
foreach n {1 2 3 4 5 5 4 3 2 1} {
Line 4,632:
Press <tt>ON</tt> to terminate the program.
 
<syntaxhighlight lang="ti83b">:1->C
:While 1
:Prompt I
Line 4,645:
 
Function that returns a list containing the averaged data of the supplied argument
<syntaxhighlight lang="ti89b">movinavg(list,p)
Func
Local r, i, z
Line 4,659:
 
Program that returns a simple value at each invocation:
<syntaxhighlight lang="ti89b">movinav2(x_,v_)
Prgm
If getType(x_)="STR" Then
Line 4,705:
=={{header|VBA}}==
This is a "simple" moving average.
<syntaxhighlight lang="vb">Class sma
'to be stored in a class module with name "sma"
Private n As Integer 'period
Line 4,749:
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">data = "1,2,3,4,5,5,4,3,2,1"
token = Split(data,",")
stream = ""
Line 4,804:
=={{header|Vlang}}==
{{trans|Go}}
<syntaxhighlight lang="vlang">fn sma(period int) fn(f64) f64 {
mut i := int(0)
mut sum := f64(0)
Line 4,848:
{{trans|Go}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="ecmascript">import "/fmt" for Fmt
 
var sma = Fn.new { |period|
Line 4,890:
 
=={{header|zkl}}==
<syntaxhighlight lang="zkl">fcn SMA(P){
fcn(n,ns,P){
sz:=ns.append(n.toFloat()).len();
Line 4,900:
fp1 creates a partial application fixing the (in this case) the second and third
parameters
<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>
{{out}}
10,333

edits

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