Cumulative standard deviation: Difference between revisions

m
m (→‎{{header|R}}: Improved syntax.)
m (→‎{{header|Wren}}: Minor tidy)
 
(13 intermediate revisions by 9 users not shown)
Line 24:
=={{header|11l}}==
{{trans|Python:_Callable_class}}
<langsyntaxhighlight lang="11l">T SD
sum = 0.0
sum2 = 0.0
Line 37:
V sd_inst = SD()
L(value) [2, 4, 4, 4, 5, 5, 7, 9]
print(value‘ ’sd_inst(value))</langsyntaxhighlight>
 
{{out}}
Line 54:
For maximum compatibility, this program uses only the basic instruction set.
Part of the code length is due to the square root algorithm and to the nice output.
<langsyntaxhighlight lang="360asm">******** Standard deviation of a population
STDDEV CSECT
USING STDDEV,R13
Line 155:
BUF DC CL80'N=1 ITEM=1 AVG=1.234 STDDEV=1.234 '
YREGS
END STDDEV</langsyntaxhighlight>
{{out}}
<pre>N=1 ITEM=2 AVG=2.000 STDDEV=0.000
Line 169:
{{libheader|Action! Tool Kit}}
{{libheader|Action! Real Math}}
<langsyntaxhighlight Actionlang="action!">INCLUDE "H6:REALMATH.ACT"
 
REAL sum,sum2
Line 214:
Print(" sd=") PrintRE(sd)
OD
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Cumulative_standard_deviation.png Screenshot from Atari 8-bit computer]
Line 229:
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;
Line 265:
end loop;
end Test_Deviation;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 287:
<!-- {{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: the use of a UNION to mimic C's enumerated types is "experimental" and probably not typical of "production code". However it is a example of '''ALGOL 68'''s ''conformity CASE clause'' useful for classroom dissection.
<langsyntaxhighlight Algol68lang="algol68">MODE VALUE = STRUCT(CHAR value),
STDDEV = STRUCT(CHAR stddev),
MEAN = STRUCT(CHAR mean),
Line 338:
OD
)</langsyntaxhighlight>
{{out}}
<pre>
Line 357:
 
A code sample in an object oriented style:
<langsyntaxhighlight Algol68lang="algol68">MODE STAT = STRUCT(
LONG REAL sum,
LONG REAL sum2,
Line 432:
 
)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 451:
 
A simple - but "unpackaged" - code example, useful if the standard deviation is required on only one set of concurrent data:
<langsyntaxhighlight Algol68lang="algol68">LONG REAL sum, sum2;
INT n;
 
Line 466:
LONG REAL value = values[i];
printf(($2(xg(0,6))l$, value, sd(value)))
OD</langsyntaxhighlight>
{{out}}
<pre>
Line 482:
{{Trans|ALGOL 68}}
This is an Algol W version of the third, "unpackaged" Algol 68 sample, which was itself translated from Python.
<langsyntaxhighlight lang="algolw">begin
 
long real sum, sum2;
Line 506:
end for_i
 
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 523:
Accumulation over a fold:
 
<langsyntaxhighlight AppleScriptlang="applescript">-------------- CUMULATIVE STANDARD DEVIATION -------------
 
-- stdDevInc :: Accumulator -> Num -> Index -> Accumulator
Line 575:
end script
end if
end mReturn</langsyntaxhighlight>
 
{{Out}}
<langsyntaxhighlight AppleScriplang="applescrip">{0.0, 1.0, 0.942809041582, 0.866025403784,
0.979795897113, 1.0, 1.399708424448, 2.0}</langsyntaxhighlight>
 
 
Or as a map-accumulation:
 
<langsyntaxhighlight lang="applescript">-------------- CUMULATIVE STANDARD DEVIATION -------------
 
-- cumulativeStdDevns :: [Float] -> [Float]
Line 652:
end script
end if
end mReturn</langsyntaxhighlight>
 
{{Out}}
Line 659:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">arr: new []
loop [2 4 4 4 5 5 7 9] 'value [
'arr ++ value
print [value "->" deviation arr]
]</langsyntaxhighlight>
 
{{out}}
Line 677:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">Data := [2,4,4,4,5,5,7,9]
for k, v in Data {
Line 691:
return sqrt((sum2/n) - (((sum*sum)/n)/n))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 705:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f STANDARD_DEVIATION.AWK
BEGIN {
Line 725:
return(sqrt(variance))
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 740:
=={{header|Axiom}}==
{{incorrect|Axiom|It does not return the ''running'' standard deviation of the series.}}
We implement a domain with dependent type T with the operation + and identity 0:<langsyntaxhighlight Axiomlang="axiom">)abbrev package TESTD TestDomain
TestDomain(T : Join(Field,RadicalCategory)): Exports == Implementation where
R ==> Record(n : Integer, sum : T, ssq : T)
Line 756:
sd obj ==
mean : T := obj.sum / (obj.n::T)
sqrt(obj.ssq / (obj.n::T) - mean*mean)</langsyntaxhighlight>This can be called using:<syntaxhighlight lang Axiom="axiom">T ==> Expression Integer
D ==> TestDomain(T)
items := [2,4,4,4,5,5,7,9+x] :: List T;
Line 769:
 
(2) 2
Type: Expression(Integer)</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
Uses the MOD(array()) and SUM(array()) functions.
<langsyntaxhighlight lang="bbcbasic"> MAXITEMS = 100
FOR i% = 1 TO 8
READ n
Line 788:
i% += 1
list(i%) = n
= SQR(MOD(list())^2/i% - (SUM(list())/i%)^2)</langsyntaxhighlight>
{{out}}
<pre>
Line 803:
=={{header|C}}==
 
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <math.h>
Line 850:
so->sum2 += v*v;
return stat_obj_value(so, so->action);
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="c">double v[] = { 2,4,4,4,5,5,7,9 };
 
int main()
Line 864:
FREE_STAT_OBJECT(so);
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 891:
}
}
}</langsyntaxhighlight>
<pre>0
1
Line 903:
=={{header|C++}}==
No attempt to handle different types -- standard deviation is intrinsically a real number.
<langsyntaxhighlight lang="cpp">
#include <assert.hcassert>
#include <cmath>
#include <vector>
Line 943:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Clojure}}==
 
<langsyntaxhighlight lang="lisp">
(defn stateful-std-deviation[x]
(letfn [(std-dev[x]
Line 957:
(intern *ns* 'v (atom [])))
(std-dev x)))
</syntaxhighlight>
</lang>
 
=={{header|COBOL}}==
 
{{works with|OpenCOBOL|1.1}}
<langsyntaxhighlight lang="cobol">IDENTIFICATION DIVISION.
PROGRAM-ID. run-stddev.
environment division.
Line 1,033:
goback.
end program stddev.
</syntaxhighlight>
</lang>
<langsyntaxhighlight lang="cobol">sample output:
inp=002 stddev=+00000.0000
inp=004 stddev=+00001.0000
Line 1,043:
inp=007 stddev=+00001.3996
inp=009 stddev=+00002.0000
</syntaxhighlight>
</lang>
 
=={{header|CoffeeScript}}==
Uses a class instance to maintain state.
 
<langsyntaxhighlight lang="coffeescript">
class StandardDeviation
constructor: ->
Line 1,076:
 
"""
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,106:
 
=={{header|Common Lisp}}==
Since we don't care about the sample values once std dev is computed, we only need to keep track of their sum and square sums, hence:<langsyntaxhighlight lang="lisp">(defun running-stddev ()
(let ((sum 0) (sq 0) (n 0))
(lambda (x)
Line 1,122:
5 1.0
7 1.3997085
9 2.0</langsyntaxhighlight>
 
In the REPL, one step at a time:
<langsyntaxhighlight lang="lisp">CL-USER> (setf fn (running-stddev))
#<Interpreted Closure (:INTERNAL RUNNING-STDDEV) @ #x21b9a492>
CL-USER> (funcall fn 2)
Line 1,143:
CL-USER> (funcall fn 9)
2.0
</syntaxhighlight>
</lang>
 
=={{header|Component Pascal}}==
{{incorrect|Component Pascal|Function does not take numbers individually.}}
BlackBox Component Builder
<langsyntaxhighlight lang="oberon2">
MODULE StandardDeviation;
IMPORT StdLog, Args,Strings,Math;
Line 1,192:
END Do;
END StandardDeviation.
</syntaxhighlight>
</lang>
Execute: ^Q StandardDeviation.Do 2 4 4 4 5 5 7 9 ~<br/>
{{out}}
Line 1,210:
Use an object to keep state.
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">class StdDevAccumulator
def initialize
@n, @sum, @sum2 = 0, 0.0, 0.0
Line 1,225:
sd = StdDevAccumulator.new
i = 0
[2,4,4,4,5,5,7,9].each { |n| puts "adding #{n}: stddev of #{i+=1} samples is #{sd << n}" }</langsyntaxhighlight>
{{out}}
<pre>
Line 1,240:
===Closure===
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">def sdaccum
n, sum, sum2 = 0, 0.0, 0.0
->(num : Int32) do
Line 1,251:
 
sd = sdaccum
[2,4,4,4,5,5,7,9].each {|n| print sd.call(n), ", "}</langsyntaxhighlight>
{{out}}
<pre>0.0, 1.0, 0.9428090415820634, 0.8660254037844386, 0.9797958971132712, 1.0, 1.3997084244475304, 2.0</pre>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.math;
 
struct StdDev {
Line 1,283:
writefln("%e", stdev.getStdDev());
}
}</langsyntaxhighlight>
{{out}}
<pre>0.000000e+00
Line 1,305:
The algorithm is {{trans|Perl}} and the results were checked against [[#Python]].
 
<langsyntaxhighlight lang="e">def makeRunningStdDev() {
var sum := 0.0
var sumSquares := 0.0
Line 1,328:
return [insert, stddev]
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="e">? def [insert, stddev] := makeRunningStdDev()
# value: <insert>, <stddev>
 
Line 1,347:
1.0
1.3997084244475297
2.0</langsyntaxhighlight>
 
=={{header|EasyLang}}==
{{trans|Pascal}}
<syntaxhighlight lang="easylang">
global sum sum2 n .
proc sd x . r .
sum += x
sum2 += x * x
n += 1
r = sqrt (sum2 / n - sum * sum / n / n)
.
v[] = [ 2 4 4 4 5 5 7 9 ]
for v in v[]
sd v r
print v & " " & r
.
</syntaxhighlight>
 
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule Standard_deviation do
def add_sample( pid, n ), do: send( pid, {:add, n} )
Line 1,393 ⟶ 1,410:
end
 
Standard_deviation.task</langsyntaxhighlight>
 
{{out}}
Line 1,409 ⟶ 1,426:
=={{header|Emacs Lisp}}==
 
<syntaxhighlight lang="lisp">(defun running-std (items)
This implementation uses a temporary buffer (the central data structure of emacs) to have simple local variables.
(let ((running-sum 0)
(running-len 0)
(running-squared-sum 0)
(result 0))
(dolist (item items)
(setq running-sum (+ running-sum item))
(setq running-len (1+ running-len))
(setq running-squared-sum (+ running-squared-sum (* item item)))
(setq result (sqrt (- (/ running-squared-sum (float running-len))
(/ (* running-sum running-sum)
(float (* running-len running-len))))))
(message "%f" result))
result))
 
<lang lisp>(defun running-std '(x2 4 4 4 5 5 7 9))</syntaxhighlight>
; ensure that we have a float to avoid potential integer math errors.
(setq x (float x))
; define variables to use
(defvar running-sum 0 "the running sum of all known values")
(defvar running-len 0 "the running number of all known values")
(defvar running-squared-sum 0 "the running squared sum of all known values")
; and make them local to this buffer
(make-local-variable 'running-sum)
(make-local-variable 'running-len)
(make-local-variable 'running-squared-sum)
; now process the new value
(setq running-sum (+ running-sum x))
(setq running-len (1+ running-len))
(setq running-squared-sum (+ running-squared-sum (* x x)))
; and calculate the new standard deviation
(sqrt (- (/ running-squared-sum
running-len) (/ (* running-sum running-sum)
(* running-len running-len )))))</lang>
 
{{out}}
<lang lisp>(with-temp-buffer
(loop for i in '(2 4 4 4 5 5 7 9) do
(insert (number-to-string (running-std i)))
(newline))
(message (buffer-substring (point-min) (1- (point-max)))))
 
" 0.0000000
1.0000000
0.942809
0.9428090415820636
0.866025
0.8660254037844386
0.979796
0.9797958971132716
1.0000000
1.399708
1.399708424447531
2.000000
2.0"</lang>
2.0
 
{{libheader|Calc}}
Emacs Lisp with built-in Emacs Calc
 
<syntaxhighlight lang="lisp">(let ((x '(2 4 4 4 5 5 7 9)))
<lang emacs-lisp>
(string-to-number (calc-eval "sqrt(vpvar($1))" nil (append '(vec) x))))</syntaxhighlight>
(setq x '[2 4 4 4 5 5 7 9])
(string-to-number (calc-eval (format "sqrt(vpvar(%s))" x)))</lang>
 
{{libheader|generator.el}}
Emacs Lisp with generator library (introduced in Emacs 25.1)
 
<syntaxhighlight lang="lisp">;; lexical-binding: t
<lang emacs-lisp>
(require 'generator)
 
(setq lexical-binding t)
(iter-defun std-dev-gen (lst)
(let ((sum 0)
(avg 0)
(tmp '())
(std 0))
(dolist (i lst)
(setq i (float i))
Line 1,469 ⟶ 1,477:
(setq std 0)
(dolist (j tmp)
(setq std (+ std (expt (- j avg) 2))))
(setq std (/ std (length tmp)))
(setq std (sqrt std))
Line 1,475 ⟶ 1,483:
 
(let* ((test-data '(2 4 4 4 5 5 7 9))
(generator (std-dev-gen test-data)))
(dolist (i test-data)
(princ (formatmessage "with %d : %f" i (iter-next generator))))</syntaxhighlight>
(princ (format "%f\n" (iter-next generator))))) </lang>
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( standard_deviation ).
 
Line 1,521 ⟶ 1,528:
 
loop_calculate_average( Ns ) -> lists:sum( Ns ) / erlang:length( Ns ).
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,536 ⟶ 1,543:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: accessors io kernel math math.functions math.parser
sequences ;
IN: standard-deviator
Line 1,557 ⟶ 1,564:
{ 2 4 4 4 5 5 7 9 }
<standard-deviator> [ [ add-value ] curry each ] keep
current-std number>string print ;</langsyntaxhighlight>
 
=={{header|FOCAL}}==
<langsyntaxhighlight FOCALlang="focal">01.01 C-- TEST SET
01.10 S T(1)=2;S T(2)=4;S T(3)=4;S T(4)=4
01.20 S T(5)=5;S T(6)=5;S T(7)=7;S T(8)=9
Line 1,574 ⟶ 1,581:
02.10 S XN=0;S XS=0;S XQ=0
02.20 S XN=XN+1;S XS=XS+A;S XQ=XQ+A*A
02.30 S A=FSQT(XQ/XN - (XS/XN)^2)</langsyntaxhighlight>
 
{{out}}
Line 1,589 ⟶ 1,596:
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: f+! ( x addr -- ) dup f@ f+ f! ;
 
: st-count ( stats -- n ) f@ ;
Line 1,611 ⟶ 1,618:
fdup dup f+! float+
fdup f* f+!
std-stddev ;</langsyntaxhighlight>
 
This variation is more numerically stable when there are large numbers of samples or large sample ranges.
<langsyntaxhighlight lang="forth">: st-count ( stats -- n ) f@ ;
: st-mean ( stats -- mean ) float+ f@ ;
: st-nvar ( stats -- n*var ) 2 floats + f@ ;
Line 1,631 ⟶ 1,638:
( delta x )
dup f@ f- f* float+ f+! \ update nvar
st-stddev ;</langsyntaxhighlight>
Usage example:
<langsyntaxhighlight lang="forth">create stats 0e f, 0e f, 0e f,
 
2e stats st-add f. \ 0.
Line 1,643 ⟶ 1,650:
7e stats st-add f. \ 1.39970842444753
9e stats st-add f. \ 2.
</syntaxhighlight>
</lang>
 
=={{header|Fortran}}==
{{works with|Fortran|2003 and later}}
<langsyntaxhighlight lang="fortran">
program standard_deviation
implicit none
Line 1,697 ⟶ 1,704:
end function stddev
end program standard_deviation
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,718 ⟶ 1,725:
 
Incidentally, Fortran implementations rarely enable re-entrancy for the WRITE statement, so, since here the functions are invoked in a WRITE statement, the functions cannot themselves use WRITE statements, say for debugging.
<syntaxhighlight lang="fortran">
<lang Fortran>
REAL FUNCTION STDDEV(X) !Standard deviation for successive values.
REAL X !The latest value.
Line 1,793 ⟶ 1,800:
END DO !On to the next value.
END
</syntaxhighlight>
</lang>
 
Output: the second pair of columns have the calculations done with a working mean and thus accumulate deviations from that.
Line 1,872 ⟶ 1,879:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function calcStandardDeviation(number As Double) As Double
Line 1,901 ⟶ 1,908:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,919 ⟶ 1,926:
 
State maintained with a closure.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,941 ⟶ 1,948:
fmt.Println(r(x))
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,956 ⟶ 1,963:
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">List samples = []
 
def stdDev = { def sample ->
Line 1,968 ⟶ 1,975:
[2,4,4,4,5,5,7,9].each {
println "${stdDev(it)}"
}</langsyntaxhighlight>
 
{{out}}
Line 1,984 ⟶ 1,991:
We store the state in the <code>ST</code> monad using an <code>STRef</code>.
 
<langsyntaxhighlight lang="haskell">{-# LANGUAGE BangPatterns #-}
 
import Data.List (foldl') -- '
Line 2,011 ⟶ 2,018:
 
main = mapM_ print $ runST $
mkSD >>= forM [2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0]</langsyntaxhighlight>
 
 
Or, perhaps more simply, as a map-accumulation over an indexed list:
 
<langsyntaxhighlight Haskelllang="haskell">import Data.List (mapAccumL)
 
 
Line 2,033 ⟶ 2,040:
--------------------------- TEST -------------------------
main :: IO ()
main = mapM_ print $ cumulativeStdDevns [2, 4, 4, 4, 5, 5, 7, 9]</langsyntaxhighlight>
{{Out}}
<pre>0.0
Line 2,045 ⟶ 2,052:
 
=={{header|Haxe}}==
<langsyntaxhighlight lang="haxe">using Lambda;
 
class Main {
Line 2,067 ⟶ 2,074:
return Math.sqrt(average(store));
}
}</langsyntaxhighlight>
<pre>0
1
Line 2,078 ⟶ 2,085:
 
=={{header|HicEst}}==
<langsyntaxhighlight HicEstlang="hicest">REAL :: n=8, set(n), sum=0, sum2=0
 
set = (2,4,4,4,5,5,7,9)
Line 2,093 ⟶ 2,100:
sum2 = sum2 + x*x
stdev = ( sum2/k - (sum/k)^2) ^ 0.5
END</langsyntaxhighlight>
<pre>Adding 2 stdev = 0
Adding 4 stdev = 1
Line 2,104 ⟶ 2,111:
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main()
 
stddev() # reset state / empty
Line 2,125 ⟶ 2,132:
return sqrt( (sum2X / *X) - (sumX / *X)^2 )
}
end</langsyntaxhighlight>
{{out}}
<pre>stddev (so far) := 0.0
Line 2,137 ⟶ 2,144:
 
=={{header|IS-BASIC}}==
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "StDev.bas"
110 LET N=8
120 NUMERIC ARR(1 TO N)
Line 2,153 ⟶ 2,160:
240 PRINT J;"item =";ARR(J),"standard dev =";STDEV(J)
250 NEXT
260 DATA 2,4,4,4,5,5,7,9</langsyntaxhighlight>
 
=={{header|J}}==
 
J is block-oriented; it expresses algorithms with the semantics of all the data being available at once. It does not have native lexical closure or coroutine semantics. It is possible to implement these semantics in J; see [[Moving Average]] for an example. We will not reprise that here.
<langsyntaxhighlight lang="j"> mean=: +/ % #
dev=: - mean
stddevP=: [: %:@mean *:@dev NB. A) 3 equivalent defs for stddevP
Line 2,166 ⟶ 2,173:
 
stddevP\ 2 4 4 4 5 5 7 9
0 1 0.942809 0.866025 0.979796 1 1.39971 2</langsyntaxhighlight>
 
'''Alternatives:'''<br>
Using verbose names for J primitives.
<langsyntaxhighlight lang="j"> of =: @:
sqrt =: %:
sum =: +/
Line 2,180 ⟶ 2,187:
 
stddevP\ 2 4 4 4 5 5 7 9
0 1 0.942809 0.866025 0.979796 1 1.39971 2</langsyntaxhighlight>
 
{{trans|R}}<BR>
Or we could take a cue from the [[#R|R implementation]] and reverse the Bessel correction to stddev:
 
<langsyntaxhighlight lang="j"> require'stats'
(%:@:(%~<:)@:# * stddev)\ 2 4 4 4 5 5 7 9
0 1 0.942809 0.866025 0.979796 1 1.39971 2</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">public class StdDev {
int n = 0;
double sum = 0;
Line 2,211 ⟶ 2,218:
}
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Line 2,218 ⟶ 2,225:
 
Uses a closure.
<langsyntaxhighlight lang="javascript">function running_stddev() {
var n = 0;
var sum = 0.0;
Line 2,237 ⟶ 2,244:
 
// using WSH
WScript.Echo(stddev.join(', ');</langsyntaxhighlight>
 
{{out}}
Line 2,246 ⟶ 2,253:
Accumulating across a fold
 
<langsyntaxhighlight JavaScriptlang="javascript">(function (xs) {
return xs.reduce(function (a, x, i) {
Line 2,267 ⟶ 2,274:
}).stages
 
})([2, 4, 4, 4, 5, 5, 7, 9]);</langsyntaxhighlight>
 
{{Out}}
<langsyntaxhighlight JavaScriptlang="javascript">[0, 1, 0.9428090415820626, 0.8660254037844386,
0.9797958971132716, 1, 1.3997084244475297, 2]</langsyntaxhighlight>
 
====ES6====
 
As a map-accumulation:
<langsyntaxhighlight lang="javascript">(() => {
'use strict';
 
Line 2,330 ⟶ 2,337:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>[
Line 2,359 ⟶ 2,366:
where SSD is the sum of squared deviations about the mean.
 
<langsyntaxhighlight lang="jq"># Compute the standard deviation of the observations
# seen so far, given the current state as input:
def standard_deviation: .ssd / .n | sqrt;
Line 2,384 ⟶ 2,391:
 
# Begin:
simulate</langsyntaxhighlight>
'''Example 1'''
# observations.txt
Line 2,396 ⟶ 2,403:
9
{{Out}}
<syntaxhighlight lang="sh">
<lang sh>
$ jq -s -f Dynamic_standard_deviation.jq observations.txt
0
Line 2,406 ⟶ 2,413:
1.3997084244475302
1.9999999999999998
</syntaxhighlight>
</lang>
====Observations from a stream====
Recent versions of jq (after 1.4) support retention of state while processing a stream. This means that any generator (including generators that produce items indefinitely) can be used as the source of observations, without first having to capture all the observations, e.g. in a file or array.
<langsyntaxhighlight lang="jq"># requires jq version > 1.4
def simulate(stream):
foreach stream as $observation
(initial_state;
update_state($observation);
standard_deviation);</langsyntaxhighlight>
'''Example 2''':
simulate( range(0;10) )
Line 2,433 ⟶ 2,440:
 
The definitions of the filters update_state/1 and initial_state/0 are as above but are repeated so that this script is self-contained.
<langsyntaxhighlight lang="sh">#!/bin/bash
 
# jq is assumed to be on PATH
Line 2,470 ⟶ 2,477:
sed -n 1p <<< "$result"
state=$(sed -n 2p <<< "$result")
done</langsyntaxhighlight>
'''Example 3'''
<langsyntaxhighlight lang="sh">$ ./standard_deviation_server.sh
Next observation: 10
0
Line 2,479 ⟶ 2,486:
Next observation: 0
8.16496580927726
</syntaxhighlight>
</lang>
 
=={{header|Julia}}==
Use a closure to create a running standard deviation function.
<langsyntaxhighlight lang="julia">function makerunningstd(::Type{T} = Float64) where T
∑x = ∑x² = zero(T)
n = 0
Line 2,502 ⟶ 2,509:
for i in test
println(" - add $i → ", rstd(i))
end</langsyntaxhighlight>
 
{{out}}
Line 2,519 ⟶ 2,526:
{{trans|Java}}
Using a class to keep the running sum, sum of squares and number of elements added so far:
<langsyntaxhighlight lang="scala">// version 1.0.5-2
 
class CumStdDev {
Line 2,538 ⟶ 2,545:
val csd = CumStdDev()
for (d in testData) println("Add $d => ${csd.sd(d)}")
}</langsyntaxhighlight>
 
{{out}}
Line 2,554 ⟶ 2,561:
=={{header|Liberty BASIC}}==
Using a global array to maintain the state. Implements definition explicitly.
<syntaxhighlight lang="lb">
<lang lb>
dim SD.storage$( 100) ' can call up to 100 versions, using ID to identify.. arrays are global.
' holds (space-separated) number of data items so far, current sum.of.values and current sum.of.squares
Line 2,581 ⟶ 2,588:
 
Data 2, 4, 4, 4, 5, 5, 7, 9
</syntaxhighlight>
</lang>
<pre>
New data 2 so S.D. now = 0.000000
Line 2,594 ⟶ 2,601:
 
=={{header|Lobster}}==
<syntaxhighlight lang="lobster">
<lang Lobster>
// Stats computes a running mean and variance
// See Knuth TAOCP vol 2, 3rd edition, page 232
Line 2,623 ⟶ 2,630:
 
test_stdv()
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,631 ⟶ 2,638:
=={{header|Lua}}==
Uses a closure. Translation of JavaScript.
<langsyntaxhighlight lang="lua">function stdev()
local sum, sumsq, k = 0,0,0
return function(n)
Line 2,642 ⟶ 2,649:
for i, v in ipairs{2,4,4,4,5,5,7,9} do
print(ldev(v))
end</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">runningSTDDev[n_] := (If[Not[ValueQ[$Data]], $Data = {}];StandardDeviation[AppendTo[$Data, n]])</langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
The simple form is, computing only the standand deviation of the whole data set:
 
<langsyntaxhighlight Matlablang="matlab"> x = [2,4,4,4,5,5,7,9];
n = length (x);
 
Line 2,656 ⟶ 2,663:
x2 = mean (x .* x);
dev= sqrt (x2 - m * m)
dev = 2 </langsyntaxhighlight>
 
When the intermediate results are also needed, one can use this vectorized form:
 
<langsyntaxhighlight Matlablang="matlab"> m = cumsum(x) ./ [1:n]; % running mean
x2= cumsum(x.^2) ./ [1:n]; % running squares
 
Line 2,667 ⟶ 2,674:
0.00000 1.00000 0.94281 0.86603 0.97980 1.00000 1.39971 2.00000
 
</syntaxhighlight>
</lang>
 
Here is a vectorized one line solution as a function
<syntaxhighlight lang="matlab">
<lang Matlab>
function stdDevEval(n)
disp(sqrt(sum((n-sum(n)/length(n)).^2)/length(n)));
end
</syntaxhighlight>
</lang>
 
=={{header|MiniScript}}==
<langsyntaxhighlight MiniScriptlang="miniscript">StdDeviator = {}
StdDeviator.count = 0
StdDeviator.sum = 0
Line 2,697 ⟶ 2,704:
sd.add x
end for
print sd.stddev</langsyntaxhighlight>
{{out}}
<pre>2</pre>
 
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">0 П4 П5 П6 С/П П0 ИП5 + П5 ИП0
x^2 ИП6 + П6 КИП4 ИП6 ИП4 / ИП5 ИП4
/ x^2 - КвКор БП 04</langsyntaxhighlight>
 
Instruction: В/О С/П ''number'' С/П ''number'' С/П ...
Line 2,710 ⟶ 2,717:
=={{header|Nanoquery}}==
{{trans|Java}}
<langsyntaxhighlight Nanoquerylang="nanoquery">class StdDev
declare n
declare sum
Line 2,735 ⟶ 2,742:
for x in testData
println sd.sd(x)
end</langsyntaxhighlight>
 
{{out}}
Line 2,750 ⟶ 2,757:
 
===Using global variables===
<langsyntaxhighlight lang="nim">import math, strutils
 
var sdSum, sdSum2, sdN = 0.0
Line 2,761 ⟶ 2,768:
 
for value in [float 2,4,4,4,5,5,7,9]:
echo value, " ", formatFloat(sd(value), precision = -1)</langsyntaxhighlight>
 
{{out}}
Line 2,774 ⟶ 2,781:
 
===Using an accumulator object===
<langsyntaxhighlight Nimlang="nim">import math, strutils
 
type SDAccum = object
Line 2,789 ⟶ 2,796:
 
for value in [float 2, 4, 4, 4, 5, 5, 7, 9]:
echo value, " ", formatFloat(accum.add(value), precision = -1)</langsyntaxhighlight>
 
{{out}}
Line 2,795 ⟶ 2,802:
 
===Using a closure===
<langsyntaxhighlight Nimlang="nim">import math, strutils
 
func accumBuilder(): auto =
Line 2,809 ⟶ 2,816:
 
for value in [float 2, 4, 4, 4, 5, 5, 7, 9]:
echo value, " ", formatFloat(std(value), precision = -1)</langsyntaxhighlight>
 
{{out}}
Line 2,816 ⟶ 2,823:
=={{header|Objeck}}==
{{trans|Java}}
<langsyntaxhighlight lang="objeck">
use Structure;
 
Line 2,852 ⟶ 2,859:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Objective-C}}==
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
@interface SDAccum : NSObject
Line 2,909 ⟶ 2,916:
}
return 0;
}</langsyntaxhighlight>
 
===Blocks===
Line 2,915 ⟶ 2,922:
{{works with|iOS|4+}}
 
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
typedef double (^Func)(double); // a block that takes a double and returns a double
Line 2,944 ⟶ 2,951:
}
return 0;
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let sqr x = x *. x
 
let stddev l =
Line 2,961 ⟶ 2,968:
Printf.printf "List: ";
List.iter (Printf.printf "%g ") l;
Printf.printf "\nStandard deviation: %g\n" (stddev l)</langsyntaxhighlight>
 
{{out}}
Line 2,975 ⟶ 2,982:
Here, we create a channel to hold current list of numbers. Constraint is that this channel can't hold mutable objects. On the other hand, stddev function is thread safe and can be called by tasks running in parallel.
 
<langsyntaxhighlight Oforthlang="oforth">Channel new [ ] over send drop const: StdValues
 
: stddev(x)
| l |
StdValues receive x + dup ->l StdValues send drop
#qs l map sum l size asFloat / l avg sq - sqrt ;</langsyntaxhighlight>
 
{{out}}
Line 2,999 ⟶ 3,006:
=={{header|ooRexx}}==
{{works with|oorexx}}
<langsyntaxhighlight lang="rexx">sdacc = .SDAccum~new
x = .array~of(2,4,4,4,5,5,7,9)
sd = 0
Line 3,040 ⟶ 3,047:
ans = ( prev + ( n / prev ) ) / 2
end
return ans</langsyntaxhighlight>
{{out}}
<pre>#1 value = 2 stdev = 0
Line 3,053 ⟶ 3,060:
=={{header|PARI/GP}}==
Uses the Cramer-Young updating algorithm. For demonstration it displays the mean and variance at each step.
<langsyntaxhighlight lang="parigp">newpoint(x)={
myT=x;
myS=0;
Line 3,071 ⟶ 3,078:
print("Standard deviation: ",sqrt(myS/myN))
};
addpoints([2,4,4,4,5,5,7,9])</langsyntaxhighlight>
 
=={{header|Pascal}}==
===Std.Pascal===
{{trans|AWK}}
<langsyntaxhighlight lang="pascal">program stddev;
uses math;
const
Line 3,103 ⟶ 3,110:
writeln(i,' item=',arr[i]:2:0,' stddev=',stddev(i):18:15)
end
end.</langsyntaxhighlight>
{{out}}
<pre>1 item= 2 stddev= 0.000000000000000
Line 3,114 ⟶ 3,121:
8 item= 9 stddev= 2.000000000000000</pre>
==={{header|Delphi}}===
<langsyntaxhighlight Delphilang="delphi">program prj_CalcStdDerv;
 
{$APPTYPE CONSOLE}
Line 3,144 ⟶ 3,151:
end;
Readln;
end. </langsyntaxhighlight>
{{out}}
<pre>
Line 3,158 ⟶ 3,165:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">{
package SDAccum;
sub new {
Line 3,194 ⟶ 3,201:
return $self->stddev;
}
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="perl">my $sdacc = SDAccum->new;
my $sd;
 
Line 3,202 ⟶ 3,209:
$sd = $sdacc->value($v);
}
print "std dev = $sd\n";</langsyntaxhighlight>
 
A much shorter version using a closure and a property of the variance:
 
<langsyntaxhighlight lang="perl"># <(x - <x>)²> = <x²> - <x>²
{
my $num, $sum, $sum2;
Line 3,219 ⟶ 3,226:
}
 
print stddev($_), "\n" for qw(2 4 4 4 5 5 7 9);</langsyntaxhighlight>
 
{{out}}
Line 3,232 ⟶ 3,239:
 
one-liner:
<langsyntaxhighlight lang="bash">perl -MMath::StdDev -e '$d=new Math::StdDev;foreach my $v ( 2,4,4,4,5,5,7,9 ) {$d->Update($v); print $d->variance(),"\n"}'</langsyntaxhighlight>
 
small script:
<langsyntaxhighlight lang="perl">use Math::StdDev;
$d=new Math::StdDev;
foreach my $v ( 2,4,4,4,5,5,7,9 ) {
$d->Update($v);
print $d->variance(),"\n"
}</langsyntaxhighlight>
 
{{out}}
Line 3,255 ⟶ 3,262:
=={{header|Phix}}==
demo\rosetta\Standard_deviation.exw contains a copy of this code and a version that could be the basis for a library version that can handle multiple active data sets concurrently.
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
Line 3,282 ⟶ 3,289:
<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;">"N=%d Item=%d Avg=%5.3f StdDev=%5.3f\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ti</span><span style="color: #0000FF;">,</span><span style="color: #000000;">sdavg</span><span style="color: #0000FF;">(),</span><span style="color: #000000;">sddev</span><span style="color: #0000FF;">()})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 3,297 ⟶ 3,304:
=={{header|PHP}}==
This is just straight PHP class usage, respecting the specifications "stateful" and "one at a time":
<langsyntaxhighlight PHPlang="php"><?php
class sdcalc {
private $cnt, $sumup, $square;
Line 3,327 ⟶ 3,334:
foreach ([2,4,4,4,5,5,7,9] as $v) {
printf('Adding %g: result %g%s', $v, $c->add($v), PHP_EOL);
}</langsyntaxhighlight>
 
This will produce the output:
Line 3,342 ⟶ 3,349:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(scl 2)
 
(de stdDev ()
Line 3,359 ⟶ 3,366:
(let Fun (stdDev)
(for N (2.0 4.0 4.0 4.0 5.0 5.0 7.0 9.0)
(prinl (format N *Scl) " -> " (format (Fun N) *Scl)) ) )</langsyntaxhighlight>
{{out}}
<pre>2.00 -> 0.00
Line 3,371 ⟶ 3,378:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">*process source attributes xref;
stddev: proc options(main);
declare a(10) float init(1,2,3,4,5,6,7,8,9,10);
Line 3,395 ⟶ 3,402:
end std_dev;
end;</langsyntaxhighlight>
{{out}}
<pre>AVERAGE= 5.50000E+0000;
Line 3,403 ⟶ 3,410:
This implementation takes the form of an advanced function
which can act like a cmdlet and receive input from the pipeline.
<langsyntaxhighlight lang="powershell">function Get-StandardDeviation {
begin {
$avg = 0
Line 3,415 ⟶ 3,422:
[Math]::Sqrt($sum / $nums.Length)
}
}</langsyntaxhighlight>
Usage as follows:
<pre>PS> 2,4,4,4,5,5,7,9 | Get-StandardDeviation
Line 3,428 ⟶ 3,435:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">;Define our Standard deviation function
Declare.d Standard_deviation(x)
 
Line 3,456 ⟶ 3,463:
MyList:
Data.i 2,4,4,4,5,5,7,9
EndDataSection</langsyntaxhighlight>
 
{{out}}
Line 3,474 ⟶ 3,481:
The program should work with Python 2.x and 3.x,
although the output would not be a tuple in 3.x
<langsyntaxhighlight lang="python">>>> from math import sqrt
>>> def sd(x):
sd.sum += x
Line 3,495 ⟶ 3,502:
(7, 1.3997084244475311)
(9, 2.0)
>>></langsyntaxhighlight>
 
===Python: Using a class instance===
<langsyntaxhighlight lang="python">>>> class SD(object): # Plain () for python 3.x
def __init__(self):
self.sum, self.sum2, self.n = (0,0,0)
Line 3,510 ⟶ 3,517:
>>> sd_inst = SD()
>>> for value in (2,4,4,4,5,5,7,9):
print (value, sd_inst.sd(value))</langsyntaxhighlight>
 
====Python: Callable class====
Line 3,517 ⟶ 3,524:
===Python: Using a Closure===
{{Works with|Python|3.x}}
<langsyntaxhighlight lang="python">>>> from math import sqrt
>>> def sdcreator():
sum = sum2 = n = 0
Line 3,541 ⟶ 3,548:
5 1.0
7 1.39970842445
9 2.0</langsyntaxhighlight>
 
===Python: Using an extended generator===
{{Works with|Python|2.5+}}
<langsyntaxhighlight lang="python">>>> from math import sqrt
>>> def sdcreator():
sum = sum2 = n = 0
Line 3,568 ⟶ 3,575:
5 1.0
7 1.39970842445
9 2.0</langsyntaxhighlight>
 
===Python: In a couple of 'functional' lines===
<langsyntaxhighlight lang="python">>>> myMean = lambda MyList : reduce(lambda x, y: x + y, MyList) / float(len(MyList))
>>> myStd = lambda MyList : (reduce(lambda x,y : x + y , map(lambda x: (x-myMean(MyList))**2 , MyList)) / float(len(MyList)))**.5
 
>>> print myStd([2,4,4,4,5,5,7,9])
2.0
</syntaxhighlight>
</lang>
 
=={{header|R}}==
 
===Built-in Std Dev fn===
To compute the running sum, one must keep track of the number of items, the sum of values, and the sum of squares.
<lang rsplus>#The built-in standard deviation function applies the Bessel correction. To reverse this, we can apply an uncorrection.
 
#If na.rm is true, missing data points (NA values) are removed.
If the goal is to get a vector of running standard deviations, the simplest is to do it with cumsum:
reverseBesselCorrection <- function(x, na.rm=FALSE)
 
{
<syntaxhighlight lang="rsplus">cumsd <- function(x) {
if(na.rm) x <- x[!is.na(x)]
lenn <- lengthseq_along(x)
sqrt(cumsum(x^2) / n - (cumsum(x) / n)^2)
if(len < 2) stop("2 or more data points required")
sqrt((len-1)/len)
}
testdata <- c(2,4,4,4,5,5,7,9)
reverseBesselCorrection(testdata)*sd(testdata) #2</lang>
===From scratch===
<lang rsplus>#Again, if na.rm is true, missing data points (NA values) are removed.
uncorrectedsd <- function(x, na.rm=FALSE)
{
len <- length(x)
if(len < 2) stop("2 or more data points required")
mu <- mean(x, na.rm=na.rm)
ssq <- sum((x - mu)^2, na.rm=na.rm)
usd <- sqrt(ssq/len)
usd
}
uncorrectedsd(testdata) #2</lang>
==="Running" SD===
If we desire a solution that gives every "running" standard deviation for each input, rather than only giving one number as our final output, we can do the following. To make this differ from previous solutions, we will not have our code make any mention of missing values, and we will show off R's Reduce and sapply.
<lang rsplus>biasedSd <- function(data)#Once again, we have to make a standard deviation function from scratch.
{
sqrt(mean((data - mean(data))^2))
}
 
set.seed(12345L)
cumSd <- function(data)
x <- rnorm(10)
{
 
sapply(Reduce(c, data, accumulate = TRUE), biasedSd)
cumsd(x)
}</lang>
# [1] 0.0000000 0.3380816 0.8752973 1.1783628 1.2345538 1.3757142 1.2867220 1.2229056 1.1665168 1.1096814
{{out}}
 
<pre>> cumSd(c(2, 4, 4, 4, 5, 5, 7, 9))
# Compare to the naive implementation, i.e. compute sd on each sublist:
[1] 0.0000000 1.0000000 0.9428090 0.8660254 0.9797959 1.0000000 1.3997084 2.0000000</pre>
Vectorize(function(k) sd(x[1:k]) * sqrt((k - 1) / k))(seq_along(x))
===Stateful SD===
# [1] NA 0.3380816 0.8752973 1.1783628 1.2345538 1.3757142 1.2867220 1.2229056 1.1665168 1.1096814
If we want a function that remembers and uses the previous inputs, letting us be very strict about the "one at a time" requirement, then we can lift biasedSd from the previous solution and make good use of the distinction between R's <- and <<- methods of assignment.
# Note that the first is NA because sd is unbiased formula, hence there is a division by n-1, which is 0 for n=1.</syntaxhighlight>
<lang rsplus>cumSDStateful <- function()
 
{
The task requires an accumulator solution:
data <- numeric(0)
 
function(oneNumber)
<syntaxhighlight lang="rsplus">accumsd <- function() {
{
n <- 0
data <<- c(data, oneNumber)
m <- 0
biasedSd(data)
s <- 0
function(x) {
n <<- n + 1
m <<- m + x
s <<- s + x * x
sqrt(s / n - (m / n)^2)
}
}
state <- cumSDStateful()</lang>
{{out}}
<pre>> state(2);state(4);state(4);state(4);state(5);state(5);state(7);state(9)
[1] 0
[1] 1
[1] 0.942809
[1] 0.8660254
[1] 0.9797959
[1] 1
[1] 1.399708
[1] 2</pre>
 
f <- accumsd()
===Environment solution===
sapply(x, f)
R gives us some control over what environment expressions are evaluated in. This lets us shorten the previous solution and get identical output.
# [1] 0.0000000 0.3380816 0.8752973 1.1783628 1.2345538 1.3757142 1.2867220 1.2229056 1.1665168 1.1096814</syntaxhighlight>
<lang rsplus>localCumSD <- local({
data <- numeric(0)
function(oneNumber)
{
data <<- c(data, oneNumber)
biasedSd(data)#Again, lifted from the ""Running" SD" solution.
}
})
localCumSD(2);localCumSD(4);localCumSD(4);localCumSD(4);localCumSD(5);localCumSD(5);localCumSD(7);localCumSD(9)</lang>
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">
#lang racket
(require math)
Line 3,662 ⟶ 3,636:
;; run it on each number, return the last result
(last (map running-stddev '(2 4 4 4 5 5 7 9)))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
 
{{works with|Rakudo Star|2010.08}}
Using a closure:
<syntaxhighlight lang="raku" perl6line>sub sd (@a) {
my $mean = @a R/ [+] @a;
sqrt @a R/ [+] map (* - $mean)**2², @a;
}
Line 3,679 ⟶ 3,653:
my &f = sdaccum;
say f $_ for 2, 4, 4, 4, 5, 5, 7, 9;</langsyntaxhighlight>
 
Using a state variable (remember that <tt><(x-<x>)²> = <x²> - <x>²</tt>):
<syntaxhighlight lang="raku" line>sub stddev($x) {
<lang perl6># remember that <(x-<x>)²> = <x²> - <x>²
sub stddev($x) {
sqrt
( .[2] += $x**2²) / ++.[0] -
- ((.[1] += $x ) / .[0])**2²
given state @;
}
 
say .&stddev $_ for <2 4 4 4 5 5 7 9>;</langsyntaxhighlight>
 
{{out}}
Line 3,705 ⟶ 3,678:
These REXX versions use &nbsp; ''running sums''.
===show running sums===
<langsyntaxhighlight lang="rexx">/*REXX program calculates and displays the standard deviation of a given set of numbers.*/
parse arg # /*obtain optional arguments from the CL*/
if #='' then #= 2 4 4 4 5 5 7 9 /*None specified? Then use the default*/
Line 3,723 ⟶ 3,696:
do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/
numeric digits d; return g/1</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input of: &nbsp; &nbsp; <tt> 2 &nbsp; 4 &nbsp; 4 &nbsp; 4 &nbsp; 5 &nbsp; 5 &nbsp; 7 &nbsp; 9 </tt>}}
<pre>
Line 3,738 ⟶ 3,711:
 
===only show standard deviation===
<langsyntaxhighlight lang="rexx">/*REXX program calculates and displays the standard deviation of a given set of numbers.*/
parse arg # /*obtain optional arguments from the CL*/
if #='' then #= 2 4 4 4 5 5 7 9 /*None specified? Then use the default*/
Line 3,754 ⟶ 3,727:
do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/
numeric digits d; return g/1</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input of: &nbsp; &nbsp; <tt> 2 &nbsp; 4 &nbsp; 4 &nbsp; 4 &nbsp; 5 &nbsp; 5 &nbsp; 7 &nbsp; 9 </tt>}}
<pre>
Line 3,761 ⟶ 3,734:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Cumulative standard deviation
 
Line 3,779 ⟶ 3,752:
see "" + num + " value in = " + stddata + " Stand Dev = " + standdev + nl
next
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,790 ⟶ 3,763:
7 value in = 7 Stand Dev = 1.399708
8 value in = 9 Stand Dev = 2
</pre>
 
=={{header|RPL}}==
===Basic RPL===
≪ CL∑ { } SWAP
1 OVER SIZE '''FOR''' j
DUP j GET ∑+
'''IF''' j 1 > '''THEN'''
SDEV ∑DAT SIZE 1 GET DUP 1 - SWAP / √ *
ROT SWAP + SWAP '''END'''
'''NEXT'''
DROP CL∑
≫ '<span style="color:blue>CSDEV</span>' STO
===RPL 1993===
≪ CL∑
1 ≪ ∑+ PSDEV ≫ DOSUBS CL∑
≫ '<span style="color:blue>CSDEV</span>' STO
{{out}}
<pre>
1: { 0 1 0.942809041582 0.866025403784 0.979795897113 1 1.39970842445 2 }
</pre>
 
Line 3,798 ⟶ 3,791:
"Simplification of the formula [...] for standard deviation [...] can be memorized as taking the square root of (the average of the squares less the square of the average)." [[wp:Standard_deviation#Simplification_of_the_formula|c.f. wikipedia]].
 
<langsyntaxhighlight lang="ruby">class StdDevAccumulator
def initialize
@n, @sum, @sumofsquares = 0, 0.0, 0.0
Line 3,822 ⟶ 3,815:
sd = StdDevAccumulator.new
i = 0
[2,4,4,4,5,5,7,9].each {|n| puts "adding #{n}: stddev of #{i+=1} samples is #{sd << n}" }</langsyntaxhighlight>
 
<pre>adding 2: stddev of 1 samples is 0.0
Line 3,834 ⟶ 3,827:
 
=== Closure ===
<langsyntaxhighlight lang="ruby">def sdaccum
n, sum, sum2 = 0, 0.0, 0.0
lambda do |num|
Line 3,845 ⟶ 3,838:
 
sd = sdaccum
[2,4,4,4,5,5,7,9].each {|n| print sd.call(n), ", "}</langsyntaxhighlight>
 
<pre>0.0, 1.0, 0.942809041582063, 0.866025403784439, 0.979795897113272, 1.0, 1.39970842444753, 2.0, </pre>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">dim sdSave$(100) 'can call up to 100 versions
'holds (space-separated) number of data , sum of values and sum of squares
sd$ = "2,4,4,4,5,5,7,9"
Line 3,865 ⟶ 3,858:
print num;" value in = ";stdData; " Stand Dev = "; using("###.######", standDev)
 
next num</langsyntaxhighlight>
<pre>1 value in = 2 Stand Dev = 0.000000
2 value in = 4 Stand Dev = 1.000000
Line 3,878 ⟶ 3,871:
Using a struct:
{{trans|Java}}
<langsyntaxhighlight lang="rust">pub struct CumulativeStandardDeviation {
n: f64,
sum: f64,
Line 3,909 ⟶ 3,902:
println!("{}", cum_stdev.push(*num as f64));
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,923 ⟶ 3,916:
 
Using a closure:
<langsyntaxhighlight lang="rust">fn sd_creator() -> impl FnMut(f64) -> f64 {
let mut n = 0.0;
let mut sum = 0.0;
Line 3,942 ⟶ 3,935:
println!("{}", sd_acc(*num as f64));
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,956 ⟶ 3,949:
 
=={{header|SAS}}==
<syntaxhighlight lang="sas">
<lang SAS>
*--Load the test data;
data test1;
Line 3,989 ⟶ 3,982:
var n sd /*mean*/;
run;
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,008 ⟶ 4,001:
===Generic for any numeric type===
{{libheader|Scala}}
<langsyntaxhighlight Scalalang="scala">import scala.math.sqrt
 
object StddevCalc extends App {
Line 4,033 ⟶ 4,026:
println(s"Successfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart}ms]")
 
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">
(define (standart-deviation-generator)
(let ((nums '()))
Line 4,048 ⟶ 4,041:
(let loop ((f (standart-deviation-generator))
(input '(2 4 4 4 5 5 7 9)))
(if (notunless (null? input))
(begin
(display (f (car input)))
(newline)
(loop f (cdr input)))))
</syntaxhighlight>
</lang>
 
=={{header|Scilab}}==
Scilab has the built-in function '''stdev''' to compute the standard deviation of a sample so it is straightforward to have the standard deviation of a sample with a correction of the bias.
<syntaxhighlight lang="text">T=[2,4,4,4,5,5,7,9];
stdev(T)*sqrt((length(T)-1)/length(T))</langsyntaxhighlight>
{{out}}
<pre>-->T=[2,4,4,4,5,5,7,9];
Line 4,066 ⟶ 4,058:
=={{header|Sidef}}==
Using an object to keep state:
<langsyntaxhighlight lang="ruby">class StdDevAccumulator(n=0, sum=0, sumofsquares=0) {
method <<(num) {
n += 1
Line 4,087 ⟶ 4,079:
[2,4,4,4,5,5,7,9].each {|n|
say "adding #{n}: stddev of #{i+=1} samples is #{sd << n}"
}</langsyntaxhighlight>
{{out}}
<pre>
Line 4,101 ⟶ 4,093:
 
Using ''static'' variables:
<langsyntaxhighlight lang="ruby">func stddev(x) {
static(num=0, sum=0, sum2=0)
num++
Line 4,110 ⟶ 4,102:
}
 
%n(2 4 4 4 5 5 7 9).each { say stddev(_) }</langsyntaxhighlight>
{{out}}
<pre>
Line 4,126 ⟶ 4,118:
{{works with|GNU Smalltalk}}
 
<langsyntaxhighlight lang="smalltalk">Object subclass: SDAccum [
|sum sum2 num|
SDAccum class >> new [ |o|
Line 4,145 ⟶ 4,137:
]
stddev [ ^ (self variance) sqrt ]
].</langsyntaxhighlight>
 
<langsyntaxhighlight lang="smalltalk">|sdacc sd|
sdacc := SDAccum new.
 
#( 2 4 4 4 5 5 7 9 ) do: [ :v | sd := sdacc value: v ].
('std dev = %1' % { sd }) displayNl.</langsyntaxhighlight>
 
=={{header|SQL}}==
{{works with|Postgresql}}
<langsyntaxhighlight SQLlang="sql">-- the minimal table
create table if not exists teststd (n double precision not null);
 
Line 4,189 ⟶ 4,181:
-- cleanup test data
delete from teststd;
</syntaxhighlight>
</lang>
With a command like '''psql <rosetta-std-dev.sql''' you will get an output like this: (duplicate lines generously deleted, locale is DE)
<pre>
Line 4,215 ⟶ 4,207:
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift">import Darwin
class stdDev{
Line 4,242 ⟶ 4,234:
}
var aa = stdDev()</langsyntaxhighlight>
{{out}}
<pre>
Line 4,257 ⟶ 4,249:
Functional:
 
<syntaxhighlight lang="swift">
<lang Swift>
func standardDeviation(arr : [Double]) -> Double
{
Line 4,270 ⟶ 4,262:
standardDeviation(responseTimes) // 20.8742514835862
standardDeviation([2,4,4,4,5,5,7,9]) // 2.0
</syntaxhighlight>
</lang>
 
=={{header|Tcl}}==
===With a Class===
{{works with|Tcl|8.6}} or {{libheader|TclOO}}
<langsyntaxhighlight lang="tcl">oo::class create SDAccum {
variable sum sum2 num
constructor {} {
Line 4,307 ⟶ 4,299:
set sd [$sdacc value $val]
}
puts "the standard deviation is: $sd"</langsyntaxhighlight>
{{out}}
<pre>the standard deviation is: 2.0</pre>
Line 4,313 ⟶ 4,305:
===With a Coroutine===
{{works with|Tcl|8.6}}
<langsyntaxhighlight lang="tcl"># Make a coroutine out of a lambda application
coroutine sd apply {{} {
set sum 0.0
Line 4,332 ⟶ 4,324:
}
sd stop
puts "the standard deviation is: $sd"</langsyntaxhighlight>
 
[[Category:Stateful transactions]]
Line 4,346 ⟶ 4,338:
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vb">data = Array(2,4,4,4,5,5,7,9)
 
For i = 0 To UBound(data)
Line 4,366 ⟶ 4,358:
variance = variance/(n+1)
sd = FormatNumber(Sqr(variance),6)
End Function</langsyntaxhighlight>
 
{{Out}}
Line 4,384 ⟶ 4,376:
Note that the helper function <code>avg</code> is not named <code>average</code> to avoid a name conflict with <code>WorksheetFunction.Average</code> in MS Excel.
 
<langsyntaxhighlight lang="vb">Function avg(what() As Variant) As Variant
'treats non-numeric strings as zero
Dim L0 As Variant, total As Variant
Line 4,433 ⟶ 4,425:
Debug.Print standardDeviation(x(L0))
Next
End Sub</langsyntaxhighlight>
 
{{out}}
Line 4,450 ⟶ 4,442:
{{libheader|Wren-fmt}}
{{libheader|Wren-math}}
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for Fmt
import "./math" for Nums
 
var cumStdDev = Fiber.new { |a|
Line 4,465 ⟶ 4,457:
var sd = cumStdDev.call(a)
if (cumStdDev.isDone) return
SystemFmt.print("Std Dev : %(Fmt$10.f(108f\n", sd, 8))\n")
}</langsyntaxhighlight>
 
{{out}}
Line 4,496 ⟶ 4,488:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
int A, I;
real N, S, S2;
Line 4,508 ⟶ 4,500:
];
CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 4,516 ⟶ 4,508:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn sdf{ fcn(x,xs){
m:=xs.append(x.toFloat()).sum(0.0)/xs.len();
(xs.reduce('wrap(p,x){(x-m)*(x-m) +p},0.0)/xs.len()).sqrt()
}.fp1(L())
}</langsyntaxhighlight>
{{out}}
<pre>
9,476

edits