Cumulative standard deviation: Difference between revisions
m
→{{header|Wren}}: Minor tidy
m (→{{header|Wren}}: Minor tidy) |
|||
(24 intermediate revisions by 15 users not shown) | |||
Line 24:
=={{header|11l}}==
{{trans|Python:_Callable_class}}
<
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))</
{{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.
<
STDDEV CSECT
USING STDDEV,R13
Line 155:
BUF DC CL80'N=1 ITEM=1 AVG=1.234 STDDEV=1.234 '
YREGS
END STDDEV</
{{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}}==
<
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>
{{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.
<
STDDEV = STRUCT(CHAR stddev),
MEAN = STRUCT(CHAR mean),
Line 276 ⟶ 338:
OD
)</
{{out}}
<pre>
Line 295 ⟶ 357:
A code sample in an object oriented style:
<
LONG REAL sum,
LONG REAL sum2,
Line 370 ⟶ 432:
)
</syntaxhighlight>
{{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:
<
INT n;
Line 404 ⟶ 466:
LONG REAL value = values[i];
printf(($2(xg(0,6))l$, value, sd(value)))
OD</
{{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.
<
long real sum, sum2;
Line 444 ⟶ 506:
end for_i
end.</
{{out}}
<pre>
Line 461 ⟶ 523:
Accumulation over a fold:
<
-- stdDevInc :: Accumulator -> Num -> Index -> Accumulator
Line 513 ⟶ 575:
end script
end if
end mReturn</
{{Out}}
<
0.979795897113, 1.0, 1.399708424448, 2.0}</
Or as a map-accumulation:
<
-- cumulativeStdDevns :: [Float] -> [Float]
Line 590 ⟶ 652:
end script
end if
end mReturn</
{{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}}==
<
for k, v in Data {
Line 610 ⟶ 691:
return sqrt((sum2/n) - (((sum*sum)/n)/n))
}</
{{out}}
<pre>
Line 624 ⟶ 705:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f STANDARD_DEVIATION.AWK
BEGIN {
Line 644 ⟶ 725:
return(sqrt(variance))
}
</syntaxhighlight>
{{out}}
<pre>
Line 659 ⟶ 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:<
TestDomain(T : Join(Field,RadicalCategory)): Exports == Implementation where
R ==> Record(n : Integer, sum : T, ssq : T)
Line 675 ⟶ 756:
sd obj ==
mean : T := obj.sum / (obj.n::T)
sqrt(obj.ssq / (obj.n::T) - mean*mean)</
D ==> TestDomain(T)
items := [2,4,4,4,5,5,7,9+x] :: List T;
Line 688 ⟶ 769:
(2) 2
Type: Expression(Integer)</
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
Uses the MOD(array()) and SUM(array()) functions.
<
FOR i% = 1 TO 8
READ n
Line 707 ⟶ 788:
i% += 1
list(i%) = n
= SQR(MOD(list())^2/i% - (SUM(list())/i%)^2)</
{{out}}
<pre>
Line 722 ⟶ 803:
=={{header|C}}==
<
#include <stdlib.h>
#include <math.h>
Line 769 ⟶ 850:
so->sum2 += v*v;
return stat_obj_value(so, so->action);
}</
<
int main()
Line 783 ⟶ 864:
FREE_STAT_OBJECT(so);
return 0;
}</
=={{header|C sharp|C#}}==
<
using System.Collections.Generic;
using System.Linq;
Line 810 ⟶ 891:
}
}
}</
<pre>0
1
Line 822 ⟶ 903:
=={{header|C++}}==
No attempt to handle different types -- standard deviation is intrinsically a real number.
<
#include <
#include <cmath>
#include <vector>
Line 862 ⟶ 943:
}
}
</syntaxhighlight>
=={{header|Clojure}}==
<
(defn stateful-std-deviation[x]
(letfn [(std-dev[x]
Line 876 ⟶ 957:
(intern *ns* 'v (atom [])))
(std-dev x)))
</syntaxhighlight>
=={{header|COBOL}}==
{{works with|OpenCOBOL|1.1}}
<
PROGRAM-ID. run-stddev.
environment division.
Line 952 ⟶ 1,033:
goback.
end program stddev.
</syntaxhighlight>
<
inp=002 stddev=+00000.0000
inp=004 stddev=+00001.0000
Line 962 ⟶ 1,043:
inp=007 stddev=+00001.3996
inp=009 stddev=+00002.0000
</syntaxhighlight>
=={{header|CoffeeScript}}==
Uses a class instance to maintain state.
<
class StandardDeviation
constructor: ->
Line 995 ⟶ 1,076:
"""
</syntaxhighlight>
{{out}}
Line 1,025 ⟶ 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:<
(let ((sum 0) (sq 0) (n 0))
(lambda (x)
Line 1,041 ⟶ 1,122:
5 1.0
7 1.3997085
9 2.0</
In the REPL, one step at a time:
<
#<Interpreted Closure (:INTERNAL RUNNING-STDDEV) @ #x21b9a492>
CL-USER> (funcall fn 2)
Line 1,062 ⟶ 1,143:
CL-USER> (funcall fn 9)
2.0
</syntaxhighlight>
=={{header|Component Pascal}}==
{{incorrect|Component Pascal|Function does not take numbers individually.}}
BlackBox Component Builder
<
MODULE StandardDeviation;
IMPORT StdLog, Args,Strings,Math;
Line 1,111 ⟶ 1,192:
END Do;
END StandardDeviation.
</syntaxhighlight>
Execute: ^Q StandardDeviation.Do 2 4 4 4 5 5 7 9 ~<br/>
{{out}}
Line 1,129 ⟶ 1,210:
Use an object to keep state.
{{trans|Ruby}}
<
def initialize
@n, @sum, @sum2 = 0, 0.0, 0.0
Line 1,144 ⟶ 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}" }</
{{out}}
<pre>
Line 1,159 ⟶ 1,240:
===Closure===
{{trans|Ruby}}
<
n, sum, sum2 = 0, 0.0, 0.0
->(num : Int32) do
Line 1,170 ⟶ 1,251:
sd = sdaccum
[2,4,4,4,5,5,7,9].each {|n| print sd.call(n), ", "}</
{{out}}
<pre>0.0, 1.0, 0.9428090415820634, 0.8660254037844386, 0.9797958971132712, 1.0, 1.3997084244475304, 2.0</pre>
=={{header|D}}==
<
struct StdDev {
Line 1,202 ⟶ 1,283:
writefln("%e", stdev.getStdDev());
}
}</
{{out}}
<pre>0.000000e+00
Line 1,224 ⟶ 1,305:
The algorithm is {{trans|Perl}} and the results were checked against [[#Python]].
<
var sum := 0.0
var sumSquares := 0.0
Line 1,247 ⟶ 1,328:
return [insert, stddev]
}</
<
# value: <insert>, <stddev>
Line 1,266 ⟶ 1,347:
1.0
1.3997084244475297
2.0</
=={{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}}
<
def add_sample( pid, n ), do: send( pid, {:add, n} )
Line 1,312 ⟶ 1,410:
end
Standard_deviation.task</
{{out}}
Line 1,328 ⟶ 1,426:
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">(defun running-std (items)
(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))
{{out}}
1.
0.942809
0.866025
0.979796
1.
1.399708
2.000000
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)
(let ((sum 0)
(dolist (i lst)
(setq i (float i))
Line 1,388 ⟶ 1,477:
(setq std 0)
(dolist (j tmp)
(setq std (/ std (length tmp)))
(setq std (sqrt std))
Line 1,394 ⟶ 1,483:
(let* ((test-data '(2 4 4 4 5 5 7 9))
(generator (std-dev-gen test-data)))
(dolist (i test-data)
(
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
-module( standard_deviation ).
Line 1,440 ⟶ 1,528:
loop_calculate_average( Ns ) -> lists:sum( Ns ) / erlang:length( Ns ).
</syntaxhighlight>
{{out}}
<pre>
Line 1,455 ⟶ 1,543:
=={{header|Factor}}==
<
sequences ;
IN: standard-deviator
Line 1,476 ⟶ 1,564:
{ 2 4 4 4 5 5 7 9 }
<standard-deviator> [ [ add-value ] curry each ] keep
current-std number>string print ;</
=={{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}}==
<
: st-count ( stats -- n ) f@ ;
Line 1,501 ⟶ 1,618:
fdup dup f+! float+
fdup f* f+!
std-stddev ;</
This variation is more numerically stable when there are large numbers of samples or large sample ranges.
<
: st-mean ( stats -- mean ) float+ f@ ;
: st-nvar ( stats -- n*var ) 2 floats + f@ ;
Line 1,521 ⟶ 1,638:
( delta x )
dup f@ f- f* float+ f+! \ update nvar
st-stddev ;</
Usage example:
<
2e stats st-add f. \ 0.
Line 1,533 ⟶ 1,650:
7e stats st-add f. \ 1.39970842444753
9e stats st-add f. \ 2.
</syntaxhighlight>
=={{header|Fortran}}==
{{works with|Fortran|2003 and later}}
<
program standard_deviation
implicit none
Line 1,587 ⟶ 1,704:
end function stddev
end program standard_deviation
</syntaxhighlight>
{{out}}
<pre>
Line 1,608 ⟶ 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">
REAL FUNCTION STDDEV(X) !Standard deviation for successive values.
REAL X !The latest value.
Line 1,683 ⟶ 1,800:
END DO !On to the next value.
END
</syntaxhighlight>
Output: the second pair of columns have the calculations done with a working mean and thus accumulate deviations from that.
Line 1,762 ⟶ 1,879:
=={{header|FreeBASIC}}==
<
Function calcStandardDeviation(number As Double) As Double
Line 1,791 ⟶ 1,908:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 1,809 ⟶ 1,926:
State maintained with a closure.
<
import (
Line 1,831 ⟶ 1,948:
fmt.Println(r(x))
}
}</
{{out}}
<pre>
Line 1,846 ⟶ 1,963:
=={{header|Groovy}}==
Solution:
<
def stdDev = { def sample ->
Line 1,858 ⟶ 1,975:
[2,4,4,4,5,5,7,9].each {
println "${stdDev(it)}"
}</
{{out}}
Line 1,874 ⟶ 1,991:
We store the state in the <code>ST</code> monad using an <code>STRef</code>.
<
import Data.List (foldl') -- '
Line 1,901 ⟶ 2,018:
main = mapM_ print $ runST $
mkSD >>= forM [2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0]</
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
where
go (s, q) (i, x) =
let _s = s + x
_q = q + (x ^ 2)
in ((_s, _q), sqrt
--------------------------- TEST -------------------------
main :: IO ()
main = mapM_ print $ cumulativeStdDevns [2, 4, 4, 4, 5, 5, 7, 9]</
{{Out}}
<pre>0.0
Line 1,934 ⟶ 2,052:
=={{header|Haxe}}==
<
class Main {
Line 1,956 ⟶ 2,074:
return Math.sqrt(average(store));
}
}</
<pre>0
1
Line 1,967 ⟶ 2,085:
=={{header|HicEst}}==
<
set = (2,4,4,4,5,5,7,9)
Line 1,982 ⟶ 2,100:
sum2 = sum2 + x*x
stdev = ( sum2/k - (sum/k)^2) ^ 0.5
END</
<pre>Adding 2 stdev = 0
Adding 4 stdev = 1
Line 1,993 ⟶ 2,111:
=={{header|Icon}} and {{header|Unicon}}==
<
stddev() # reset state / empty
Line 2,014 ⟶ 2,132:
return sqrt( (sum2X / *X) - (sumX / *X)^2 )
}
end</
{{out}}
<pre>stddev (so far) := 0.0
Line 2,026 ⟶ 2,144:
=={{header|IS-BASIC}}==
<
110 LET N=8
120 NUMERIC ARR(1 TO N)
Line 2,042 ⟶ 2,160:
240 PRINT J;"item =";ARR(J),"standard dev =";STDEV(J)
250 NEXT
260 DATA 2,4,4,4,5,5,7,9</
=={{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.
<
dev=: - mean
stddevP=: [: %:@mean *:@dev NB. A) 3 equivalent defs for stddevP
Line 2,055 ⟶ 2,173:
stddevP\ 2 4 4 4 5 5 7 9
0 1 0.942809 0.866025 0.979796 1 1.39971 2</
'''Alternatives:'''<br>
Using verbose names for J primitives.
<
sqrt =: %:
sum =: +/
Line 2,069 ⟶ 2,187:
stddevP\ 2 4 4 4 5 5 7 9
0 1 0.942809 0.866025 0.979796 1 1.39971 2</
{{trans|R}}<BR>
Or we could take a cue from the [[#R|R implementation]] and reverse the Bessel correction to stddev:
<
(%:@:(%~<:)@:# * stddev)\ 2 4 4 4 5 5 7 9
0 1 0.942809 0.866025 0.979796 1 1.39971 2</
=={{header|Java}}==
<
int n = 0;
double sum = 0;
Line 2,100 ⟶ 2,218:
}
}
}</
=={{header|JavaScript}}==
Line 2,107 ⟶ 2,225:
Uses a closure.
<
var n = 0;
var sum = 0.0;
Line 2,126 ⟶ 2,244:
// using WSH
WScript.Echo(stddev.join(', ');</
{{out}}
<pre>0, 1, 0.942809041582063, 0.866025403784439, 0.979795897113273, 1, 1.39970842444753, 2</pre>
===Functional
====ES5====
Accumulating across a fold
<
return xs.reduce(function (a, x, i) {
Line 2,156 ⟶ 2,274:
}).stages
})([2, 4, 4, 4, 5, 5, 7, 9]);</
{{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 2,178 ⟶ 2,366:
where SSD is the sum of squared deviations about the mean.
<
# seen so far, given the current state as input:
def standard_deviation: .ssd / .n | sqrt;
Line 2,203 ⟶ 2,391:
# Begin:
simulate</
'''Example 1'''
# observations.txt
Line 2,215 ⟶ 2,403:
9
{{Out}}
<syntaxhighlight lang="sh">
$ jq -s -f Dynamic_standard_deviation.jq observations.txt
0
Line 2,225 ⟶ 2,413:
1.3997084244475302
1.9999999999999998
</syntaxhighlight>
====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.
<
def simulate(stream):
foreach stream as $observation
(initial_state;
update_state($observation);
standard_deviation);</
'''Example 2''':
simulate( range(0;10) )
Line 2,252 ⟶ 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.
<
# jq is assumed to be on PATH
Line 2,289 ⟶ 2,477:
sed -n 1p <<< "$result"
state=$(sed -n 2p <<< "$result")
done</
'''Example 3'''
<
Next observation: 10
0
Line 2,298 ⟶ 2,486:
Next observation: 0
8.16496580927726
</syntaxhighlight>
=={{header|Julia}}==
Use a closure to create a running standard deviation function.
<
∑x = ∑x² = zero(T)
n = 0
Line 2,321 ⟶ 2,509:
for i in test
println(" - add $i → ", rstd(i))
end</
{{out}}
Line 2,338 ⟶ 2,526:
{{trans|Java}}
Using a class to keep the running sum, sum of squares and number of elements added so far:
<
class CumStdDev {
Line 2,357 ⟶ 2,545:
val csd = CumStdDev()
for (d in testData) println("Add $d => ${csd.sd(d)}")
}</
{{out}}
Line 2,373 ⟶ 2,561:
=={{header|Liberty BASIC}}==
Using a global array to maintain the state. Implements definition explicitly.
<syntaxhighlight 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,400 ⟶ 2,588:
Data 2, 4, 4, 4, 5, 5, 7, 9
</syntaxhighlight>
<pre>
New data 2 so S.D. now = 0.000000
Line 2,413 ⟶ 2,601:
=={{header|Lobster}}==
<syntaxhighlight lang="lobster">
// Stats computes a running mean and variance
// See Knuth TAOCP vol 2, 3rd edition, page 232
Line 2,442 ⟶ 2,630:
test_stdv()
</syntaxhighlight>
{{out}}
<pre>
Line 2,450 ⟶ 2,638:
=={{header|Lua}}==
Uses a closure. Translation of JavaScript.
<
local sum, sumsq, k = 0,0,0
return function(n)
Line 2,461 ⟶ 2,649:
for i, v in ipairs{2,4,4,4,5,5,7,9} do
print(ldev(v))
end</
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
=={{header|MATLAB}} / {{header|Octave}}==
The simple form is, computing only the standand deviation of the whole data set:
<
n = length (x);
Line 2,476 ⟶ 2,663:
x2 = mean (x .* x);
dev= sqrt (x2 - m * m)
dev = 2 </
When the intermediate results are also needed, one can use this vectorized form:
<
x2= cumsum(x.^2) ./ [1:n]; % running squares
Line 2,487 ⟶ 2,674:
0.00000 1.00000 0.94281 0.86603 0.97980 1.00000 1.39971 2.00000
</syntaxhighlight>
Here is a vectorized one line solution as a function
<syntaxhighlight lang="matlab">
function stdDevEval(n)
disp(sqrt(sum((n-sum(n)/length(n)).^2)/length(n)));
end
</syntaxhighlight>
=={{header|MiniScript}}==
<
StdDeviator.count = 0
StdDeviator.sum = 0
Line 2,517 ⟶ 2,704:
sd.add x
end for
print sd.stddev</
{{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</
Instruction: В/О С/П ''number'' С/П ''number'' С/П ...
Line 2,530 ⟶ 2,717:
=={{header|Nanoquery}}==
{{trans|Java}}
<
declare n
declare sum
Line 2,555 ⟶ 2,742:
for x in testData
println sd.sd(x)
end</
{{out}}
Line 2,570 ⟶ 2,757:
===Using global variables===
<
var sdSum, sdSum2, sdN = 0.0
Line 2,581 ⟶ 2,768:
for value in [float 2,4,4,4,5,5,7,9]:
echo value, " ", formatFloat(sd(value), precision = -1)</
{{out}}
Line 2,594 ⟶ 2,781:
===Using an accumulator object===
<
type SDAccum = object
Line 2,609 ⟶ 2,796:
for value in [float 2, 4, 4, 4, 5, 5, 7, 9]:
echo value, " ", formatFloat(accum.add(value), precision = -1)</
{{out}}
Line 2,615 ⟶ 2,802:
===Using a closure===
<
func accumBuilder(): auto =
Line 2,629 ⟶ 2,816:
for value in [float 2, 4, 4, 4, 5, 5, 7, 9]:
echo value, " ", formatFloat(std(value), precision = -1)</
{{out}}
Line 2,636 ⟶ 2,823:
=={{header|Objeck}}==
{{trans|Java}}
<
use Structure;
Line 2,672 ⟶ 2,859:
}
}
</syntaxhighlight>
=={{header|Objective-C}}==
<
@interface SDAccum : NSObject
Line 2,729 ⟶ 2,916:
}
return 0;
}</
===Blocks===
Line 2,735 ⟶ 2,922:
{{works with|iOS|4+}}
<
typedef double (^Func)(double); // a block that takes a double and returns a double
Line 2,764 ⟶ 2,951:
}
return 0;
}</
=={{header|OCaml}}==
<
let stddev l =
Line 2,781 ⟶ 2,968:
Printf.printf "List: ";
List.iter (Printf.printf "%g ") l;
Printf.printf "\nStandard deviation: %g\n" (stddev l)</
{{out}}
Line 2,795 ⟶ 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.
<
: stddev(x)
| l |
StdValues receive x + dup ->l StdValues send drop
#qs l map sum l size asFloat / l avg sq - sqrt ;</
{{out}}
Line 2,819 ⟶ 3,006:
=={{header|ooRexx}}==
{{works with|oorexx}}
<
x = .array~of(2,4,4,4,5,5,7,9)
sd = 0
Line 2,860 ⟶ 3,047:
ans = ( prev + ( n / prev ) ) / 2
end
return ans</
{{out}}
<pre>#1 value = 2 stdev = 0
Line 2,873 ⟶ 3,060:
=={{header|PARI/GP}}==
Uses the Cramer-Young updating algorithm. For demonstration it displays the mean and variance at each step.
<
myT=x;
myS=0;
Line 2,891 ⟶ 3,078:
print("Standard deviation: ",sqrt(myS/myN))
};
addpoints([2,4,4,4,5,5,7,9])</
=={{header|Pascal}}==
===Std.Pascal===
{{trans|AWK}}
<
uses math;
const
Line 2,923 ⟶ 3,110:
writeln(i,' item=',arr[i]:2:0,' stddev=',stddev(i):18:15)
end
end.</
{{out}}
<pre>1 item= 2 stddev= 0.000000000000000
Line 2,934 ⟶ 3,121:
8 item= 9 stddev= 2.000000000000000</pre>
==={{header|Delphi}}===
<
{$APPTYPE CONSOLE}
Line 2,964 ⟶ 3,151:
end;
Readln;
end. </
{{out}}
<pre>
Line 2,978 ⟶ 3,165:
=={{header|Perl}}==
<
package SDAccum;
sub new {
Line 3,014 ⟶ 3,201:
return $self->stddev;
}
}</
<
my $sd;
Line 3,022 ⟶ 3,209:
$sd = $sdacc->value($v);
}
print "std dev = $sd\n";</
A much shorter version using a closure and a property of the variance:
<
{
my $num, $sum, $sum2;
Line 3,039 ⟶ 3,226:
}
print stddev($_), "\n" for qw(2 4 4 4 5 5 7 9);</
{{out}}
Line 3,052 ⟶ 3,239:
one-liner:
<
small script:
<
$d=new Math::StdDev;
foreach my $v ( 2,4,4,4,5,5,7,9 ) {
$d->Update($v);
print $d->variance(),"\n"
}</
{{out}}
Line 3,075 ⟶ 3,262:
=={{header|Phix}}==
demo\rosetta\Standard_deviation.exw contains a copy of this code and a version that could be the basis for a library version that can handle multiple active data sets concurrently.
<!--<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>
Line 3,113 ⟶ 3,304:
=={{header|PHP}}==
This is just straight PHP class usage, respecting the specifications "stateful" and "one at a time":
<
class sdcalc {
private $cnt, $sumup, $square;
Line 3,143 ⟶ 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);
}</
This will produce the output:
Line 3,158 ⟶ 3,349:
=={{header|PicoLisp}}==
<
(de stdDev ()
Line 3,175 ⟶ 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)) ) )</
{{out}}
<pre>2.00 -> 0.00
Line 3,187 ⟶ 3,378:
=={{header|PL/I}}==
<
stddev: proc options(main);
declare a(10) float init(1,2,3,4,5,6,7,8,9,10);
Line 3,211 ⟶ 3,402:
end std_dev;
end;</
{{out}}
<pre>AVERAGE= 5.50000E+0000;
Line 3,219 ⟶ 3,410:
This implementation takes the form of an advanced function
which can act like a cmdlet and receive input from the pipeline.
<
begin {
$avg = 0
Line 3,231 ⟶ 3,422:
[Math]::Sqrt($sum / $nums.Length)
}
}</
Usage as follows:
<pre>PS> 2,4,4,4,5,5,7,9 | Get-StandardDeviation
Line 3,244 ⟶ 3,435:
=={{header|PureBasic}}==
<
Declare.d Standard_deviation(x)
Line 3,272 ⟶ 3,463:
MyList:
Data.i 2,4,4,4,5,5,7,9
EndDataSection</
{{out}}
Line 3,290 ⟶ 3,481:
The program should work with Python 2.x and 3.x,
although the output would not be a tuple in 3.x
<
>>> def sd(x):
sd.sum += x
Line 3,311 ⟶ 3,502:
(7, 1.3997084244475311)
(9, 2.0)
>>></
===Python: Using a class instance===
<
def __init__(self):
self.sum, self.sum2, self.n = (0,0,0)
Line 3,326 ⟶ 3,517:
>>> sd_inst = SD()
>>> for value in (2,4,4,4,5,5,7,9):
print (value, sd_inst.sd(value))</
====Python: Callable class====
Line 3,333 ⟶ 3,524:
===Python: Using a Closure===
{{Works with|Python|3.x}}
<
>>> def sdcreator():
sum = sum2 = n = 0
Line 3,357 ⟶ 3,548:
5 1.0
7 1.39970842445
9 2.0</
===Python: Using an extended generator===
{{Works with|Python|2.5+}}
<
>>> def sdcreator():
sum = sum2 = n = 0
Line 3,384 ⟶ 3,575:
5 1.0
7 1.39970842445
9 2.0</
===Python: In a couple of 'functional' lines===
<
>>> 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>
=={{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) {
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}}==
<
#lang racket
(require math)
Line 3,478 ⟶ 3,636:
;; run it on each number, return the last result
(last (map running-stddev '(2 4 4 4 5 5 7 9)))
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
Using a closure:
<syntaxhighlight lang="raku"
my $mean = @a R/ [+] @a;
sqrt @a R/ [+] map (* - $mean)
}
Line 3,495 ⟶ 3,653:
my &f = sdaccum;
say f $_ for 2, 4, 4, 4, 5, 5, 7, 9;</
Using a state variable (remember that <tt><(x-<x>)²> = <x²> - <x>²</tt>):
<syntaxhighlight lang="raku" line>sub stddev($x) {
sqrt
( .[2] += $x
given state @;
}
say .&stddev
{{out}}
Line 3,521 ⟶ 3,678:
These REXX versions use ''running sums''.
===show running sums===
<
parse arg # /*obtain optional arguments from the CL*/
if #='' then #= 2 4 4 4 5 5 7 9 /*None specified? Then use the default*/
Line 3,539 ⟶ 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</
{{out|output|text= when using the default input of: <tt> 2 4 4 4 5 5 7 9 </tt>}}
<pre>
Line 3,554 ⟶ 3,711:
===only show standard deviation===
<
parse arg # /*obtain optional arguments from the CL*/
if #='' then #= 2 4 4 4 5 5 7 9 /*None specified? Then use the default*/
Line 3,570 ⟶ 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</
{{out|output|text= when using the default input of: <tt> 2 4 4 4 5 5 7 9 </tt>}}
<pre>
Line 3,577 ⟶ 3,734:
=={{header|Ring}}==
<
# Project : Cumulative standard deviation
Line 3,595 ⟶ 3,752:
see "" + num + " value in = " + stddata + " Stand Dev = " + standdev + nl
next
</syntaxhighlight>
Output:
<pre>
Line 3,606 ⟶ 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,614 ⟶ 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]].
<
def initialize
@n, @sum, @sumofsquares = 0, 0.0, 0.0
Line 3,638 ⟶ 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}" }</
<pre>adding 2: stddev of 1 samples is 0.0
Line 3,650 ⟶ 3,827:
=== Closure ===
<
n, sum, sum2 = 0, 0.0, 0.0
lambda do |num|
Line 3,661 ⟶ 3,838:
sd = sdaccum
[2,4,4,4,5,5,7,9].each {|n| print sd.call(n), ", "}</
<pre>0.0, 1.0, 0.942809041582063, 0.866025403784439, 0.979795897113272, 1.0, 1.39970842444753, 2.0, </pre>
=={{header|Run BASIC}}==
<
'holds (space-separated) number of data , sum of values and sum of squares
sd$ = "2,4,4,4,5,5,7,9"
Line 3,681 ⟶ 3,858:
print num;" value in = ";stdData; " Stand Dev = "; using("###.######", standDev)
next num</
<pre>1 value in = 2 Stand Dev = 0.000000
2 value in = 4 Stand Dev = 1.000000
Line 3,694 ⟶ 3,871:
Using a struct:
{{trans|Java}}
<
n: f64,
sum: f64,
Line 3,725 ⟶ 3,902:
println!("{}", cum_stdev.push(*num as f64));
}
}</
{{out}}
<pre>
Line 3,739 ⟶ 3,916:
Using a closure:
<
let mut n = 0.0;
let mut sum = 0.0;
Line 3,758 ⟶ 3,935:
println!("{}", sd_acc(*num as f64));
}
}</
{{out}}
<pre>
Line 3,772 ⟶ 3,949:
=={{header|SAS}}==
<syntaxhighlight lang="sas">
*--Load the test data;
data test1;
Line 3,805 ⟶ 3,982:
var n sd /*mean*/;
run;
</syntaxhighlight>
{{out}}
Line 3,824 ⟶ 4,001:
===Generic for any numeric type===
{{libheader|Scala}}
<
object StddevCalc extends App {
Line 3,849 ⟶ 4,026:
println(s"Successfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart}ms]")
}</
=={{header|Scheme}}==
<
(define (standart-deviation-generator)
(let ((nums '()))
Line 3,864 ⟶ 4,041:
(let loop ((f (standart-deviation-generator))
(input '(2 4 4 4 5 5 7 9)))
(
(display (f (car input)))
(newline)
(loop f (cdr input
</syntaxhighlight>
=={{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))</
{{out}}
<pre>-->T=[2,4,4,4,5,5,7,9];
Line 3,882 ⟶ 4,058:
=={{header|Sidef}}==
Using an object to keep state:
<
method <<(num) {
n += 1
Line 3,903 ⟶ 4,079:
[2,4,4,4,5,5,7,9].each {|n|
say "adding #{n}: stddev of #{i+=1} samples is #{sd << n}"
}</
{{out}}
<pre>
Line 3,917 ⟶ 4,093:
Using ''static'' variables:
<
static(num=0, sum=0, sum2=0)
num++
Line 3,926 ⟶ 4,102:
}
%n(2 4 4 4 5 5 7 9).each { say stddev(_) }</
{{out}}
<pre>
Line 3,942 ⟶ 4,118:
{{works with|GNU Smalltalk}}
<
|sum sum2 num|
SDAccum class >> new [ |o|
Line 3,961 ⟶ 4,137:
]
stddev [ ^ (self variance) sqrt ]
].</
<
sdacc := SDAccum new.
#( 2 4 4 4 5 5 7 9 ) do: [ :v | sd := sdacc value: v ].
('std dev = %1' % { sd }) displayNl.</
=={{header|SQL}}==
{{works with|Postgresql}}
<
create table if not exists teststd (n double precision not null);
Line 4,005 ⟶ 4,181:
-- cleanup test data
delete from teststd;
</syntaxhighlight>
With a command like '''psql <rosetta-std-dev.sql''' you will get an output like this: (duplicate lines generously deleted, locale is DE)
<pre>
Line 4,031 ⟶ 4,207:
=={{header|Swift}}==
<
class stdDev{
Line 4,058 ⟶ 4,234:
}
var aa = stdDev()</
{{out}}
<pre>
Line 4,073 ⟶ 4,249:
Functional:
<syntaxhighlight lang="swift">
func standardDeviation(arr : [Double]) -> Double
{
Line 4,086 ⟶ 4,262:
standardDeviation(responseTimes) // 20.8742514835862
standardDeviation([2,4,4,4,5,5,7,9]) // 2.0
</syntaxhighlight>
=={{header|Tcl}}==
===With a Class===
{{works with|Tcl|8.6}} or {{libheader|TclOO}}
<
variable sum sum2 num
constructor {} {
Line 4,123 ⟶ 4,299:
set sd [$sdacc value $val]
}
puts "the standard deviation is: $sd"</
{{out}}
<pre>the standard deviation is: 2.0</pre>
Line 4,129 ⟶ 4,305:
===With a Coroutine===
{{works with|Tcl|8.6}}
<
coroutine sd apply {{} {
set sum 0.0
Line 4,148 ⟶ 4,324:
}
sd stop
puts "the standard deviation is: $sd"</
[[Category:Stateful transactions]]
Line 4,162 ⟶ 4,338:
=={{header|VBScript}}==
<
For i = 0 To UBound(data)
Line 4,182 ⟶ 4,358:
variance = variance/(n+1)
sd = FormatNumber(Sqr(variance),6)
End Function</
{{Out}}
Line 4,200 ⟶ 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.
<
'treats non-numeric strings as zero
Dim L0 As Variant, total As Variant
Line 4,249 ⟶ 4,425:
Debug.Print standardDeviation(x(L0))
Next
End Sub</
{{out}}
Line 4,266 ⟶ 4,442:
{{libheader|Wren-fmt}}
{{libheader|Wren-math}}
<
import "./math" for Nums
var cumStdDev = Fiber.new { |a|
Line 4,281 ⟶ 4,457:
var sd = cumStdDev.call(a)
if (cumStdDev.isDone) return
}</
{{out}}
Line 4,312 ⟶ 4,488:
=={{header|XPL0}}==
<
int A, I;
real N, S, S2;
Line 4,324 ⟶ 4,500:
];
CrLf(0);
]</
{{out}}
Line 4,332 ⟶ 4,508:
=={{header|zkl}}==
<
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())
}</
{{out}}
<pre>
|