Cumulative standard deviation: Difference between revisions

m
m (→‎{{header|Wren}}: Minor tidy)
 
(43 intermediate revisions by 20 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 165:
N=7 ITEM=7 AVG=4.428 STDDEV=1.399
N=8 ITEM=9 AVG=5.000 STDDEV=2.000</pre>
 
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
{{libheader|Action! Real Math}}
<syntaxhighlight lang="action!">INCLUDE "H6:REALMATH.ACT"
 
REAL sum,sum2
INT count
 
PROC Calc(REAL POINTER x,sd)
REAL tmp1,tmp2,tmp3
 
RealAdd(sum,x,tmp1) ;tmp1=sum+x
RealAssign(tmp1,sum) ;sum=sum+x
RealMult(x,x,tmp1) ;tmp1=x*x
RealAdd(sum2,tmp1,tmp2) ;tmp2=sum2+x*x
RealAssign(tmp2,sum2) ;sum2=sum2+x*x
count==+1
IF count=0 THEN
IntToReal(0,sd) ;sd=0
ELSE
IntToReal(count,tmp1)
RealMult(sum,sum,tmp2) ;tmp2=sum*sum
RealDiv(tmp2,tmp1,tmp3) ;tmp3=sum*sum/count
RealDiv(tmp3,tmp1,tmp2) ;tmp2=sum*sum/count/count
RealDiv(sum2,tmp1,tmp3) ;tmp3=sum2/count
RealSub(tmp3,tmp2,tmp1) ;tmp1=sum2/count-sum*sum/count/count
Sqrt(tmp1,sd) ;sd=sqrt(sum2/count-sum*sum/count/count)
FI
RETURN
 
PROC Main()
INT ARRAY values=[2 4 4 4 5 5 7 9]
INT i
REAL x,sd
 
Put(125) PutE() ;clear screen
MathInit()
IntToReal(0,sum)
IntToReal(0,sum2)
count=0
FOR i=0 TO 7
DO
IntToReal(values(i),x)
Calc(x,sd)
Print("x=") PrintR(x)
Print(" sum=") PrintR(sum)
Print(" sd=") PrintRE(sd)
OD
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Cumulative_standard_deviation.png Screenshot from Atari 8-bit computer]
<pre>
x=2 sum=2 sd=0
x=4 sum=6 sd=1
x=4 sum=10 sd=.942809052
x=4 sum=14 sd=.86602541
x=5 sum=19 sd=.979795903
x=5 sum=24 sd=1
x=7 sum=31 sd=1.39970843
x=9 sum=40 sd=1.99999999
</pre>
 
=={{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 203 ⟶ 265:
end loop;
end Test_Deviation;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 225 ⟶ 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 276 ⟶ 338:
OD
)</langsyntaxhighlight>
{{out}}
<pre>
Line 295 ⟶ 357:
 
A code sample in an object oriented style:
<langsyntaxhighlight Algol68lang="algol68">MODE STAT = STRUCT(
LONG REAL sum,
LONG REAL sum2,
Line 370 ⟶ 432:
 
)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 389 ⟶ 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 404 ⟶ 466:
LONG REAL value = values[i];
printf(($2(xg(0,6))l$, value, sd(value)))
OD</langsyntaxhighlight>
{{out}}
<pre>
Line 420 ⟶ 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 444 ⟶ 506:
end for_i
 
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 459 ⟶ 521:
=={{header|AppleScript}}==
 
Accumulation acrossover a fold:
 
<syntaxhighlight lang="applescript">-------------- CUMULATIVE STANDARD DEVIATION -------------
<lang AppleScript>-- stdDevInc :: Accumulator -> Num -> Index -> Accumulator
 
-- stdDevInc :: Accumulator -> Num -> Index -> Accumulator
-- stdDevInc :: {sum:, squaresSum:, stages:} -> Real -> Integer
-- -> {sum:, squaresSum:, stages:}
Line 470 ⟶ 534:
((squaresSum / i) - ((sum / i) ^ 2)) ^ 0.5
{sum:(sum of a) + n, squaresSum:squaresSum, stages:stages}
end stdDevInc
 
 
--------------------------- TEST -------------------------
-- TEST
on run
set lstSamplexs to [2, 4, 4, 4, 5, 5, 7, 9]
stages of foldl(stdDevInc, ¬
{sum:0, squaresSum:0, stages:[]}, lstSamplexs)
--> {0.0, 1.0, 0.942809041582, 0.866025403784, 0.979795897113, 1.0, 1.399708424448, 2.0}
Line 486 ⟶ 550:
 
 
-- GENERIC FUNCTIONS --------------------------------------------------- GENERIC FUNCTIONS -------------------
 
-- foldl :: (a -> b -> a) -> a -> [b] -> a
Line 494 ⟶ 558:
set lng to length of xs
repeat with i from 1 to lng
set v to lambda|λ|(v, item i of xs, i, xs)
end repeat
return v
Line 500 ⟶ 564:
end foldl
 
 
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: HandlerFirst-class m => (a -> b) -> m (a -> Scriptb)
on mReturn(f)
if-- 2nd class ofhandler ffunction islifted into 1st class script thenwrapper.
if script is class of f then
f
else
script
property lambda|λ| : f
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:
 
<syntaxhighlight lang="applescript">-------------- CUMULATIVE STANDARD DEVIATION -------------
 
-- cumulativeStdDevns :: [Float] -> [Float]
on cumulativeStdDevns(xs)
script go
on |λ|(sq, x, i)
set {s, q} to sq
set _s to x + s
set _q to q + (x ^ 2)
{{_s, _q}, ((_q / i) - ((_s / i) ^ 2)) ^ 0.5}
end |λ|
end script
item 2 of mapAccumL(go, {0, 0}, xs)
end cumulativeStdDevns
 
 
--------------------------- TEST -------------------------
on run
cumulativeStdDevns({2, 4, 4, 4, 5, 5, 7, 9})
end run
 
 
------------------------- GENERIC ------------------------
 
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
 
 
-- mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
on mapAccumL(f, acc, xs)
-- 'The mapAccumL function behaves like a combination of map and foldl;
-- it applies a function to each element of a list, passing an
-- accumulating parameter from |Left| to |Right|, and returning a final
-- value of this accumulator together with the new list.' (see Hoogle)
script
on |λ|(a, x, i)
tell mReturn(f) to set pair to |λ|(item 1 of a, x, i)
{item 1 of pair, (item 2 of a) & {item 2 of pair}}
end |λ|
end script
foldl(result, {acc, []}, xs)
end mapAccumL
 
 
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
-- 2nd class handler function lifted into 1st class script wrapper.
if script is class of f then
f
else
script
property |λ| : f
end script
end if
end mReturn</syntaxhighlight>
 
{{Out}}
<pre>{0.0, 1.0, 0.942809041582, 0.866025403784, 0.979795897113, 1.0, 1.399708424448, 2.0}</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">arr: new []
loop [2 4 4 4 5 5 7 9] 'value [
'arr ++ value
print [value "->" deviation arr]
]</syntaxhighlight>
 
{{out}}
 
<pre>2 -> 0.0
4 -> 1.0
4 -> 0.9428090415820634
4 -> 0.8660254037844386
5 -> 0.9797958971132711
5 -> 0.9999999999999999
7 -> 1.39970842444753
9 -> 2.0</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">Data := [2,4,4,4,5,5,7,9]
for k, v in Data {
Line 531 ⟶ 691:
return sqrt((sum2/n) - (((sum*sum)/n)/n))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 545 ⟶ 705:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f STANDARD_DEVIATION.AWK
BEGIN {
Line 565 ⟶ 725:
return(sqrt(variance))
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 580 ⟶ 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 596 ⟶ 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 609 ⟶ 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 628 ⟶ 788:
i% += 1
list(i%) = n
= SQR(MOD(list())^2/i% - (SUM(list())/i%)^2)</langsyntaxhighlight>
{{out}}
<pre>
Line 643 ⟶ 803:
=={{header|C}}==
 
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <math.h>
Line 690 ⟶ 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 704 ⟶ 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 731 ⟶ 891:
}
}
}</langsyntaxhighlight>
<pre>0
1
Line 743 ⟶ 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 783 ⟶ 943:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Clojure}}==
 
<langsyntaxhighlight lang="lisp">
(defn stateful-std-deviation[x]
(letfn [(std-dev[x]
Line 797 ⟶ 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 873 ⟶ 1,033:
goback.
end program stddev.
</syntaxhighlight>
</lang>
<langsyntaxhighlight lang="cobol">sample output:
inp=002 stddev=+00000.0000
inp=004 stddev=+00001.0000
Line 883 ⟶ 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 916 ⟶ 1,076:
 
"""
</syntaxhighlight>
</lang>
 
{{out}}
Line 946 ⟶ 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 962 ⟶ 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 983 ⟶ 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,032 ⟶ 1,192:
END Do;
END StandardDeviation.
</syntaxhighlight>
</lang>
Execute: ^Q StandardDeviation.Do 2 4 4 4 5 5 7 9 ~<br/>
{{out}}
Line 1,047 ⟶ 1,207:
 
=={{header|Crystal}}==
{{trans|Ruby}}
===Object===
Use an object to keep state.
<lang ruby>class StdDevAccumulator
{{trans|Ruby}}
<syntaxhighlight lang="ruby">class StdDevAccumulator
def initialize
@n, @sum, @sum2 = 0, 0.0, 0.0
Line 1,064 ⟶ 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,079 ⟶ 1,240:
===Closure===
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">def sdaccum
n, sum, sum2 = 0, 0.0, 0.0
->(num : Int32) do
Line 1,090 ⟶ 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,122 ⟶ 1,283:
writefln("%e", stdev.getStdDev());
}
}</langsyntaxhighlight>
{{out}}
<pre>0.000000e+00
Line 1,144 ⟶ 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,167 ⟶ 1,328:
return [insert, stddev]
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="e">? def [insert, stddev] := makeRunningStdDev()
# value: <insert>, <stddev>
 
Line 1,186 ⟶ 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,232 ⟶ 1,410:
end
 
Standard_deviation.task</langsyntaxhighlight>
 
{{out}}
Line 1,248 ⟶ 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,308 ⟶ 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,314 ⟶ 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,360 ⟶ 1,528:
 
loop_calculate_average( Ns ) -> lists:sum( Ns ) / erlang:length( Ns ).
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,375 ⟶ 1,543:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: accessors io kernel math math.functions math.parser
sequences ;
IN: standard-deviator
Line 1,396 ⟶ 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}}==
<syntaxhighlight lang="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
01.30 D 2.1
01.35 T %6.40
01.40 F I=1,8;S A=T(I);D 2.2;T "VAL",A;D 2.3;T " SD",A,!
01.50 Q
 
02.01 C-- RUNNING STDDEV
02.02 C-- 2.1: INITIALIZE
02.03 C-- 2.2: INSERT VALUE A
02.04 C-- 2.3: A = CURRENT STDDEV
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)</syntaxhighlight>
 
{{out}}
 
<pre>VAL= 2.00000 SD= 0.00000
VAL= 4.00000 SD= 1.00000
VAL= 4.00000 SD= 0.94281
VAL= 4.00000 SD= 0.86603
VAL= 5.00000 SD= 0.97980
VAL= 5.00000 SD= 1.00000
VAL= 7.00000 SD= 1.39971
VAL= 9.00000 SD= 2.00000</pre>
 
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: f+! ( x addr -- ) dup f@ f+ f! ;
 
: st-count ( stats -- n ) f@ ;
Line 1,421 ⟶ 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,441 ⟶ 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,453 ⟶ 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,507 ⟶ 1,704:
end function stddev
end program standard_deviation
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,528 ⟶ 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,603 ⟶ 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,682 ⟶ 1,879:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function calcStandardDeviation(number As Double) As Double
Line 1,711 ⟶ 1,908:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,729 ⟶ 1,926:
 
State maintained with a closure.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,751 ⟶ 1,948:
fmt.Println(r(x))
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,766 ⟶ 1,963:
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">List samples = []
 
def stdDev = { def sample ->
Line 1,778 ⟶ 1,975:
[2,4,4,4,5,5,7,9].each {
println "${stdDev(it)}"
}</langsyntaxhighlight>
 
{{out}}
Line 1,794 ⟶ 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 1,821 ⟶ 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:
Or, simply accumulating across a fold:
{{Trans|AppleScript}}
 
<syntaxhighlight lang="haskell">import Data.List (mapAccumL)
<lang Haskell>type Index = Int
 
type DataPoint = Float
 
-------------- CUMULATIVE STANDARD DEVIATION -------------
type Sum = Float
 
type SumOfSquares = Float
cumulativeStdDevns :: [Float] -> [Float]
cumulativeStdDevns = snd . mapAccumL go (0, 0) . zip [1.0..]
type Deviations = [Float]
type Accumulator = (Sum, SumOfSquares, Deviations)
stdDevInc :: Accumulator -> (DataPoint, Index) -> Accumulator
stdDevInc (s, q, ds) (x, i) = (_s, _q, _ds)
where
_s =go (s, +q) (i, x) =
_q let _s = qs + (x ^ 2)
_i _q = fromIntegralq + (x ^ i2)
_ds = dsin ++((_s, _q), [sqrt ((_q / _ii) - ((_s / _ii) ^ 2))])
sample :: [DataPoint]
sample = [2, 4, 4, 4, 5, 5, 7, 9]
 
 
-- The Prelude definition of foldl' --'
 
-- adjusted to avoid wiki formatting glitches.
--------------------------- TEST -------------------------
foldl_ :: Foldable t => (b -> a -> b) -> b -> t a -> b
foldl_ f z0 xs = foldr f_ id xs z0
where f_ x k z = k $! f z x
main :: IO ()
main = mapM_ print devns$ cumulativeStdDevns [2, 4, 4, 4, 5, 5, 7, 9]</syntaxhighlight>
where
(_, _, devns) = foldl_ stdDevInc (0, 0, []) $ zip sample [1 .. ]</lang>
{{Out}}
<pre>0.0
Line 1,868 ⟶ 2,052:
 
=={{header|Haxe}}==
<langsyntaxhighlight lang="haxe">using Lambda;
 
class Main {
Line 1,890 ⟶ 2,074:
return Math.sqrt(average(store));
}
}</langsyntaxhighlight>
<pre>0
1
Line 1,901 ⟶ 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 1,916 ⟶ 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 1,927 ⟶ 2,111:
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main()
 
stddev() # reset state / empty
Line 1,948 ⟶ 2,132:
return sqrt( (sum2X / *X) - (sumX / *X)^2 )
}
end</langsyntaxhighlight>
{{out}}
<pre>stddev (so far) := 0.0
Line 1,960 ⟶ 2,144:
 
=={{header|IS-BASIC}}==
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "StDev.bas"
110 LET N=8
120 NUMERIC ARR(1 TO N)
Line 1,976 ⟶ 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 1,989 ⟶ 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,003 ⟶ 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,034 ⟶ 2,218:
}
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Line 2,041 ⟶ 2,225:
 
Uses a closure.
<langsyntaxhighlight lang="javascript">function running_stddev() {
var n = 0;
var sum = 0.0;
Line 2,060 ⟶ 2,244:
 
// using WSH
WScript.Echo(stddev.join(', ');</langsyntaxhighlight>
 
{{out}}
<pre>0, 1, 0.942809041582063, 0.866025403784439, 0.979795897113273, 1, 1.39970842444753, 2</pre>
 
===Functional (ES 5)===
====ES5====
 
Accumulating across a fold
 
<langsyntaxhighlight JavaScriptlang="javascript">(function (xs) {
return xs.reduce(function (a, x, i) {
Line 2,090 ⟶ 2,274:
}).stages
 
})([2, 4, 4, 4, 5, 5, 7, 9]);</langsyntaxhighlight>
 
{{Out}}
<syntaxhighlight lang="javascript">[0, 1, 0.9428090415820626, 0.8660254037844386,
0.9797958971132716, 1, 1.3997084244475297, 2]</syntaxhighlight>
 
====ES6====
 
As a map-accumulation:
<syntaxhighlight lang="javascript">(() => {
'use strict';
 
// ---------- CUMULATIVE STANDARD DEVIATION ----------
 
// cumulativeStdDevns :: [Float] -> [Float]
const cumulativeStdDevns = ns => {
const go = ([s, q]) =>
([i, x]) => {
const
_s = s + x,
_q = q + (x * x),
j = 1 + i;
return [
[_s, _q],
Math.sqrt(
(_q / j) - Math.pow(_s / j, 2)
)
];
};
return mapAccumL(go)([0, 0])(ns)[1];
};
 
// ---------------------- TEST -----------------------
const main = () =>
showLog(
cumulativeStdDevns([
2, 4, 4, 4, 5, 5, 7, 9
])
);
 
// --------------------- GENERIC ---------------------
 
// mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
const mapAccumL = f =>
// A tuple of an accumulation and a list
// obtained by a combined map and fold,
// with accumulation from left to right.
acc => xs => [...xs].reduce((a, x, i) => {
const pair = f(a[0])([i, x]);
return [pair[0], a[1].concat(pair[1])];
}, [acc, []]);
 
 
// showLog :: a -> IO ()
const showLog = (...args) =>
console.log(
args
.map(x => JSON.stringify(x, null, 2))
.join(' -> ')
);
 
// MAIN ---
return main();
})();</syntaxhighlight>
{{Out}}
<pre>[
<lang JavaScript>[0, 1, 0.9428090415820626, 0.8660254037844386,
0,
0.9797958971132716, 1, 1.3997084244475297, 2]</lang>
1,
0.9428090415820626,
0.8660254037844386,
0.9797958971132716,
1,
1.3997084244475297,
2
]</pre>
 
=={{header|jq}}==
Line 2,112 ⟶ 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,137 ⟶ 2,391:
 
# Begin:
simulate</langsyntaxhighlight>
'''Example 1'''
# observations.txt
Line 2,149 ⟶ 2,403:
9
{{Out}}
<syntaxhighlight lang="sh">
<lang sh>
$ jq -s -f Dynamic_standard_deviation.jq observations.txt
0
Line 2,159 ⟶ 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,186 ⟶ 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,223 ⟶ 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,232 ⟶ 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,255 ⟶ 2,509:
for i in test
println(" - add $i → ", rstd(i))
end</langsyntaxhighlight>
 
{{out}}
Line 2,272 ⟶ 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,291 ⟶ 2,545:
val csd = CumStdDev()
for (d in testData) println("Add $d => ${csd.sd(d)}")
}</langsyntaxhighlight>
 
{{out}}
Line 2,307 ⟶ 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,334 ⟶ 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,347 ⟶ 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,376 ⟶ 2,630:
 
test_stdv()
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,384 ⟶ 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,395 ⟶ 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]])</syntaxhighlight>
StandardDeviation[AppendTo[$Data, n]])</lang>
 
=={{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,410 ⟶ 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,421 ⟶ 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,451 ⟶ 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,464 ⟶ 2,717:
=={{header|Nanoquery}}==
{{trans|Java}}
<langsyntaxhighlight Nanoquerylang="nanoquery">class StdDev
declare n
declare sum
Line 2,489 ⟶ 2,742:
for x in testData
println sd.sd(x)
end</langsyntaxhighlight>
 
{{out}}
Line 2,502 ⟶ 2,755:
 
=={{header|Nim}}==
 
<lang nim>import math, strutils
===Using global variables===
<syntaxhighlight lang="nim">import math, strutils
 
var sdSum, sdSum2, sdN = 0.0
 
proc sd(x: float): float =
sdN += 1
sdSum += x
sdSum2 += x * x
sqrt(sdSum2 / sdN - sdSum * sdSum / (sdN/ * sdN))
 
for value in [float 2,4,4,4,5,5,7,9]:
echo value, " ", formatFloat(sd(value), precision = -1)</syntaxhighlight>
 
for value in [2,4,4,4,5,5,7,9]:
echo value, " ", formatFloat(sd(value.float), precision = -1)</lang>
{{out}}
<pre>2 0
2 0
4 1
4 0.942809
Line 2,523 ⟶ 2,779:
7 1.39971
9 2</pre>
 
===Using an accumulator object===
<syntaxhighlight lang="nim">import math, strutils
 
type SDAccum = object
sdN, sdSum, sdSum2: float
 
var accum: SDAccum
 
proc add(accum: var SDAccum; value: float): float =
# Add a value to the accumulator. Return the standard deviation.
accum.sdN += 1
accum.sdSum += value
accum.sdSum2 += value * value
result = sqrt(accum.sdSum2 / accum.sdN - accum.sdSum * accum.sdSum / (accum.sdN * accum.sdN))
 
for value in [float 2, 4, 4, 4, 5, 5, 7, 9]:
echo value, " ", formatFloat(accum.add(value), precision = -1)</syntaxhighlight>
 
{{out}}
Same output.
 
===Using a closure===
<syntaxhighlight lang="nim">import math, strutils
 
func accumBuilder(): auto =
var sdSum, sdSum2, sdN = 0.0
 
result = func(value: float): float =
sdN += 1
sdSum += value
sdSum2 += value * value
result = sqrt(sdSum2 / sdN - sdSum * sdSum / (sdN * sdN))
 
let std = accumBuilder()
 
for value in [float 2, 4, 4, 4, 5, 5, 7, 9]:
echo value, " ", formatFloat(std(value), precision = -1)</syntaxhighlight>
 
{{out}}
Same output.
 
=={{header|Objeck}}==
{{trans|Java}}
<langsyntaxhighlight lang="objeck">
use Structure;
 
Line 2,562 ⟶ 2,859:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Objective-C}}==
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
@interface SDAccum : NSObject
Line 2,619 ⟶ 2,916:
}
return 0;
}</langsyntaxhighlight>
 
===Blocks===
Line 2,625 ⟶ 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,654 ⟶ 2,951:
}
return 0;
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let sqr x = x *. x
 
let stddev l =
Line 2,671 ⟶ 2,968:
Printf.printf "List: ";
List.iter (Printf.printf "%g ") l;
Printf.printf "\nStandard deviation: %g\n" (stddev l)</langsyntaxhighlight>
 
{{out}}
Line 2,685 ⟶ 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,709 ⟶ 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 2,750 ⟶ 3,047:
ans = ( prev + ( n / prev ) ) / 2
end
return ans</langsyntaxhighlight>
{{out}}
<pre>#1 value = 2 stdev = 0
Line 2,763 ⟶ 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 2,781 ⟶ 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 2,813 ⟶ 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 2,824 ⟶ 3,121:
8 item= 9 stddev= 2.000000000000000</pre>
==={{header|Delphi}}===
<langsyntaxhighlight Delphilang="delphi">program prj_CalcStdDerv;
 
{$APPTYPE CONSOLE}
Line 2,854 ⟶ 3,151:
end;
Readln;
end. </langsyntaxhighlight>
{{out}}
<pre>
Line 2,868 ⟶ 3,165:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">{
package SDAccum;
sub new {
Line 2,904 ⟶ 3,201:
return $self->stddev;
}
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="perl">my $sdacc = SDAccum->new;
my $sd;
 
Line 2,912 ⟶ 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 2,929 ⟶ 3,226:
}
 
print stddev($_), "\n" for qw(2 4 4 4 5 5 7 9);</langsyntaxhighlight>
 
{{out}}
Line 2,941 ⟶ 3,238:
2</pre>
 
one-liner:
=={{header|Phix}}==
<syntaxhighlight 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"}'</syntaxhighlight>
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.
<lang Phix>atom sdn = 0, sdsum = 0, sdsumsq = 0
 
small script:
procedure sdadd(atom n)
<syntaxhighlight lang="perl">use Math::StdDev;
sdn += 1
$d=new Math::StdDev;
sdsum += n
foreach my $v ( 2,4,4,4,5,5,7,9 ) {
sdsumsq += n*n
$d->Update($v);
end procedure
print $d->variance(),"\n"
}</syntaxhighlight>
 
{{out}}
function sdavg()
<pre>
return sdsum/sdn
0
end function
1
0.942809041582063
0.866025403784439
0.979795897113271
1
1.39970842444753
2</pre>
 
=={{header|Phix}}==
function sddev()
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.
return sqrt(sdsumsq/sdn - power(sdsum/sdn,2))
<!--<syntaxhighlight lang="phix">(phixonline)-->
end function
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
 
--test code:
<span style="color: #004080;">atom</span> <span style="color: #000000;">sdn</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">sdsum</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">sdsumsq</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
constant testset = {2, 4, 4, 4, 5, 5, 7, 9}
integer ti
<span style="color: #008080;">procedure</span> <span style="color: #000000;">sdadd</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
for i=1 to length(testset) do
<span style="color: #000000;">sdn</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
ti = testset[i]
<span style="color: #000000;">sdsum</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">n</span>
sdadd(ti)
<span style="color: #000000;">sdsumsq</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">*</span><span style="color: #000000;">n</span>
printf(1,"N=%d Item=%d Avg=%5.3f StdDev=%5.3f\n",{i,ti,sdavg(),sddev()})
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
end for</lang>
<span style="color: #008080;">function</span> <span style="color: #000000;">sdavg</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">sdsum</span><span style="color: #0000FF;">/</span><span style="color: #000000;">sdn</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">sddev</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">return</span> <span style="color: #7060A8;">sqrt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sdsumsq</span><span style="color: #0000FF;">/</span><span style="color: #000000;">sdn</span> <span style="color: #0000FF;">-</span> <span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sdsum</span><span style="color: #0000FF;">/</span><span style="color: #000000;">sdn</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #000080;font-style:italic;">--test code:</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">testset</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">9</span><span style="color: #0000FF;">}</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">ti</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">testset</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">ti</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">testset</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
<span style="color: #000000;">sdadd</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ti</span><span style="color: #0000FF;">)</span>
<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>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 2,981 ⟶ 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,011 ⟶ 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,026 ⟶ 3,349:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(scl 2)
 
(de stdDev ()
Line 3,043 ⟶ 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,055 ⟶ 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,079 ⟶ 3,402:
end std_dev;
end;</langsyntaxhighlight>
{{out}}
<pre>AVERAGE= 5.50000E+0000;
Line 3,087 ⟶ 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,099 ⟶ 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,112 ⟶ 3,435:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">;Define our Standard deviation function
Declare.d Standard_deviation(x)
 
Line 3,140 ⟶ 3,463:
MyList:
Data.i 2,4,4,4,5,5,7,9
EndDataSection</langsyntaxhighlight>
 
{{out}}
Line 3,158 ⟶ 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,179 ⟶ 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,194 ⟶ 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,201 ⟶ 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,225 ⟶ 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,252 ⟶ 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)
 
}
set.seed(12345L)
testdata <- c(2,4,4,4,5,5,7,9)
x <- rnorm(10)
reverseBesselCorrection(testdata)*sd(testdata) #2</lang>
 
===From scratch===
cumsd(x)
<lang rsplus>#Again, if na.rm is true, missing data points (NA values) are removed.
# [1] 0.0000000 0.3380816 0.8752973 1.1783628 1.2345538 1.3757142 1.2867220 1.2229056 1.1665168 1.1096814
uncorrectedsd <- function(x, na.rm=FALSE)
 
{
# Compare to the naive implementation, i.e. compute sd on each sublist:
len <- length(x)
Vectorize(function(k) sd(x[1:k]) * sqrt((k - 1) / k))(seq_along(x))
if(len < 2) stop("2 or more data points required")
# [1] NA 0.3380816 0.8752973 1.1783628 1.2345538 1.3757142 1.2867220 1.2229056 1.1665168 1.1096814
mu <- mean(x, na.rm=na.rm)
# 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>
ssq <- sum((x - mu)^2, na.rm=na.rm)
 
usd <- sqrt(ssq/len)
The task requires an accumulator solution:
usd
 
}
<syntaxhighlight lang="rsplus">accumsd <- function() {
uncorrectedsd(testdata) #2</lang>
n <- 0
m <- 0
s <- 0
function(x) {
n <<- n + 1
m <<- m + x
s <<- s + x * x
sqrt(s / n - (m / n)^2)
}
}
 
f <- accumsd()
sapply(x, f)
# [1] 0.0000000 0.3380816 0.8752973 1.1783628 1.2345538 1.3757142 1.2867220 1.2229056 1.1665168 1.1096814</syntaxhighlight>
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">
#lang racket
(require math)
Line 3,298 ⟶ 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,315 ⟶ 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,341 ⟶ 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*/
n= words(#); $= 0; $$= 0; L= length(n) /*N: # items; $,$$: sums to be zeroed*/
/* [↓] process each number in the list*/
do j=1 for n; _=word(#,do j); $ =$1 +for _n
_= word(#, j); $= $ + $$=$$ + _**2
say ' item' right(j,L)":" right(_,4) ' average=' left( $/j,12),$= $$ + _**2
' say standard deviation=' item' sqrtright($$/j, -L)":" right(_, 4) ' average=' left($/j, 12)**2),
end /*j*/ ' standard deviation=' sqrt($$/j - ($/j)* [↑] prettify output with whitespace*/2)
end /*j*/ /* [↑] prettify output with whitespace*/
say 'standard deviation: ' sqrt($$/n - ($/n)**2) /*calculate & display the std deviation*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); h=d+6; m.=9; numeric form
Line 3,358 ⟶ 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,373 ⟶ 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*/
n= words(#); $= 0; $$= 0 /*N: # items; $,$$: sums to be zeroed*/
/* [↓] process each number in the list*/
do j=1 for n; _=word(#,j); $ =$ + _ /*perform summation on two sets of #'s.*/
_= word(#, j); $$=$ $ + _**2 + /*perform summation on two sets of #'s.*/_
$$= $$ + _**2
end /*j*/
end /*j*/
say 'standard deviation: ' sqrt($$/n - ($/n)**2) /*calculate&display the std, deviation.*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); h=d+6; m.=9; numeric form
Line 3,388 ⟶ 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,395 ⟶ 3,734:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Cumulative standard deviation
 
Line 3,413 ⟶ 3,752:
see "" + num + " value in = " + stddata + " Stand Dev = " + standdev + nl
next
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,424 ⟶ 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,432 ⟶ 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,456 ⟶ 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,468 ⟶ 3,827:
 
=== Closure ===
<langsyntaxhighlight lang="ruby">def sdaccum
n, sum, sum2 = 0, 0.0, 0.0
lambda do |num|
Line 3,479 ⟶ 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,499 ⟶ 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,512 ⟶ 3,871:
Using a struct:
{{trans|Java}}
<langsyntaxhighlight lang="rust">pub struct CumulativeStandardDeviation {
n: f64,
sum: f64,
Line 3,543 ⟶ 3,902:
println!("{}", cum_stdev.push(*num as f64));
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,557 ⟶ 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,576 ⟶ 3,935:
println!("{}", sd_acc(*num as f64));
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,590 ⟶ 3,949:
 
=={{header|SAS}}==
<syntaxhighlight lang="sas">
<lang SAS>
*--Load the test data;
data test1;
Line 3,623 ⟶ 3,982:
var n sd /*mean*/;
run;
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,642 ⟶ 4,001:
===Generic for any numeric type===
{{libheader|Scala}}
<langsyntaxhighlight Scalalang="scala">import scala.math.sqrt
 
object StddevCalc extends App {
Line 3,667 ⟶ 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 3,682 ⟶ 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 3,700 ⟶ 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 3,721 ⟶ 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 3,735 ⟶ 4,093:
 
Using ''static'' variables:
<langsyntaxhighlight lang="ruby">func stddev(x) {
static(num=0, sum=0, sum2=0)
num++
Line 3,744 ⟶ 4,102:
}
 
%n(2 4 4 4 5 5 7 9).each { say stddev(_) }</langsyntaxhighlight>
{{out}}
<pre>
Line 3,760 ⟶ 4,118:
{{works with|GNU Smalltalk}}
 
<langsyntaxhighlight lang="smalltalk">Object subclass: SDAccum [
|sum sum2 num|
SDAccum class >> new [ |o|
Line 3,779 ⟶ 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 3,823 ⟶ 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 3,849 ⟶ 4,207:
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift">import Darwin
class stdDev{
Line 3,876 ⟶ 4,234:
}
var aa = stdDev()</langsyntaxhighlight>
{{out}}
<pre>
Line 3,891 ⟶ 4,249:
Functional:
 
<syntaxhighlight lang="swift">
<lang Swift>
func standardDeviation(arr : [Double]) -> Double
{
Line 3,904 ⟶ 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 3,941 ⟶ 4,299:
set sd [$sdacc value $val]
}
puts "the standard deviation is: $sd"</langsyntaxhighlight>
{{out}}
<pre>the standard deviation is: 2.0</pre>
Line 3,947 ⟶ 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 3,966 ⟶ 4,324:
}
sd stop
puts "the standard deviation is: $sd"</langsyntaxhighlight>
 
[[Category:Stateful transactions]]
Line 3,980 ⟶ 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,000 ⟶ 4,358:
variance = variance/(n+1)
sd = FormatNumber(Sqr(variance),6)
End Function</langsyntaxhighlight>
 
{{Out}}
Line 4,018 ⟶ 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,067 ⟶ 4,425:
Debug.Print standardDeviation(x(L0))
Next
End Sub</langsyntaxhighlight>
 
{{out}}
Line 4,079 ⟶ 4,437:
1.39970842444753
2
</pre>
 
=={{header|Wren}}==
{{libheader|Wren-fmt}}
{{libheader|Wren-math}}
<syntaxhighlight lang="wren">import "./fmt" for Fmt
import "./math" for Nums
 
var cumStdDev = Fiber.new { |a|
for (i in 0...a.count) {
var b = a[0..i]
System.print("Values : %(b)")
Fiber.yield(Nums.popStdDev(b))
}
}
 
var a = [2, 4, 4, 4, 5, 5, 7, 9]
while (true) {
var sd = cumStdDev.call(a)
if (cumStdDev.isDone) return
Fmt.print("Std Dev : $10.8f\n", sd)
}</syntaxhighlight>
 
{{out}}
<pre>
Values : [2]
Std Dev : 0.00000000
 
Values : [2, 4]
Std Dev : 1.00000000
 
Values : [2, 4, 4]
Std Dev : 0.94280904
 
Values : [2, 4, 4, 4]
Std Dev : 0.86602540
 
Values : [2, 4, 4, 4, 5]
Std Dev : 0.97979590
 
Values : [2, 4, 4, 4, 5, 5]
Std Dev : 1.00000000
 
Values : [2, 4, 4, 4, 5, 5, 7]
Std Dev : 1.39970842
 
Values : [2, 4, 4, 4, 5, 5, 7, 9]
Std Dev : 2.00000000
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
int A, I;
real N, S, S2;
Line 4,094 ⟶ 4,500:
];
CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 4,102 ⟶ 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