Cumulative standard deviation: Difference between revisions

m
m (→‎{{header|Wren}}: Minor tidy)
 
(121 intermediate revisions by 45 users not shown)
Line 1:
{{task|Probability and statistics}}
Write a stateful function, class, generator or coroutine that takes a series of floating point numbers, ''one at a time'', and returns the running [[wp:Standard Deviation|standard deviation]] of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task ''must'' state which is being used. Do not apply [[wp:Bessel's correction|Bessel's correction]]; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
 
{{task heading}}
 
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, ''one at a time'', and returns the running [[wp:Standard Deviation|standard deviation]] of the series.
 
The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task ''must'' state which is being used.
 
Do not apply [[wp:Bessel's correction|Bessel's correction]]; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
 
 
;Test case:
Use this to compute the standard deviation of this demonstration set, <math>\{2, 4, 4, 4, 5, 5, 7, 9\}</math>, which is <math>2</math>.
 
 
'''See also:'''
;Related tasks:
* [[Moving Average]]
* [[Random numbers]]
 
 
{{Related tasks/Statistical measures}}
 
<hr>
 
=={{header|11l}}==
{{trans|Python:_Callable_class}}
<syntaxhighlight lang="11l">T SD
sum = 0.0
sum2 = 0.0
n = 0.0
 
F ()(x)
.sum += x
.sum2 += x ^ 2
.n += 1.0
R sqrt(.sum2 / .n - (.sum / .n) ^ 2)
 
V sd_inst = SD()
L(value) [2, 4, 4, 4, 5, 5, 7, 9]
print(value‘ ’sd_inst(value))</syntaxhighlight>
 
{{out}}
<pre>
2 0
4 1
4 0.942809042
4 0.866025404
5 0.979795897
5 1
7 1.399708424
9 2
</pre>
 
=={{header|360 Assembly}}==
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 113 ⟶ 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 123 ⟶ 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 161 ⟶ 265:
end loop;
end Test_Deviation;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 183 ⟶ 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 234 ⟶ 338:
OD
)</langsyntaxhighlight>
{{out}}
<pre>
Line 253 ⟶ 357:
 
A code sample in an object oriented style:
<langsyntaxhighlight Algol68lang="algol68">MODE STAT = STRUCT(
LONG REAL sum,
LONG REAL sum2,
Line 328 ⟶ 432:
 
)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 347 ⟶ 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 362 ⟶ 466:
LONG REAL value = values[i];
printf(($2(xg(0,6))l$, value, sd(value)))
OD</langsyntaxhighlight>
{{out}}
<pre>
Line 378 ⟶ 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 402 ⟶ 506:
end for_i
 
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 414 ⟶ 518:
9.000000 2.000000
</pre>
 
=={{header|AppleScript}}==
 
Accumulation over a fold:
 
<syntaxhighlight lang="applescript">-------------- CUMULATIVE STANDARD DEVIATION -------------
 
-- stdDevInc :: Accumulator -> Num -> Index -> Accumulator
-- stdDevInc :: {sum:, squaresSum:, stages:} -> Real -> Integer
-- -> {sum:, squaresSum:, stages:}
on stdDevInc(a, n, i)
set sum to (sum of a) + n
set squaresSum to (squaresSum of a) + (n ^ 2)
set stages to (stages of a) & ¬
((squaresSum / i) - ((sum / i) ^ 2)) ^ 0.5
{sum:(sum of a) + n, squaresSum:squaresSum, stages:stages}
end stdDevInc
 
 
--------------------------- TEST -------------------------
on run
set xs to [2, 4, 4, 4, 5, 5, 7, 9]
stages of foldl(stdDevInc, ¬
{sum:0, squaresSum:0, stages:[]}, xs)
--> {0.0, 1.0, 0.942809041582, 0.866025403784, 0.979795897113, 1.0, 1.399708424448, 2.0}
end run
 
 
 
-------------------- GENERIC FUNCTIONS -------------------
 
-- 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
 
 
-- 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}}
<syntaxhighlight lang="applescrip">{0.0, 1.0, 0.942809041582, 0.866025403784,
0.979795897113, 1.0, 1.399708424448, 2.0}</syntaxhighlight>
 
 
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}}==
<syntaxhighlight lang="autohotkey">Data := [2,4,4,4,5,5,7,9]
{{incorrect|AutoHotkey|It does not return the ''running'' standard deviation of the series.}}
ahk forum: [http://www.autohotkey.com/forum/post-276698.html#276698 discussion]
for k, v in Data {
<lang AutoHotkey>std(2),std(4),std(4),std(4),std(5),std(5),std(7)
FileAppend, % "#" a_index " value = " v " stddev = " stddev(v) "`n", * ; send to stdout
MsgBox % std(9) ; 2
}
return
 
stdstddev(x="") {
static n, sum, sum2
Static sum:=0, sqr:=0, n:=0
n++
If (x="") ; blank parameter: reset
sum += x
sum := 0, sqr := 0, n := 0
sum2 += x*x
Else
sum += x, sqr += x*x, n++ ; update state
Return return sqrt((sqrsum2/n) - (((sum*sum)/n)/n))
}</langsyntaxhighlight>
{{out}}
<pre>
#1 value = 2 stddev 0 0.000000
#2 value = 4 stddev 0 1.000000
#3 value = 4 stddev 0 0.942809
#4 value = 4 stddev 0 0.866025
#5 value = 5 stddev 0 0.979796
#6 value = 5 stddev 0 1.000000
#7 value = 7 stddev 0 1.399708
#8 value = 9 stddev 0 2.000000
</pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f STANDARD_DEVIATION.AWK
BEGIN {
Line 451 ⟶ 725:
return(sqrt(variance))
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 466 ⟶ 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 482 ⟶ 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 495 ⟶ 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 514 ⟶ 788:
i% += 1
list(i%) = n
= SQR(MOD(list())^2/i% - (SUM(list())/i%)^2)</langsyntaxhighlight>
{{out}}
<pre>
Line 529 ⟶ 803:
=={{header|C}}==
 
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <math.h>
Line 576 ⟶ 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 590 ⟶ 864:
FREE_STAT_OBJECT(so);
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
 
namespace standardDeviation
{
class Program
{
static void Main(string[] args)
{
List<double> nums = new List<double> { 2, 4, 4, 4, 5, 5, 7, 9 };
for (int i = 1; i <= nums.Count; i++)
Console.WriteLine(sdev(nums.GetRange(0, i)));
}
 
static double sdev(List<double> nums)
{
List<double> store = new List<double>();
foreach (double n in nums)
store.Add((n - nums.Average()) * (n - nums.Average()));
 
return Math.Sqrt(store.Sum() / store.Count);
}
}
}</syntaxhighlight>
<pre>0
1
0,942809041582063
0,866025403784439
0,979795897113271
1
1,39970842444753
2</pre>
 
=={{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 634 ⟶ 943:
}
}
</syntaxhighlight>
</lang>
 
=={{header|C sharp|C#}}==
<lang csharp>using System;
using System.Collections.Generic;
using System.Linq;
 
namespace standardDeviation
{
class Program
{
static void Main(string[] args)
{
List<double> nums = new List<double> { 2, 4, 4, 4, 5, 5, 7, 9 };
for (int i = 1; i <= nums.Count; i++)
Console.WriteLine(sdev(nums.GetRange(0, i)));
}
 
static double sdev(List<double> nums)
{
List<double> store = new List<double>();
foreach (double n in nums)
store.Add((n - nums.Average()) * (n - nums.Average()));
 
return Math.Sqrt(store.Sum() / store.Count);
}
}
}</lang>
<pre>0
1
0,942809041582063
0,866025403784439
0,979795897113271
1
1,39970842444753
2</pre>
 
=={{header|Clojure}}==
{{incorrect|Clojure|Function does not take numbers one at a time.}}
<lang lisp>
(defn std-dev [samples]
(let [n (count samples)
mean (/ (reduce + samples) n)
intermediate (map #(Math/pow (- %1 mean) 2) samples)]
(Math/sqrt
(/ (reduce + intermediate) n))))
 
 
(println (std-dev [2 4 4 4 5 5 7 9])) ;;2.0
 
</syntaxhighlight lang="lisp">
(defn stateful-std-deviation[x]
(letfn [(std-dev[x]
(let [v (deref (find-var (symbol (str *ns* "/v"))))]
(swap! v conj x)
(let [m (/ (reduce + @v) (count @v))]
(Math/sqrt (/ (reduce + (map #(* (- m %) (- m %)) @v)) (count @v))))))]
(when (nil? (resolve 'v))
(intern *ns* 'v (atom [])))
(std-dev x)))
</syntaxhighlight>
 
=={{header|COBOL}}==
 
{{works with|OpenCOBOL|1.1}}
<langsyntaxhighlight lang="cobol">IDENTIFICATION DIVISION.
PROGRAM-ID. run-stddev.
environment division.
Line 760 ⟶ 1,033:
goback.
end program stddev.
</syntaxhighlight>
</lang>
<langsyntaxhighlight lang="cobol">sample output:
inp=002 stddev=+00000.0000
inp=004 stddev=+00001.0000
Line 770 ⟶ 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 803 ⟶ 1,076:
 
"""
</syntaxhighlight>
</lang>
 
{{out}}
Line 833 ⟶ 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 849 ⟶ 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 870 ⟶ 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 919 ⟶ 1,192:
END Do;
END StandardDeviation.
</syntaxhighlight>
</lang>
Execute: ^Q StandardDeviation.Do 2 4 4 4 5 5 7 9 ~<br/>
{{out}}
Line 932 ⟶ 1,205:
8 :> 2.0
</pre>
 
=={{header|Crystal}}==
===Object===
Use an object to keep state.
{{trans|Ruby}}
<syntaxhighlight lang="ruby">class StdDevAccumulator
def initialize
@n, @sum, @sum2 = 0, 0.0, 0.0
end
def <<(num)
@n += 1
@sum += num
@sum2 += num**2
Math.sqrt (@sum2 * @n - @sum**2) / @n**2
end
end
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}" }</syntaxhighlight>
{{out}}
<pre>
adding 2: stddev of 1 samples is 0.0
adding 4: stddev of 2 samples is 1.0
adding 4: stddev of 3 samples is 0.9428090415820634
adding 4: stddev of 4 samples is 0.8660254037844386
adding 5: stddev of 5 samples is 0.9797958971132712
adding 5: stddev of 6 samples is 1.0
adding 7: stddev of 7 samples is 1.3997084244475304
adding 9: stddev of 8 samples is 2.0
</pre>
 
===Closure===
{{trans|Ruby}}
<syntaxhighlight lang="ruby">def sdaccum
n, sum, sum2 = 0, 0.0, 0.0
->(num : Int32) do
n += 1
sum += num
sum2 += num**2
Math.sqrt( (sum2 * n - sum**2) / n**2 )
end
end
 
sd = sdaccum
[2,4,4,4,5,5,7,9].each {|n| print sd.call(n), ", "}</syntaxhighlight>
{{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 961 ⟶ 1,283:
writefln("%e", stdev.getStdDev());
}
}</langsyntaxhighlight>
{{out}}
<pre>0.000000e+00
Line 983 ⟶ 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,006 ⟶ 1,328:
return [insert, stddev]
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="e">? def [insert, stddev] := makeRunningStdDev()
# value: <insert>, <stddev>
 
Line 1,025 ⟶ 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}}
<syntaxhighlight lang="elixir">defmodule Standard_deviation do
def add_sample( pid, n ), do: send( pid, {:add, n} )
def create, do: spawn_link( fn -> loop( [] ) end )
def destroy( pid ), do: send( pid, :stop )
def get( pid ) do
send( pid, {:get, self()} )
receive do
{ :get, value, _pid } -> value
end
end
def task do
pid = create()
for x <- [2,4,4,4,5,5,7,9], do: add_print( pid, x, add_sample(pid, x) )
destroy( pid )
end
defp add_print( pid, n, _add ) do
IO.puts "Standard deviation #{ get(pid) } when adding #{ n }"
end
defp loop( ns ) do
receive do
{:add, n} -> loop( [n | ns] )
{:get, pid} ->
send( pid, {:get, loop_calculate( ns ), self()} )
loop( ns )
:stop -> :ok
end
end
defp loop_calculate( ns ) do
average = loop_calculate_average( ns )
:math.sqrt( loop_calculate_average( for x <- ns, do: :math.pow(x - average, 2) ) )
end
defp loop_calculate_average( ns ), do: Enum.sum( ns ) / length( ns )
end
 
Standard_deviation.task</syntaxhighlight>
 
{{out}}
<pre>
Standard deviation 0.0 when adding 2
Standard deviation 1.0 when adding 4
Standard deviation 0.9428090415820634 when adding 4
Standard deviation 0.8660254037844386 when adding 4
Standard deviation 0.9797958971132712 when adding 5
Standard deviation 1.0 when adding 5
Standard deviation 1.3997084244475302 when adding 7
Standard deviation 2.0 when adding 9
</pre>
 
=={{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}}
 
<syntaxhighlight lang="lisp">(let ((x '(2 4 4 4 5 5 7 9)))
(string-to-number (calc-eval "sqrt(vpvar($1))" nil (append '(vec) x))))</syntaxhighlight>
 
{{libheader|generator.el}}
 
<syntaxhighlight lang="lisp">;; lexical-binding: t
(require 'generator)
 
(iter-defun std-dev-gen (lst)
Emacs Lisp with built-in Emacs Calc
(let ((sum 0)
(avg 0)
(tmp '())
(std 0))
(dolist (i lst)
(setq i (float i))
(push i tmp)
(setq sum (+ sum i))
(setq avg (/ sum (length tmp)))
(setq std 0)
(dolist (j tmp)
(setq std (+ std (expt (- j avg) 2))))
(setq std (/ std (length tmp)))
(setq std (sqrt std))
(iter-yield std))))
 
(let* ((test-data '(2 4 4 4 5 5 7 9))
<lang emacs-lisp>
(generator (std-dev-gen test-data)))
(setq x '[2 4 4 4 5 5 7 9])
(dolist (i test-data)
(string-to-number (calc-eval (format "sqrt(vpvar(%s))" x)))</lang>
(message "with %d: %f" i (iter-next generator))))</syntaxhighlight>
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( standard_deviation ).
 
Line 1,096 ⟶ 1,511:
[add_print(Pid, X, add_sample(Pid, X)) || X <- [2,4,4,4,5,5,7,9]],
destroy( Pid ).
 
 
 
add_print( Pid, N, _Add ) -> io:fwrite( "Standard deviation ~p when adding ~p~n", [get(Pid), N] ).
Line 1,115 ⟶ 1,528:
 
loop_calculate_average( Ns ) -> lists:sum( Ns ) / erlang:length( Ns ).
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,130 ⟶ 1,543:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: accessors io kernel math math.functions math.parser
sequences ;
IN: standard-deviator
Line 1,151 ⟶ 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,176 ⟶ 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,196 ⟶ 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,208 ⟶ 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,262 ⟶ 1,704:
end function stddev
end program standard_deviation
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,283 ⟶ 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,358 ⟶ 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,435 ⟶ 1,877:
 
In other words, a two-pass method will be more accurate (where the second pass calculates the variance by accumulating deviations from the actual average, itself calculated with a working mean) but at the cost of that second pass and the saving of all the values. Higher precision variables for the accumulations are the easiest way towards accurate results.
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function calcStandardDeviation(number As Double) As Double
Static a() As Double
Redim Preserve a(0 To UBound(a) + 1)
Dim ub As UInteger = UBound(a)
a(ub) = number
Dim sum As Double = 0.0
For i As UInteger = 0 To ub
sum += a(i)
Next
Dim mean As Double = sum / (ub + 1)
Dim diff As Double
sum = 0.0
For i As UInteger = 0 To ub
diff = a(i) - mean
sum += diff * diff
Next
Return Sqr(sum/ (ub + 1))
End Function
 
Dim a(0 To 7) As Double = {2, 4, 4, 4, 5, 5, 7, 9}
 
For i As UInteger = 0 To 7
Print "Added"; a(i); " SD now : "; calcStandardDeviation(a(i))
Next
 
Print
Print "Press any key to quit"
Sleep</syntaxhighlight>
 
{{out}}
<pre>
Added 2 SD now : 0
Added 4 SD now : 1
Added 4 SD now : 0.9428090415820634
Added 4 SD now : 0.8660254037844386
Added 5 SD now : 0.9797958971132712
Added 5 SD now : 1
Added 7 SD now : 1.39970842444753
Added 9 SD now : 2
</pre>
 
=={{header|Go}}==
Line 1,440 ⟶ 1,926:
 
State maintained with a closure.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,462 ⟶ 1,948:
fmt.Println(r(x))
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,476 ⟶ 1,962:
 
=={{header|Groovy}}==
{{incorrect|Groovy|No function-like encapsulation of code defined and called.}}
Solution:
<langsyntaxhighlight lang="groovy">defList sumsamples = 0[]
 
def sumSq = 0
def countstdDev = 0{ def sample ->
samples << sample
def sum = samples.sum()
def sumSq = samples.sum { it * it }
def count = samples.size()
(sumSq/count - (sum/count)**2)**0.5
}
 
[2,4,4,4,5,5,7,9].each {
sum +=println "${stdDev(it)}"
}</syntaxhighlight>
sumSq += it*it
count++
println "running std.dev.: ${(sumSq/count - (sum/count)**2)**0.5}"
}</lang>
 
{{out}}
<pre>running std.dev.: 0
1
running std.dev.: 1
running std.dev.: 0.9428090416999145
running std.dev.: 0.8660254037844386
running std.dev.: 0.9797958971132712
1
running std.dev.: 1
running std.dev.: 1.3997084243469262
running std.dev.: 2</pre>
 
=={{header|Haskell}}==
Line 1,502 ⟶ 1,991:
We store the state in the <code>ST</code> monad using an <code>STRef</code>.
 
<syntaxhighlight lang="haskell">{-# LANGUAGE BangPatterns #-}
<lang haskell>import Data.List (genericLength)
 
import Data.List (foldl') -- '
import Data.STRef
import Control.Monad.ST
 
sddata :: RealFloatPair a b => [Pair !a] -> a!b
sd l = sqrt $ sum (map ((^2) . subtract mean) l) / n
where n = genericLength l
mean = sum l / n
 
sumLen :: [Double] -> Pair Double Double
sdAccum :: RealFloat a => ST s (a -> ST s a)
sumLen = fiof2 . foldl' (\(Pair s l) x -> Pair (s+x) (l+1)) (Pair 0.0 0) --'
sdAccum = do
where fiof2 (Pair s l) = Pair s (fromIntegral l)
accum <- newSTRef []
return $ \x -> do
modifySTRef accum (x:)
list <- readSTRef accum
return $ sd list
 
divl :: Pair Double Double -> Double
main = mapM_ print results
divl (Pair _ 0.0) = 0.0
where results = runST $ do
divl (Pair s l) = s / l
runningSD <- sdAccum
 
mapM runningSD [2, 4, 4, 4, 5, 5, 7, 9]</lang>
sd :: [Double] -> Double
sd xs = sqrt $ foldl' (\a x -> a+(x-m)^2) 0 xs / l --'
where p@(Pair s l) = sumLen xs
m = divl p
 
mkSD :: ST s (Double -> ST s Double)
mkSD = go <$> newSTRef []
where go acc x =
modifySTRef acc (x:) >> (sd <$> readSTRef acc)
 
main = mapM_ print $ runST $
mkSD >>= forM [2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0]</syntaxhighlight>
 
 
Or, perhaps more simply, as a map-accumulation over an indexed list:
 
<syntaxhighlight lang="haskell">import Data.List (mapAccumL)
 
 
-------------- CUMULATIVE STANDARD DEVIATION -------------
 
cumulativeStdDevns :: [Float] -> [Float]
cumulativeStdDevns = snd . mapAccumL go (0, 0) . zip [1.0..]
where
go (s, q) (i, x) =
let _s = s + x
_q = q + (x ^ 2)
in ((_s, _q), sqrt ((_q / i) - ((_s / i) ^ 2)))
 
 
 
--------------------------- TEST -------------------------
main :: IO ()
main = mapM_ print $ cumulativeStdDevns [2, 4, 4, 4, 5, 5, 7, 9]</syntaxhighlight>
{{Out}}
<pre>0.0
1.0
0.9428093
0.8660254
0.97979593
1.0
1.3997087
2.0</pre>
 
=={{header|Haxe}}==
<langsyntaxhighlight lang="haxe">using Lambda;
 
class Main {
Line 1,547 ⟶ 2,074:
return Math.sqrt(average(store));
}
}</langsyntaxhighlight>
<pre>0
1
Line 1,558 ⟶ 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,573 ⟶ 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,584 ⟶ 2,111:
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">rocedureprocedure main()
 
stddev() # reset state / empty
Line 1,592 ⟶ 2,119:
end
 
procedure stddev(x) /:# running standard deviation
static X,sumX,sum2X
 
Line 1,605 ⟶ 2,132:
return sqrt( (sum2X / *X) - (sumX / *X)^2 )
}
end</langsyntaxhighlight>
{{out}}
<pre>stddev (so far) := 0.0
Line 1,615 ⟶ 2,142:
stddev (so far) := 1.39970842444753
stddev (so far) := 2.0</pre>
 
=={{header|IS-BASIC}}==
<syntaxhighlight lang="is-basic">100 PROGRAM "StDev.bas"
110 LET N=8
120 NUMERIC ARR(1 TO N)
130 FOR I=1 TO N
140 READ ARR(I)
150 NEXT
160 DEF STDEV(N)
170 LET S1,S2=0
180 FOR I=1 TO N
190 LET S1=S1+ARR(I)^2:LET S2=S2+ARR(I)
200 NEXT
210 LET STDEV=SQR((N*S1-S2^2)/N^2)
220 END DEF
230 FOR J=1 TO N
240 PRINT J;"item =";ARR(J),"standard dev =";STDEV(J)
250 NEXT
260 DATA 2,4,4,4,5,5,7,9</syntaxhighlight>
 
=={{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,627 ⟶ 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 1,641 ⟶ 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 1,672 ⟶ 2,218:
}
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
 
===Imperative===
 
Uses a closure.
<langsyntaxhighlight lang="javascript">function running_stddev() {
var n = 0;
var sum = 0.0;
Line 1,695 ⟶ 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===
====ES5====
Accumulating across a fold
 
<syntaxhighlight lang="javascript">(function (xs) {
return xs.reduce(function (a, x, i) {
var n = i + 1,
sum_ = a.sum + x,
squaresSum_ = a.squaresSum + (x * x);
 
return {
sum: sum_,
squaresSum: squaresSum_,
stages: a.stages.concat(
Math.sqrt((squaresSum_ / n) - Math.pow((sum_ / n), 2))
)
};
 
}, {
sum: 0,
squaresSum: 0,
stages: []
}).stages
 
})([2, 4, 4, 4, 5, 5, 7, 9]);</syntaxhighlight>
 
{{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>[
0,
1,
0.9428090415820626,
0.8660254037844386,
0.9797958971132716,
1,
1.3997084244475297,
2
]</pre>
 
=={{header|jq}}==
Line 1,716 ⟶ 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 1,741 ⟶ 2,391:
 
# Begin:
simulate</langsyntaxhighlight>
'''Example 1'''
# observations.txt
Line 1,753 ⟶ 2,403:
9
{{Out}}
<syntaxhighlight lang="sh">
<lang sh>
$ jq -s -f Dynamic_standard_deviation.jq observations.txt
0
Line 1,763 ⟶ 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 1,790 ⟶ 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 1,827 ⟶ 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 1,836 ⟶ 2,486:
Next observation: 0
8.16496580927726
</syntaxhighlight>
</lang>
 
=={{header|Julia}}==
Use a closure to create a running standard deviation function.
<syntaxhighlight lang="julia">function makerunningstd(::Type{T} = Float64) where T
<lang Julia>
∑x = ∑x² = zero(T)
function makerunningstd()
an = zero(Float64)0
b = zero(Float64)
n = zero(Int64)
function runningstd(x)
a∑x += x
b∑x² += x ^ 2
n += 1
stds = sqrt(∑x² / n*b - a^2)(∑x / n) ^ 2
return stds
end
return runningstd
end
 
test = Float64[2, 4, 4, 4, 5, 5, 7, 9]
 
rstd = makerunningstd()
 
println("Perform a running standard deviation of ", test)
for i in test
println(i, " =>- add $i → ", rstd(i))
end</syntaxhighlight>
end
 
</lang>
{{out}}
<pre>Perform a running standard deviation of [2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0]
- add 2.0 → 0.0
- add 4.0 → 1.0
- add 4.0 → 0.8888888888888875
- add 4.0 → 0.75
- add 5.0 → 0.9600000000000009
- add 5.0 → 1.0
- add 7.0 → 1.9591836734693864
- add 9.0 → 4.0
</pre>
 
=={{header|Kotlin}}==
{{trans|Java}}
Using a class to keep the running sum, sum of squares and number of elements added so far:
<syntaxhighlight lang="scala">// version 1.0.5-2
 
class CumStdDev {
private var n = 0
private var sum = 0.0
private var sum2 = 0.0
 
fun sd(x: Double): Double {
n++
sum += x
sum2 += x * x
return Math.sqrt(sum2 / n - sum * sum / n / n)
}
}
 
fun main(args: Array<String>) {
val testData = doubleArrayOf(2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0)
val csd = CumStdDev()
for (d in testData) println("Add $d => ${csd.sd(d)}")
}</syntaxhighlight>
 
{{out}}
<pre>
Add 2.0 => 0.0
Perform a running standard deviation of [2,4,4,4,5,5,7,9]
2Add 4.0 => 01.0
Add 4.0 => 0.9428090415820626
4 => 1.0
Add 4.0 => 0.94280904158206358660254037844386
4Add 5.0 => 0.86602540378443869797958971132708
Add 5.0 => 01.97979589711327120
5Add 7.0 => 1.0399708424447531
Add 9.0 => 2.0
7 => 1.3997084244475302
9 => 2.0
</pre>
 
=={{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 1,907 ⟶ 2,588:
 
Data 2, 4, 4, 4, 5, 5, 7, 9
</syntaxhighlight>
</lang>
<pre>
New data 2 so S.D. now = 0.000000
Line 1,917 ⟶ 2,598:
New data 7 so S.D. now = 1.399708
New data 9 so S.D. now = 2.000000
</pre>
 
=={{header|Lobster}}==
<syntaxhighlight lang="lobster">
// Stats computes a running mean and variance
// See Knuth TAOCP vol 2, 3rd edition, page 232
 
class Stats:
M = 0.0
S = 0.0
n = 0
def incl(x):
n += 1
if n == 1:
M = x
else:
let mm = (x - M)
M += mm / n
S += mm * (x - M)
def mean(): return M
//def variance(): return (if n > 1.0: S / (n - 1.0) else: 0.0) // Bessel's correction
def variance(): return (if n > 0.0: S / n else: 0.0)
def stddev(): return sqrt(variance())
def count(): return n
def test_stdv() -> float:
let v = [2,4,4,4,5,5,7,9]
let s = Stats {}
for(v) x: s.incl(x+0.0)
print concat_string(["Mean: ", string(s.mean()), ", Std.Deviation: ", string(s.stddev())], "")
 
test_stdv()
</syntaxhighlight>
{{out}}
<pre>
Mean: 5.0, Std.Deviation: 2.0
</pre>
 
=={{header|Lua}}==
Uses a closure. Translation of JavaScript.
<langsyntaxhighlight lang="lua">function stdev()
local sum, sumsq, k = 0,0,0
return function(n)
Line 1,932 ⟶ 2,649:
for i, v in ipairs{2,4,4,4,5,5,7,9} do
print(ldev(v))
end</langsyntaxhighlight>
 
=={{header|Mathematica}}==
<lang Mathematica>runningSTDDev[n_] := (If[Not[ValueQ[$Data]], $Data = {}];
StandardDeviation[AppendTo[$Data, n]])</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">runningSTDDev[n_] := (If[Not[ValueQ[$Data]], $Data = {}];StandardDeviation[AppendTo[$Data, n]])</syntaxhighlight>
 
=={{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 1,948 ⟶ 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 1,959 ⟶ 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}}==
<syntaxhighlight lang="miniscript">StdDeviator = {}
StdDeviator.count = 0
StdDeviator.sum = 0
StdDeviator.sumOfSquares = 0
 
StdDeviator.add = function(x)
self.count = self.count + 1
self.sum = self.sum + x
self.sumOfSquares = self.sumOfSquares + x*x
end function
 
StdDeviator.stddev = function()
m = self.sum / self.count
return sqrt(self.sumOfSquares / self.count - m*m)
end function
 
sd = new StdDeviator
for x in [2, 4, 4, 4, 5, 5, 7, 9]
sd.add x
end for
print sd.stddev</syntaxhighlight>
{{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'' С/П ...
 
=={{header|Nanoquery}}==
{{trans|Java}}
<syntaxhighlight lang="nanoquery">class StdDev
declare n
declare sum
declare sum2
 
def StdDev()
n = 0
sum = 0
sum2 = 0
end
 
def sd(x)
this.n += 1
this.sum += x
this.sum2 += x*x
 
return sqrt(sum2/n - sum*sum/n/n)
end
end
 
testData = {2,4,4,4,5,5,7,9}
sd = new(StdDev)
 
for x in testData
println sd.sd(x)
end</syntaxhighlight>
 
{{out}}
<pre>0.0
1.0
0.9428090415820634
0.8660254037844386
0.9797958971132712
1.0
1.3997084244475304
2.0</pre>
 
=={{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 =
sdN += 1
sdSum += float(x)
sdSum2 += float(x*x)
sqrt(sdSum2/sdN - sdSum*sdSum/sdN/sdN)
 
proc sd(x: float): float =
for value in [2,4,4,4,5,5,7,9]:
sdN += 1
echo value, " ", formatFloat(sd(value), precision = 0)</lang>
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>
 
{{out}}
<pre>2 0
2 0
4 1
4 0.942809
Line 1,997 ⟶ 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}}
<syntaxhighlight lang="objeck">
use Structure;
 
bundle Default {
class StdDev {
nums : FloatVector;
New() {
nums := FloatVector->New();
}
function : Main(args : String[]) ~ Nil {
sd := StdDev->New();
test_data := [2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0];
each(i : test_data) {
sd->AddNum(test_data[i]);
sd->GetSD()->PrintLine();
};
}
method : public : AddNum(num : Float) ~ Nil {
nums->AddBack(num);
}
method : public : native : GetSD() ~ Float {
sq_diffs := 0.0;
avg := nums->Average();
each(i : nums) {
num := nums->Get(i);
sq_diffs += (num - avg) * (num - avg);
};
return (sq_diffs / nums->Size())->SquareRoot();
}
}
}
</syntaxhighlight>
 
=={{header|Objective-C}}==
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
@interface SDAccum : NSObject
Line 2,052 ⟶ 2,916:
}
return 0;
}</langsyntaxhighlight>
 
===Blocks===
Line 2,058 ⟶ 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,087 ⟶ 2,951:
}
return 0;
}</langsyntaxhighlight>
 
=={{header|Objeck}}==
{{trans|Java}}
<lang objeck>
use Structure;
 
bundle Default {
class StdDev {
nums : FloatVector;
New() {
nums := FloatVector->New();
}
function : Main(args : String[]) ~ Nil {
sd := StdDev->New();
test_data := [2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0];
each(i : test_data) {
sd->AddNum(test_data[i]);
sd->GetSD()->PrintLine();
};
}
method : public : AddNum(num : Float) ~ Nil {
nums->AddBack(num);
}
method : public : native : GetSD() ~ Float {
sq_diffs := 0.0;
avg := nums->Average();
each(i : nums) {
num := nums->Get(i);
sq_diffs += (num - avg) * (num - avg);
};
return (sq_diffs / nums->Size())->SquareRoot();
}
}
}
</lang>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let sqr x = x *. x
 
let stddev l =
Line 2,144 ⟶ 2,968:
Printf.printf "List: ";
List.iter (Printf.printf "%g ") l;
Printf.printf "\nStandard deviation: %g\n" (stddev l)</langsyntaxhighlight>
 
{{out}}
Line 2,158 ⟶ 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 Constant newconst: StdValues
 
: stddev(x)
{
| l |
StdValues receive x + dup ->l StdValues send drop
#qs l map(#sq) sum l size asFloat / l avg sq - sqrt ;</syntaxhighlight>
}</lang>
 
{{out}}
Line 2,184 ⟶ 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
do i = 1 to x~size
sd = sdacc~value(x[i])
Say '#'i 'value =' x[i] 'stdev =' sd
end
 
say "std dev = "sd
 
 
::class SDAccum
Line 2,227 ⟶ 3,047:
ans = ( prev + ( n / prev ) ) / 2
end
return ans</langsyntaxhighlight>
{{out}}
<pre>#1 value = 2 stdev = 0
#2 value = 4 stdev = 1
#3 value = 4 stdev = 0.94280905
#4 value = 4 stdev = 0.866025405
#5 value = 5 stdev = 0.979795895
#6 value = 5 stdev = 1
#7 value = 7 stdev = 1.39970844
#8 value = 9 stdev = 2</pre>
 
=={{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,249 ⟶ 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,281 ⟶ 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,292 ⟶ 3,121:
8 item= 9 stddev= 2.000000000000000</pre>
==={{header|Delphi}}===
<langsyntaxhighlight Delphilang="delphi">program prj_CalcStdDerv;
 
{$APPTYPE CONSOLE}
Line 2,322 ⟶ 3,151:
end;
Readln;
end. </langsyntaxhighlight>
{{out}}
<pre>
Line 2,334 ⟶ 3,163:
9.0000000000000000E+0000 -> 2.0000000000000000E+0000
</pre>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">{
package SDAccum;
sub new {
Line 2,371 ⟶ 3,201:
return $self->stddev;
}
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="perl">my $sdacc = SDAccum->new;
my $sd;
 
Line 2,379 ⟶ 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,396 ⟶ 3,226:
}
 
print stddev($_), "\n" for qw(2 4 4 4 5 5 7 9);</langsyntaxhighlight>
 
{{out}}
Line 2,408 ⟶ 3,238:
2</pre>
 
one-liner:
=={{header|Perl 6}}==
<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>
{{works with|Rakudo Star|2010.08}}
Using a closure:
<lang perl6>sub sd (@a) {
my $mean = @a R/ [+] @a;
sqrt @a R/ [+] map (* - $mean)**2, @a;
}
 
sub sdaccum {
my @a;
return { push @a, $^x; sd @a; };
}
 
my &f = sdaccum;
say f $_ for 2, 4, 4, 4, 5, 5, 7, 9;</lang>
 
small script:
Using a state variable:
<syntaxhighlight lang="perl">use Math::StdDev;
<lang perl6># remember that <(x-<x>)²> = <x²> - <x>²
$d=new Math::StdDev;
sub stddev($x) {
foreach my $v ( 2,4,4,4,5,5,7,9 ) {
sqrt
$d->Update($v);
(.[2] += $x**2) / ++.[0] -
print $d->variance(),"\n"
((.[1] += $x) / .[0])**2
}</syntaxhighlight>
given state @;
}
 
say stddev $_ for <2 4 4 4 5 5 7 9>;</lang>
 
{{out}}
<pre>0
0
1
0.942809041582063
Line 2,444 ⟶ 3,259:
1.39970842444753
2</pre>
 
=={{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.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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>
<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>
<span style="color: #000000;">sdn</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #000000;">sdsum</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">n</span>
<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>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<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>
N=1 Item=2 Avg=2.000 StdDev=0.000
N=2 Item=4 Avg=3.000 StdDev=1.000
N=3 Item=4 Avg=3.333 StdDev=0.943
N=4 Item=4 Avg=3.500 StdDev=0.866
N=5 Item=5 Avg=3.800 StdDev=0.980
N=6 Item=5 Avg=4.000 StdDev=1.000
N=7 Item=7 Avg=4.429 StdDev=1.400
N=8 Item=9 Avg=5.000 StdDev=2.000
</pre>
 
=={{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 2,476 ⟶ 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 2,489 ⟶ 3,347:
Adding 9: result 2
</pre>
 
=={{header|PicoLisp}}==
<syntaxhighlight lang="picolisp">(scl 2)
 
(de stdDev ()
(curry ((Data)) (N)
(push 'Data N)
(let (Len (length Data) M (*/ (apply + Data) Len))
(sqrt
(*/
(sum
'((N) (*/ (- N M) (- N M) 1.0))
Data )
1.0
Len )
T ) ) ) )
 
(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)) ) )</syntaxhighlight>
{{out}}
<pre>2.00 -> 0.00
4.00 -> 1.00
4.00 -> 0.94
4.00 -> 0.87
5.00 -> 0.98
5.00 -> 1.00
7.00 -> 1.40
9.00 -> 2.00</pre>
 
=={{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 2,515 ⟶ 3,402:
end std_dev;
end;</langsyntaxhighlight>
{{out}}
<pre>AVERAGE= 5.50000E+0000;
Standard deviation 2.87228E+0000 </pre>
 
=={{header|PicoLisp}}==
<lang PicoLisp>(scl 2)
 
(de stdDev ()
(curry ((Data)) (N)
(push 'Data N)
(let (Len (length Data) M (*/ (apply + Data) Len))
(sqrt
(*/
(sum
'((N) (*/ (- N M) (- N M) 1.0))
Data )
1.0
Len )
T ) ) ) )
 
(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)) ) )</lang>
{{out}}
<pre>2.00 -> 0.00
4.00 -> 1.00
4.00 -> 0.94
4.00 -> 0.87
5.00 -> 0.98
5.00 -> 1.00
7.00 -> 1.40
9.00 -> 2.00</pre>
 
=={{header|PowerShell}}==
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 2,564 ⟶ 3,422:
[Math]::Sqrt($sum / $nums.Length)
}
}</langsyntaxhighlight>
Usage as follows:
<pre>PS> 2,4,4,4,5,5,7,9 | Get-StandardDeviation
Line 2,577 ⟶ 3,435:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">;Define our Standard deviation function
Declare.d Standard_deviation(x)
 
Line 2,605 ⟶ 3,463:
MyList:
Data.i 2,4,4,4,5,5,7,9
EndDataSection</langsyntaxhighlight>
 
{{out}}
Line 2,623 ⟶ 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 2,644 ⟶ 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 2,659 ⟶ 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 2,666 ⟶ 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 2,690 ⟶ 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 2,717 ⟶ 3,575:
5 1.0
7 1.39970842445
9 2.0</langsyntaxhighlight>
 
 
===Python: In a couple of 'functional' lines===
<langsyntaxhighlight lang="python">>>> myMean = lambda listMyList : reduce(lambda x, y: x + y, lMyList) / float(len(lMyList))
>>> myStd = lambda listMyList : (reduce(lambda x,y : x + y , map(lambda x: (x-myMean(lMyList))**2 , lMyList)) / float(len(lMyList)))**.5
 
>>> myList =print myStd([2,4,4,4,5,5,7,9])
2.0
>>> print myStd(MyList)
</syntaxhighlight>
 
=={{header|R}}==
 
To compute the running sum, one must keep track of the number of items, the sum of values, and the sum of squares.
 
If the goal is to get a vector of running standard deviations, the simplest is to do it with cumsum:
 
<syntaxhighlight lang="rsplus">cumsd <- function(x) {
n <- seq_along(x)
sqrt(cumsum(x^2) / n - (cumsum(x) / n)^2)
}
 
set.seed(12345L)
x <- rnorm(10)
 
cumsd(x)
# [1] 0.0000000 0.3380816 0.8752973 1.1783628 1.2345538 1.3757142 1.2867220 1.2229056 1.1665168 1.1096814
 
# Compare to the naive implementation, i.e. compute sd on each sublist:
Vectorize(function(k) sd(x[1:k]) * sqrt((k - 1) / k))(seq_along(x))
# [1] NA 0.3380816 0.8752973 1.1783628 1.2345538 1.3757142 1.2867220 1.2229056 1.1665168 1.1096814
# 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>
 
The task requires an accumulator solution:
 
<syntaxhighlight lang="rsplus">accumsd <- function() {
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 2,737 ⟶ 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)
 
Using a closure:
<syntaxhighlight lang="raku" line>sub sd (@a) {
my $mean = @a R/ [+] @a;
sqrt @a R/ [+] map (* - $mean)², @a;
}
sub sdaccum {
my @a;
return { push @a, $^x; sd @a; };
}
my &f = sdaccum;
say f $_ for 2, 4, 4, 4, 5, 5, 7, 9;</syntaxhighlight>
 
Using a state variable (remember that <tt><(x-<x>)²> = <x²> - <x>²</tt>):
<syntaxhighlight lang="raku" line>sub stddev($x) {
sqrt
( .[2] += $x²) / ++.[0]
- ((.[1] += $x ) / .[0])²
given state @;
}
 
say .&stddev for <2 4 4 4 5 5 7 9>;</syntaxhighlight>
 
{{out}}
<pre>0
1
0.942809041582063
0.866025403784439
0.979795897113271
1
1.39970842444753
2</pre>
 
=={{header|REXX}}==
ThisThese REXX versionversions usesuse &nbsp; ''running sums''.
===show running sums===
<lang rexx>/*REXX pgm finds & displays the standard deviation of a given set of numbers.*/
<syntaxhighlight lang="rexx">/*REXX program calculates and displays the standard deviation of a given set of numbers.*/
parse arg # /*any optional arguments on the C.L. ? */
ifparse arg #='' then # = 2 4 4 4 5 5 7 9 /*None specified?obtain optional Thenarguments usefrom the defaultCL*/
if #='' then #= 2 4 4 4 5 5 7 9 /*None specified? Then use the default*/
w=words(#); L=length(w); $=0; $$=0 /*# items; item width; couple of sums*/
n= words(#); $= 0; $$= 0; L= length(n) /*N: [↓]# items; process$,$$: each numbersums into thebe listzeroed*/
do j=1 for w; _=word(#,j); $=$+_; $$=$$+_ /* [↓] process each number in the list*2/
do j=1 for n
say ' item' right(j,L)":" right(_,4) ' average=' left($/j,12),
' _= word(#, j); standard deviation=' left(sqrt( $= $/j - ($/j)**2 ),+ 15) _
end /*j*/ /* [↑]$$= $$ prettify output+ with whitespace_**/2
exit say ' item' right(j, L)":" right(_, 4) ' average=' left($/*stickj, a fork in it12), we're all done. */
' standard deviation=' sqrt($$/j - ($/j)**2)
/*────────────────────────────────────────────────────────────────────────────*/
end /*j*/ /* [↑] prettify output with whitespace*/
sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9
say 'standard deviation: ' sqrt($$/n - ($/n)**2) /*calculate & display the std deviation*/
numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end
exit 0 /*stick a fork in it, we're all done. */
parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2
/*──────────────────────────────────────────────────────────────────────────────────────*/
do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/
sqrt: procedure; parse arg x; if x=0 then do k=j+5 toreturn 0 by -1; numeric d=digits m.k(); gh=(gd+x/g)*6; m.5=9; numeric end /*k*/form
numeric digits d; parse value return format(g/x,2,1,,0)i 'E0' with g 'E' _ .; g=g /*make complex.5'e'_ if% X < 0.*/</lang>2
do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/
'''output''' &nbsp; when using the default input of: &nbsp; <tt> 2 &nbsp; 4 &nbsp; 4 &nbsp; 4 &nbsp; 5 &nbsp; 5 &nbsp; 7 &nbsp; 9 </tt>
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</syntaxhighlight>
{{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>
item 1: 2 average= 2 standard deviation= 0
Line 2,768 ⟶ 3,707:
item 7: 7 average= 4.42857143 standard deviation= 1.39970843
item 8: 9 average= 5 standard deviation= 2
standard deviation: 2
</pre>
 
===only show standard deviation===
<syntaxhighlight 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 /*perform summation on two sets of #'s.*/
_= word(#, j); $= $ + _
$$= $$ + _**2
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
numeric digits; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g * .5'e'_ % 2
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</syntaxhighlight>
{{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>
standard deviation: 2
</pre>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
# Project : Cumulative standard deviation
 
decimals(6)
sdsave = list(100)
sd = "2,4,4,4,5,5,7,9"
sumval = 0
sumsqs = 0
 
for num = 1 to 8
sd = substr(sd, ",", "")
stddata = number(sd[num])
sumval = sumval + stddata
sumsqs = sumsqs + pow(stddata,2)
standdev = pow(((sumsqs / num) - pow((sumval /num),2)),0.5)
sdsave[num] = string(num) + " " + string(sumval) +" " + string(sumsqs)
see "" + num + " value in = " + stddata + " Stand Dev = " + standdev + nl
next
</syntaxhighlight>
Output:
<pre>
1 value in = 2 Stand Dev = 0
2 value in = 4 Stand Dev = 1
3 value in = 4 Stand Dev = 0.942809
4 value in = 4 Stand Dev = 0.866025
5 value in = 5 Stand Dev = 0.979796
6 value in = 5 Stand Dev = 1
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 2,776 ⟶ 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 2,800 ⟶ 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 2,812 ⟶ 3,827:
 
=== Closure ===
<langsyntaxhighlight lang="ruby">def sdaccum
n, sum, sum2 = 0, 0.0, 0.0
lambda do |num|
Line 2,823 ⟶ 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 2,844 ⟶ 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 2,853 ⟶ 3,867:
7 value in = 7 Stand Dev = 1.399708
8 value in = 9 Stand Dev = 2.000000</pre>
 
=={{header|Rust}}==
Using a struct:
{{trans|Java}}
<syntaxhighlight lang="rust">pub struct CumulativeStandardDeviation {
n: f64,
sum: f64,
sum_sq: f64
}
 
impl CumulativeStandardDeviation {
pub fn new() -> Self {
CumulativeStandardDeviation {
n: 0.,
sum: 0.,
sum_sq: 0.
}
}
 
fn push(&mut self, x: f64) -> f64 {
self.n += 1.;
self.sum += x;
self.sum_sq += x * x;
 
(self.sum_sq / self.n - self.sum * self.sum / self.n / self.n).sqrt()
}
}
 
fn main() {
let nums = [2, 4, 4, 4, 5, 5, 7, 9];
 
let mut cum_stdev = CumulativeStandardDeviation::new();
for num in nums.iter() {
println!("{}", cum_stdev.push(*num as f64));
}
}</syntaxhighlight>
{{out}}
<pre>
0
1
0.9428090415820626
0.8660254037844386
0.9797958971132708
1
1.399708424447531
2
</pre>
 
Using a closure:
<syntaxhighlight lang="rust">fn sd_creator() -> impl FnMut(f64) -> f64 {
let mut n = 0.0;
let mut sum = 0.0;
let mut sum_sq = 0.0;
move |x| {
sum += x;
sum_sq += x*x;
n += 1.0;
(sum_sq / n - sum * sum / n / n).sqrt()
}
}
 
fn main() {
let nums = [2, 4, 4, 4, 5, 5, 7, 9];
 
let mut sd_acc = sd_creator();
for num in nums.iter() {
println!("{}", sd_acc(*num as f64));
}
}</syntaxhighlight>
{{out}}
<pre>
0
1
0.9428090415820626
0.8660254037844386
0.9797958971132708
1
1.399708424447531
2
</pre>
 
=={{header|SAS}}==
<syntaxhighlight lang="sas">
<lang SAS>
*--Load the test data;
data test1;
Line 2,888 ⟶ 3,982:
var n sd /*mean*/;
run;
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,903 ⟶ 3,997:
8 2.00000
</pre>
 
 
=={{header|Scala}}==
===Generic for any numeric type===
{{libheader|Scala}}
<langsyntaxhighlight Scalalang="scala">import scala.math.sqrt
 
object StddevCalc extends App {
 
def calcAvgAndStddev[T](ts: Iterable[T])(implicit num: Fractional[T]): (T, Double) = {
def avg(ts: Iterable[T])(implicit num: Fractional[T]): T = {
num.div(ts.sum, num.fromInt(ts.size)) // Leaving with type of function T
}
 
val mean: T = avg(ts) // Leave val type of T
val stdDev = // Root of mean diffs
val stdDev = sqrt(numts.toDouble(map { x =>
val diff ts= num.foldLefttoDouble(num.zero)minus((bx, amean)) =>
diff * diff
num.plus(b, num.times(num.minus(a, mean), num.minus(a, mean))))) /
}.sum / ts.size)
 
(mean, stdDev)
}
 
def calcAvgAndStddev(ts: Iterable[BigDecimal]): (Double, Double) = // Overloaded for BigDecimal
calcAvgAndStddev(ts.map(_.toDouble))
 
println(calcAvgAndStddev(List(2.0E0, 4.0, 4, 4, 5, 5, 7, 9)))
Line 2,933 ⟶ 4,023:
println(calcAvgAndStddev(0.1 to 1.1 by 0.05))
println(calcAvgAndStddev(List(BigDecimal(120), BigDecimal(1200))))
 
}</lang>
println(s"Successfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart}ms]")
 
}</syntaxhighlight>
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">
(define (standart-deviation-generator)
(let ((nums '()))
Line 2,948 ⟶ 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 2,965 ⟶ 4,057:
 
=={{header|Sidef}}==
Using an object to keep state:
<lang ruby>func stddev(x) {
<syntaxhighlight lang="ruby">class StdDevAccumulator(n=0, sum=0, sumofsquares=0) {
static(num, sum, sum2) = 3.of(0)...;
method <<(num++;) {
n += 1
sum += num
sumofsquares += num**2
self
}
 
method stddev {
sqrt(sumofsquares/n - pow(sum/n, 2))
}
 
method to_s {
self.stddev.to_s
}
}
 
var i = 0
var sd = StdDevAccumulator()
[2,4,4,4,5,5,7,9].each {|n|
say "adding #{n}: stddev of #{i+=1} samples is #{sd << n}"
}</syntaxhighlight>
{{out}}
<pre>
adding 2: stddev of 1 samples is 0
adding 4: stddev of 2 samples is 1
adding 4: stddev of 3 samples is 0.942809041582063365867792482806465385713114583585
adding 4: stddev of 4 samples is 0.866025403784438646763723170752936183471402626905
adding 5: stddev of 5 samples is 0.979795897113271239278913629882356556786378992263
adding 5: stddev of 6 samples is 1
adding 7: stddev of 7 samples is 1.39970842444753034182701947126050936683768427466
adding 9: stddev of 8 samples is 2
</pre>
 
Using ''static'' variables:
<syntaxhighlight lang="ruby">func stddev(x) {
static(num=0, sum=0, sum2=0)
num++
sqrt(
(sum2 += x**2) / num -
(((sum += x) / num)**2)
);
}
 
 
%n(2 4 4 4 5 5 7 9).each { say stddev(_) };</langsyntaxhighlight>
{{out}}
<pre>
0
1
0.942809041582063365867792482806465385713114583585
0.9428090415820633658677924828064653857143
0.866025403784438646763723170752936183471402626905
0.8660254037844386467637231707529361834714
0.979795897113271239278913629882356556786378992263
0.9797958971132712392789136298823565567864
1
1.39970842444753034182701947126050936683768427466
1.399708424447530341827019471260509366836
2
</pre>
Line 2,990 ⟶ 4,118:
{{works with|GNU Smalltalk}}
 
<langsyntaxhighlight lang="smalltalk">Object subclass: SDAccum [
|sum sum2 num|
SDAccum class >> new [ |o|
Line 3,009 ⟶ 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,052 ⟶ 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,078 ⟶ 4,207:
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift">import Darwin
class stdDev{
Line 3,105 ⟶ 4,234:
}
var aa = stdDev()</langsyntaxhighlight>
{{out}}
<pre>
Line 3,120 ⟶ 4,249:
Functional:
 
<syntaxhighlight lang="swift">
<lang Swift>
func standardDeviation(arr : [Double]) -> Double
{
Line 3,133 ⟶ 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,171 ⟶ 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,177 ⟶ 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,196 ⟶ 4,324:
}
sd stop
puts "the standard deviation is: $sd"</langsyntaxhighlight>
 
[[Category:Stateful transactions]]
Line 3,210 ⟶ 4,338:
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vb">data = Array(2,4,4,4,5,5,7,9)
 
For i = 0 To UBound(data)
Line 3,230 ⟶ 4,358:
variance = variance/(n+1)
sd = FormatNumber(Sqr(variance),6)
End Function</langsyntaxhighlight>
 
{{Out}}
Line 3,248 ⟶ 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 3,297 ⟶ 4,425:
Debug.Print standardDeviation(x(L0))
Next
End Sub</langsyntaxhighlight>
 
{{out}}
Line 3,309 ⟶ 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 3,324 ⟶ 4,500:
];
CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 3,332 ⟶ 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,483

edits