Cumulative standard deviation: Difference between revisions
Content added Content deleted
m (→{{header|R}}) |
Thundergnat (talk | contribs) m (sntax highlighting fixup automation) |
||
Line 24: | Line 24: | ||
=={{header|11l}}== |
=={{header|11l}}== |
||
{{trans|Python:_Callable_class}} |
{{trans|Python:_Callable_class}} |
||
< |
<syntaxhighlight lang="11l">T SD |
||
sum = 0.0 |
sum = 0.0 |
||
sum2 = 0.0 |
sum2 = 0.0 |
||
Line 37: | Line 37: | ||
V sd_inst = SD() |
V sd_inst = SD() |
||
L(value) [2, 4, 4, 4, 5, 5, 7, 9] |
L(value) [2, 4, 4, 4, 5, 5, 7, 9] |
||
print(value‘ ’sd_inst(value))</ |
print(value‘ ’sd_inst(value))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 54: | Line 54: | ||
For maximum compatibility, this program uses only the basic instruction set. |
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. |
Part of the code length is due to the square root algorithm and to the nice output. |
||
< |
<syntaxhighlight lang="360asm">******** Standard deviation of a population |
||
STDDEV CSECT |
STDDEV CSECT |
||
USING STDDEV,R13 |
USING STDDEV,R13 |
||
Line 155: | Line 155: | ||
BUF DC CL80'N=1 ITEM=1 AVG=1.234 STDDEV=1.234 ' |
BUF DC CL80'N=1 ITEM=1 AVG=1.234 STDDEV=1.234 ' |
||
YREGS |
YREGS |
||
END STDDEV</ |
END STDDEV</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>N=1 ITEM=2 AVG=2.000 STDDEV=0.000 |
<pre>N=1 ITEM=2 AVG=2.000 STDDEV=0.000 |
||
Line 169: | Line 169: | ||
{{libheader|Action! Tool Kit}} |
{{libheader|Action! Tool Kit}} |
||
{{libheader|Action! Real Math}} |
{{libheader|Action! Real Math}} |
||
< |
<syntaxhighlight lang="action!">INCLUDE "H6:REALMATH.ACT" |
||
REAL sum,sum2 |
REAL sum,sum2 |
||
Line 214: | Line 214: | ||
Print(" sd=") PrintRE(sd) |
Print(" sd=") PrintRE(sd) |
||
OD |
OD |
||
RETURN</ |
RETURN</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Cumulative_standard_deviation.png Screenshot from Atari 8-bit computer] |
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Cumulative_standard_deviation.png Screenshot from Atari 8-bit computer] |
||
Line 229: | Line 229: | ||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
< |
<syntaxhighlight lang="ada"> |
||
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; |
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; |
||
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; |
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; |
||
Line 265: | Line 265: | ||
end loop; |
end loop; |
||
end Test_Deviation; |
end Test_Deviation; |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 287: | Line 287: | ||
<!-- {{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8.8d.fc9.i386]}} --> |
<!-- {{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. |
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. |
||
< |
<syntaxhighlight lang="algol68">MODE VALUE = STRUCT(CHAR value), |
||
STDDEV = STRUCT(CHAR stddev), |
STDDEV = STRUCT(CHAR stddev), |
||
MEAN = STRUCT(CHAR mean), |
MEAN = STRUCT(CHAR mean), |
||
Line 338: | Line 338: | ||
OD |
OD |
||
)</ |
)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 357: | Line 357: | ||
A code sample in an object oriented style: |
A code sample in an object oriented style: |
||
< |
<syntaxhighlight lang="algol68">MODE STAT = STRUCT( |
||
LONG REAL sum, |
LONG REAL sum, |
||
LONG REAL sum2, |
LONG REAL sum2, |
||
Line 432: | Line 432: | ||
) |
) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 451: | Line 451: | ||
A simple - but "unpackaged" - code example, useful if the standard deviation is required on only one set of concurrent data: |
A simple - but "unpackaged" - code example, useful if the standard deviation is required on only one set of concurrent data: |
||
< |
<syntaxhighlight lang="algol68">LONG REAL sum, sum2; |
||
INT n; |
INT n; |
||
Line 466: | Line 466: | ||
LONG REAL value = values[i]; |
LONG REAL value = values[i]; |
||
printf(($2(xg(0,6))l$, value, sd(value))) |
printf(($2(xg(0,6))l$, value, sd(value))) |
||
OD</ |
OD</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 482: | Line 482: | ||
{{Trans|ALGOL 68}} |
{{Trans|ALGOL 68}} |
||
This is an Algol W version of the third, "unpackaged" Algol 68 sample, which was itself translated from Python. |
This is an Algol W version of the third, "unpackaged" Algol 68 sample, which was itself translated from Python. |
||
< |
<syntaxhighlight lang="algolw">begin |
||
long real sum, sum2; |
long real sum, sum2; |
||
Line 506: | Line 506: | ||
end for_i |
end for_i |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 523: | Line 523: | ||
Accumulation over a fold: |
Accumulation over a fold: |
||
< |
<syntaxhighlight lang="applescript">-------------- CUMULATIVE STANDARD DEVIATION ------------- |
||
-- stdDevInc :: Accumulator -> Num -> Index -> Accumulator |
-- stdDevInc :: Accumulator -> Num -> Index -> Accumulator |
||
Line 575: | Line 575: | ||
end script |
end script |
||
end if |
end if |
||
end mReturn</ |
end mReturn</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
< |
<syntaxhighlight lang="applescrip">{0.0, 1.0, 0.942809041582, 0.866025403784, |
||
0.979795897113, 1.0, 1.399708424448, 2.0}</ |
0.979795897113, 1.0, 1.399708424448, 2.0}</syntaxhighlight> |
||
Or as a map-accumulation: |
Or as a map-accumulation: |
||
< |
<syntaxhighlight lang="applescript">-------------- CUMULATIVE STANDARD DEVIATION ------------- |
||
-- cumulativeStdDevns :: [Float] -> [Float] |
-- cumulativeStdDevns :: [Float] -> [Float] |
||
Line 652: | Line 652: | ||
end script |
end script |
||
end if |
end if |
||
end mReturn</ |
end mReturn</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 659: | Line 659: | ||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang="rebol">arr: new [] |
||
loop [2 4 4 4 5 5 7 9] 'value [ |
loop [2 4 4 4 5 5 7 9] 'value [ |
||
'arr ++ value |
'arr ++ value |
||
print [value "->" deviation arr] |
print [value "->" deviation arr] |
||
]</ |
]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 677: | Line 677: | ||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
< |
<syntaxhighlight lang="autohotkey">Data := [2,4,4,4,5,5,7,9] |
||
for k, v in Data { |
for k, v in Data { |
||
Line 691: | Line 691: | ||
return sqrt((sum2/n) - (((sum*sum)/n)/n)) |
return sqrt((sum2/n) - (((sum*sum)/n)/n)) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 705: | Line 705: | ||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
<syntaxhighlight lang="awk"> |
|||
<lang AWK> |
|||
# syntax: GAWK -f STANDARD_DEVIATION.AWK |
# syntax: GAWK -f STANDARD_DEVIATION.AWK |
||
BEGIN { |
BEGIN { |
||
Line 725: | Line 725: | ||
return(sqrt(variance)) |
return(sqrt(variance)) |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 740: | Line 740: | ||
=={{header|Axiom}}== |
=={{header|Axiom}}== |
||
{{incorrect|Axiom|It does not return the ''running'' standard deviation of the series.}} |
{{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:< |
We implement a domain with dependent type T with the operation + and identity 0:<syntaxhighlight lang="axiom">)abbrev package TESTD TestDomain |
||
TestDomain(T : Join(Field,RadicalCategory)): Exports == Implementation where |
TestDomain(T : Join(Field,RadicalCategory)): Exports == Implementation where |
||
R ==> Record(n : Integer, sum : T, ssq : T) |
R ==> Record(n : Integer, sum : T, ssq : T) |
||
Line 756: | Line 756: | ||
sd obj == |
sd obj == |
||
mean : T := obj.sum / (obj.n::T) |
mean : T := obj.sum / (obj.n::T) |
||
sqrt(obj.ssq / (obj.n::T) - mean*mean)</ |
sqrt(obj.ssq / (obj.n::T) - mean*mean)</syntaxhighlight>This can be called using:<syntaxhighlight lang="axiom">T ==> Expression Integer |
||
D ==> TestDomain(T) |
D ==> TestDomain(T) |
||
items := [2,4,4,4,5,5,7,9+x] :: List T; |
items := [2,4,4,4,5,5,7,9+x] :: List T; |
||
Line 769: | Line 769: | ||
(2) 2 |
(2) 2 |
||
Type: Expression(Integer)</ |
Type: Expression(Integer)</syntaxhighlight> |
||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
{{works with|BBC BASIC for Windows}} |
{{works with|BBC BASIC for Windows}} |
||
Uses the MOD(array()) and SUM(array()) functions. |
Uses the MOD(array()) and SUM(array()) functions. |
||
< |
<syntaxhighlight lang="bbcbasic"> MAXITEMS = 100 |
||
FOR i% = 1 TO 8 |
FOR i% = 1 TO 8 |
||
READ n |
READ n |
||
Line 788: | Line 788: | ||
i% += 1 |
i% += 1 |
||
list(i%) = n |
list(i%) = n |
||
= SQR(MOD(list())^2/i% - (SUM(list())/i%)^2)</ |
= SQR(MOD(list())^2/i% - (SUM(list())/i%)^2)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 803: | Line 803: | ||
=={{header|C}}== |
=={{header|C}}== |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
#include <stdlib.h> |
#include <stdlib.h> |
||
#include <math.h> |
#include <math.h> |
||
Line 850: | Line 850: | ||
so->sum2 += v*v; |
so->sum2 += v*v; |
||
return stat_obj_value(so, so->action); |
return stat_obj_value(so, so->action); |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="c">double v[] = { 2,4,4,4,5,5,7,9 }; |
||
int main() |
int main() |
||
Line 864: | Line 864: | ||
FREE_STAT_OBJECT(so); |
FREE_STAT_OBJECT(so); |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
using System.Collections.Generic; |
using System.Collections.Generic; |
||
using System.Linq; |
using System.Linq; |
||
Line 891: | Line 891: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
<pre>0 |
<pre>0 |
||
1 |
1 |
||
Line 903: | Line 903: | ||
=={{header|C++}}== |
=={{header|C++}}== |
||
No attempt to handle different types -- standard deviation is intrinsically a real number. |
No attempt to handle different types -- standard deviation is intrinsically a real number. |
||
< |
<syntaxhighlight lang="cpp"> |
||
#include <assert.h> |
#include <assert.h> |
||
#include <cmath> |
#include <cmath> |
||
Line 943: | Line 943: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<syntaxhighlight lang="lisp"> |
||
(defn stateful-std-deviation[x] |
(defn stateful-std-deviation[x] |
||
(letfn [(std-dev[x] |
(letfn [(std-dev[x] |
||
Line 957: | Line 957: | ||
(intern *ns* 'v (atom []))) |
(intern *ns* 'v (atom []))) |
||
(std-dev x))) |
(std-dev x))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|COBOL}}== |
=={{header|COBOL}}== |
||
{{works with|OpenCOBOL|1.1}} |
{{works with|OpenCOBOL|1.1}} |
||
< |
<syntaxhighlight lang="cobol">IDENTIFICATION DIVISION. |
||
PROGRAM-ID. run-stddev. |
PROGRAM-ID. run-stddev. |
||
environment division. |
environment division. |
||
Line 1,033: | Line 1,033: | ||
goback. |
goback. |
||
end program stddev. |
end program stddev. |
||
</syntaxhighlight> |
|||
</lang> |
|||
< |
<syntaxhighlight lang="cobol">sample output: |
||
inp=002 stddev=+00000.0000 |
inp=002 stddev=+00000.0000 |
||
inp=004 stddev=+00001.0000 |
inp=004 stddev=+00001.0000 |
||
Line 1,043: | Line 1,043: | ||
inp=007 stddev=+00001.3996 |
inp=007 stddev=+00001.3996 |
||
inp=009 stddev=+00002.0000 |
inp=009 stddev=+00002.0000 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|CoffeeScript}}== |
=={{header|CoffeeScript}}== |
||
Uses a class instance to maintain state. |
Uses a class instance to maintain state. |
||
< |
<syntaxhighlight lang="coffeescript"> |
||
class StandardDeviation |
class StandardDeviation |
||
constructor: -> |
constructor: -> |
||
Line 1,076: | Line 1,076: | ||
""" |
""" |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 1,106: | Line 1,106: | ||
=={{header|Common Lisp}}== |
=={{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:< |
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:<syntaxhighlight lang="lisp">(defun running-stddev () |
||
(let ((sum 0) (sq 0) (n 0)) |
(let ((sum 0) (sq 0) (n 0)) |
||
(lambda (x) |
(lambda (x) |
||
Line 1,122: | Line 1,122: | ||
5 1.0 |
5 1.0 |
||
7 1.3997085 |
7 1.3997085 |
||
9 2.0</ |
9 2.0</syntaxhighlight> |
||
In the REPL, one step at a time: |
In the REPL, one step at a time: |
||
< |
<syntaxhighlight lang="lisp">CL-USER> (setf fn (running-stddev)) |
||
#<Interpreted Closure (:INTERNAL RUNNING-STDDEV) @ #x21b9a492> |
#<Interpreted Closure (:INTERNAL RUNNING-STDDEV) @ #x21b9a492> |
||
CL-USER> (funcall fn 2) |
CL-USER> (funcall fn 2) |
||
Line 1,143: | Line 1,143: | ||
CL-USER> (funcall fn 9) |
CL-USER> (funcall fn 9) |
||
2.0 |
2.0 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Component Pascal}}== |
=={{header|Component Pascal}}== |
||
{{incorrect|Component Pascal|Function does not take numbers individually.}} |
{{incorrect|Component Pascal|Function does not take numbers individually.}} |
||
BlackBox Component Builder |
BlackBox Component Builder |
||
< |
<syntaxhighlight lang="oberon2"> |
||
MODULE StandardDeviation; |
MODULE StandardDeviation; |
||
IMPORT StdLog, Args,Strings,Math; |
IMPORT StdLog, Args,Strings,Math; |
||
Line 1,192: | Line 1,192: | ||
END Do; |
END Do; |
||
END StandardDeviation. |
END StandardDeviation. |
||
</syntaxhighlight> |
|||
</lang> |
|||
Execute: ^Q StandardDeviation.Do 2 4 4 4 5 5 7 9 ~<br/> |
Execute: ^Q StandardDeviation.Do 2 4 4 4 5 5 7 9 ~<br/> |
||
{{out}} |
{{out}} |
||
Line 1,210: | Line 1,210: | ||
Use an object to keep state. |
Use an object to keep state. |
||
{{trans|Ruby}} |
{{trans|Ruby}} |
||
< |
<syntaxhighlight lang="ruby">class StdDevAccumulator |
||
def initialize |
def initialize |
||
@n, @sum, @sum2 = 0, 0.0, 0.0 |
@n, @sum, @sum2 = 0, 0.0, 0.0 |
||
Line 1,225: | Line 1,225: | ||
sd = StdDevAccumulator.new |
sd = StdDevAccumulator.new |
||
i = 0 |
i = 0 |
||
[2,4,4,4,5,5,7,9].each { |n| puts "adding #{n}: stddev of #{i+=1} samples is #{sd << n}" }</ |
[2,4,4,4,5,5,7,9].each { |n| puts "adding #{n}: stddev of #{i+=1} samples is #{sd << n}" }</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,240: | Line 1,240: | ||
===Closure=== |
===Closure=== |
||
{{trans|Ruby}} |
{{trans|Ruby}} |
||
< |
<syntaxhighlight lang="ruby">def sdaccum |
||
n, sum, sum2 = 0, 0.0, 0.0 |
n, sum, sum2 = 0, 0.0, 0.0 |
||
->(num : Int32) do |
->(num : Int32) do |
||
Line 1,251: | Line 1,251: | ||
sd = sdaccum |
sd = sdaccum |
||
[2,4,4,4,5,5,7,9].each {|n| print sd.call(n), ", "}</ |
[2,4,4,4,5,5,7,9].each {|n| print sd.call(n), ", "}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>0.0, 1.0, 0.9428090415820634, 0.8660254037844386, 0.9797958971132712, 1.0, 1.3997084244475304, 2.0</pre> |
<pre>0.0, 1.0, 0.9428090415820634, 0.8660254037844386, 0.9797958971132712, 1.0, 1.3997084244475304, 2.0</pre> |
||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.math; |
||
struct StdDev { |
struct StdDev { |
||
Line 1,283: | Line 1,283: | ||
writefln("%e", stdev.getStdDev()); |
writefln("%e", stdev.getStdDev()); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>0.000000e+00 |
<pre>0.000000e+00 |
||
Line 1,305: | Line 1,305: | ||
The algorithm is {{trans|Perl}} and the results were checked against [[#Python]]. |
The algorithm is {{trans|Perl}} and the results were checked against [[#Python]]. |
||
< |
<syntaxhighlight lang="e">def makeRunningStdDev() { |
||
var sum := 0.0 |
var sum := 0.0 |
||
var sumSquares := 0.0 |
var sumSquares := 0.0 |
||
Line 1,328: | Line 1,328: | ||
return [insert, stddev] |
return [insert, stddev] |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="e">? def [insert, stddev] := makeRunningStdDev() |
||
# value: <insert>, <stddev> |
# value: <insert>, <stddev> |
||
Line 1,347: | Line 1,347: | ||
1.0 |
1.0 |
||
1.3997084244475297 |
1.3997084244475297 |
||
2.0</ |
2.0</syntaxhighlight> |
||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
{{trans|Erlang}} |
{{trans|Erlang}} |
||
< |
<syntaxhighlight lang="elixir">defmodule Standard_deviation do |
||
def add_sample( pid, n ), do: send( pid, {:add, n} ) |
def add_sample( pid, n ), do: send( pid, {:add, n} ) |
||
Line 1,393: | Line 1,393: | ||
end |
end |
||
Standard_deviation.task</ |
Standard_deviation.task</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,409: | Line 1,409: | ||
=={{header|Emacs Lisp}}== |
=={{header|Emacs Lisp}}== |
||
< |
<syntaxhighlight lang="lisp">(defun running-std (items) |
||
(let ((running-sum 0) |
(let ((running-sum 0) |
||
(running-len 0) |
(running-len 0) |
||
Line 1,424: | Line 1,424: | ||
result)) |
result)) |
||
(running-std '(2 4 4 4 5 5 7 9))</ |
(running-std '(2 4 4 4 5 5 7 9))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,440: | Line 1,440: | ||
{{libheader|Calc}} |
{{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))))</ |
(string-to-number (calc-eval "sqrt(vpvar($1))" nil (append '(vec) x))))</syntaxhighlight> |
||
{{libheader|generator.el}} |
{{libheader|generator.el}} |
||
< |
<syntaxhighlight lang="lisp">;; lexical-binding: t |
||
(require 'generator) |
(require 'generator) |
||
Line 1,468: | Line 1,468: | ||
(generator (std-dev-gen test-data))) |
(generator (std-dev-gen test-data))) |
||
(dolist (i test-data) |
(dolist (i test-data) |
||
(message "with %d: %f" i (iter-next generator))))</ |
(message "with %d: %f" i (iter-next generator))))</syntaxhighlight> |
||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
<syntaxhighlight lang="erlang"> |
|||
<lang Erlang> |
|||
-module( standard_deviation ). |
-module( standard_deviation ). |
||
Line 1,511: | Line 1,511: | ||
loop_calculate_average( Ns ) -> lists:sum( Ns ) / erlang:length( Ns ). |
loop_calculate_average( Ns ) -> lists:sum( Ns ) / erlang:length( Ns ). |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,526: | Line 1,526: | ||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
< |
<syntaxhighlight lang="factor">USING: accessors io kernel math math.functions math.parser |
||
sequences ; |
sequences ; |
||
IN: standard-deviator |
IN: standard-deviator |
||
Line 1,547: | Line 1,547: | ||
{ 2 4 4 4 5 5 7 9 } |
{ 2 4 4 4 5 5 7 9 } |
||
<standard-deviator> [ [ add-value ] curry each ] keep |
<standard-deviator> [ [ add-value ] curry each ] keep |
||
current-std number>string print ;</ |
current-std number>string print ;</syntaxhighlight> |
||
=={{header|FOCAL}}== |
=={{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.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.20 S T(5)=5;S T(6)=5;S T(7)=7;S T(8)=9 |
||
Line 1,564: | Line 1,564: | ||
02.10 S XN=0;S XS=0;S XQ=0 |
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.20 S XN=XN+1;S XS=XS+A;S XQ=XQ+A*A |
||
02.30 S A=FSQT(XQ/XN - (XS/XN)^2)</ |
02.30 S A=FSQT(XQ/XN - (XS/XN)^2)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,579: | Line 1,579: | ||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
< |
<syntaxhighlight lang="forth">: f+! ( x addr -- ) dup f@ f+ f! ; |
||
: st-count ( stats -- n ) f@ ; |
: st-count ( stats -- n ) f@ ; |
||
Line 1,601: | Line 1,601: | ||
fdup dup f+! float+ |
fdup dup f+! float+ |
||
fdup f* f+! |
fdup f* f+! |
||
std-stddev ;</ |
std-stddev ;</syntaxhighlight> |
||
This variation is more numerically stable when there are large numbers of samples or large sample ranges. |
This variation is more numerically stable when there are large numbers of samples or large sample ranges. |
||
< |
<syntaxhighlight lang="forth">: st-count ( stats -- n ) f@ ; |
||
: st-mean ( stats -- mean ) float+ f@ ; |
: st-mean ( stats -- mean ) float+ f@ ; |
||
: st-nvar ( stats -- n*var ) 2 floats + f@ ; |
: st-nvar ( stats -- n*var ) 2 floats + f@ ; |
||
Line 1,621: | Line 1,621: | ||
( delta x ) |
( delta x ) |
||
dup f@ f- f* float+ f+! \ update nvar |
dup f@ f- f* float+ f+! \ update nvar |
||
st-stddev ;</ |
st-stddev ;</syntaxhighlight> |
||
Usage example: |
Usage example: |
||
< |
<syntaxhighlight lang="forth">create stats 0e f, 0e f, 0e f, |
||
2e stats st-add f. \ 0. |
2e stats st-add f. \ 0. |
||
Line 1,633: | Line 1,633: | ||
7e stats st-add f. \ 1.39970842444753 |
7e stats st-add f. \ 1.39970842444753 |
||
9e stats st-add f. \ 2. |
9e stats st-add f. \ 2. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
{{works with|Fortran|2003 and later}} |
{{works with|Fortran|2003 and later}} |
||
< |
<syntaxhighlight lang="fortran"> |
||
program standard_deviation |
program standard_deviation |
||
implicit none |
implicit none |
||
Line 1,687: | Line 1,687: | ||
end function stddev |
end function stddev |
||
end program standard_deviation |
end program standard_deviation |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,708: | Line 1,708: | ||
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. |
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 FUNCTION STDDEV(X) !Standard deviation for successive values. |
||
REAL X !The latest value. |
REAL X !The latest value. |
||
Line 1,783: | Line 1,783: | ||
END DO !On to the next value. |
END DO !On to the next value. |
||
END |
END |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: the second pair of columns have the calculations done with a working mean and thus accumulate deviations from that. |
Output: the second pair of columns have the calculations done with a working mean and thus accumulate deviations from that. |
||
Line 1,862: | Line 1,862: | ||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
||
Function calcStandardDeviation(number As Double) As Double |
Function calcStandardDeviation(number As Double) As Double |
||
Line 1,891: | Line 1,891: | ||
Print |
Print |
||
Print "Press any key to quit" |
Print "Press any key to quit" |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,909: | Line 1,909: | ||
State maintained with a closure. |
State maintained with a closure. |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 1,931: | Line 1,931: | ||
fmt.Println(r(x)) |
fmt.Println(r(x)) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,946: | Line 1,946: | ||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
Solution: |
Solution: |
||
< |
<syntaxhighlight lang="groovy">List samples = [] |
||
def stdDev = { def sample -> |
def stdDev = { def sample -> |
||
Line 1,958: | Line 1,958: | ||
[2,4,4,4,5,5,7,9].each { |
[2,4,4,4,5,5,7,9].each { |
||
println "${stdDev(it)}" |
println "${stdDev(it)}" |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,974: | Line 1,974: | ||
We store the state in the <code>ST</code> monad using an <code>STRef</code>. |
We store the state in the <code>ST</code> monad using an <code>STRef</code>. |
||
< |
<syntaxhighlight lang="haskell">{-# LANGUAGE BangPatterns #-} |
||
import Data.List (foldl') -- ' |
import Data.List (foldl') -- ' |
||
Line 2,001: | Line 2,001: | ||
main = mapM_ print $ runST $ |
main = mapM_ print $ runST $ |
||
mkSD >>= forM [2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0]</ |
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: |
Or, perhaps more simply, as a map-accumulation over an indexed list: |
||
< |
<syntaxhighlight lang="haskell">import Data.List (mapAccumL) |
||
Line 2,023: | Line 2,023: | ||
--------------------------- TEST ------------------------- |
--------------------------- TEST ------------------------- |
||
main :: IO () |
main :: IO () |
||
main = mapM_ print $ cumulativeStdDevns [2, 4, 4, 4, 5, 5, 7, 9]</ |
main = mapM_ print $ cumulativeStdDevns [2, 4, 4, 4, 5, 5, 7, 9]</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>0.0 |
<pre>0.0 |
||
Line 2,035: | Line 2,035: | ||
=={{header|Haxe}}== |
=={{header|Haxe}}== |
||
< |
<syntaxhighlight lang="haxe">using Lambda; |
||
class Main { |
class Main { |
||
Line 2,057: | Line 2,057: | ||
return Math.sqrt(average(store)); |
return Math.sqrt(average(store)); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
<pre>0 |
<pre>0 |
||
1 |
1 |
||
Line 2,068: | Line 2,068: | ||
=={{header|HicEst}}== |
=={{header|HicEst}}== |
||
< |
<syntaxhighlight lang="hicest">REAL :: n=8, set(n), sum=0, sum2=0 |
||
set = (2,4,4,4,5,5,7,9) |
set = (2,4,4,4,5,5,7,9) |
||
Line 2,083: | Line 2,083: | ||
sum2 = sum2 + x*x |
sum2 = sum2 + x*x |
||
stdev = ( sum2/k - (sum/k)^2) ^ 0.5 |
stdev = ( sum2/k - (sum/k)^2) ^ 0.5 |
||
END</ |
END</syntaxhighlight> |
||
<pre>Adding 2 stdev = 0 |
<pre>Adding 2 stdev = 0 |
||
Adding 4 stdev = 1 |
Adding 4 stdev = 1 |
||
Line 2,094: | Line 2,094: | ||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
< |
<syntaxhighlight lang="icon">procedure main() |
||
stddev() # reset state / empty |
stddev() # reset state / empty |
||
Line 2,115: | Line 2,115: | ||
return sqrt( (sum2X / *X) - (sumX / *X)^2 ) |
return sqrt( (sum2X / *X) - (sumX / *X)^2 ) |
||
} |
} |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>stddev (so far) := 0.0 |
<pre>stddev (so far) := 0.0 |
||
Line 2,127: | Line 2,127: | ||
=={{header|IS-BASIC}}== |
=={{header|IS-BASIC}}== |
||
< |
<syntaxhighlight lang="is-basic">100 PROGRAM "StDev.bas" |
||
110 LET N=8 |
110 LET N=8 |
||
120 NUMERIC ARR(1 TO N) |
120 NUMERIC ARR(1 TO N) |
||
Line 2,143: | Line 2,143: | ||
240 PRINT J;"item =";ARR(J),"standard dev =";STDEV(J) |
240 PRINT J;"item =";ARR(J),"standard dev =";STDEV(J) |
||
250 NEXT |
250 NEXT |
||
260 DATA 2,4,4,4,5,5,7,9</ |
260 DATA 2,4,4,4,5,5,7,9</syntaxhighlight> |
||
=={{header|J}}== |
=={{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. |
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. |
||
< |
<syntaxhighlight lang="j"> mean=: +/ % # |
||
dev=: - mean |
dev=: - mean |
||
stddevP=: [: %:@mean *:@dev NB. A) 3 equivalent defs for stddevP |
stddevP=: [: %:@mean *:@dev NB. A) 3 equivalent defs for stddevP |
||
Line 2,156: | Line 2,156: | ||
stddevP\ 2 4 4 4 5 5 7 9 |
stddevP\ 2 4 4 4 5 5 7 9 |
||
0 1 0.942809 0.866025 0.979796 1 1.39971 2</ |
0 1 0.942809 0.866025 0.979796 1 1.39971 2</syntaxhighlight> |
||
'''Alternatives:'''<br> |
'''Alternatives:'''<br> |
||
Using verbose names for J primitives. |
Using verbose names for J primitives. |
||
< |
<syntaxhighlight lang="j"> of =: @: |
||
sqrt =: %: |
sqrt =: %: |
||
sum =: +/ |
sum =: +/ |
||
Line 2,170: | Line 2,170: | ||
stddevP\ 2 4 4 4 5 5 7 9 |
stddevP\ 2 4 4 4 5 5 7 9 |
||
0 1 0.942809 0.866025 0.979796 1 1.39971 2</ |
0 1 0.942809 0.866025 0.979796 1 1.39971 2</syntaxhighlight> |
||
{{trans|R}}<BR> |
{{trans|R}}<BR> |
||
Or we could take a cue from the [[#R|R implementation]] and reverse the Bessel correction to stddev: |
Or we could take a cue from the [[#R|R implementation]] and reverse the Bessel correction to stddev: |
||
< |
<syntaxhighlight lang="j"> require'stats' |
||
(%:@:(%~<:)@:# * stddev)\ 2 4 4 4 5 5 7 9 |
(%:@:(%~<:)@:# * stddev)\ 2 4 4 4 5 5 7 9 |
||
0 1 0.942809 0.866025 0.979796 1 1.39971 2</ |
0 1 0.942809 0.866025 0.979796 1 1.39971 2</syntaxhighlight> |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
< |
<syntaxhighlight lang="java">public class StdDev { |
||
int n = 0; |
int n = 0; |
||
double sum = 0; |
double sum = 0; |
||
Line 2,201: | Line 2,201: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
Line 2,208: | Line 2,208: | ||
Uses a closure. |
Uses a closure. |
||
< |
<syntaxhighlight lang="javascript">function running_stddev() { |
||
var n = 0; |
var n = 0; |
||
var sum = 0.0; |
var sum = 0.0; |
||
Line 2,227: | Line 2,227: | ||
// using WSH |
// using WSH |
||
WScript.Echo(stddev.join(', ');</ |
WScript.Echo(stddev.join(', ');</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,236: | Line 2,236: | ||
Accumulating across a fold |
Accumulating across a fold |
||
< |
<syntaxhighlight lang="javascript">(function (xs) { |
||
return xs.reduce(function (a, x, i) { |
return xs.reduce(function (a, x, i) { |
||
Line 2,257: | Line 2,257: | ||
}).stages |
}).stages |
||
})([2, 4, 4, 4, 5, 5, 7, 9]);</ |
})([2, 4, 4, 4, 5, 5, 7, 9]);</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
< |
<syntaxhighlight lang="javascript">[0, 1, 0.9428090415820626, 0.8660254037844386, |
||
0.9797958971132716, 1, 1.3997084244475297, 2]</ |
0.9797958971132716, 1, 1.3997084244475297, 2]</syntaxhighlight> |
||
====ES6==== |
====ES6==== |
||
As a map-accumulation: |
As a map-accumulation: |
||
< |
<syntaxhighlight lang="javascript">(() => { |
||
'use strict'; |
'use strict'; |
||
Line 2,320: | Line 2,320: | ||
// MAIN --- |
// MAIN --- |
||
return main(); |
return main(); |
||
})();</ |
})();</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>[ |
<pre>[ |
||
Line 2,349: | Line 2,349: | ||
where SSD is the sum of squared deviations about the mean. |
where SSD is the sum of squared deviations about the mean. |
||
< |
<syntaxhighlight lang="jq"># Compute the standard deviation of the observations |
||
# seen so far, given the current state as input: |
# seen so far, given the current state as input: |
||
def standard_deviation: .ssd / .n | sqrt; |
def standard_deviation: .ssd / .n | sqrt; |
||
Line 2,374: | Line 2,374: | ||
# Begin: |
# Begin: |
||
simulate</ |
simulate</syntaxhighlight> |
||
'''Example 1''' |
'''Example 1''' |
||
# observations.txt |
# observations.txt |
||
Line 2,386: | Line 2,386: | ||
9 |
9 |
||
{{Out}} |
{{Out}} |
||
<syntaxhighlight lang="sh"> |
|||
<lang sh> |
|||
$ jq -s -f Dynamic_standard_deviation.jq observations.txt |
$ jq -s -f Dynamic_standard_deviation.jq observations.txt |
||
0 |
0 |
||
Line 2,396: | Line 2,396: | ||
1.3997084244475302 |
1.3997084244475302 |
||
1.9999999999999998 |
1.9999999999999998 |
||
</syntaxhighlight> |
|||
</lang> |
|||
====Observations from a stream==== |
====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. |
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. |
||
< |
<syntaxhighlight lang="jq"># requires jq version > 1.4 |
||
def simulate(stream): |
def simulate(stream): |
||
foreach stream as $observation |
foreach stream as $observation |
||
(initial_state; |
(initial_state; |
||
update_state($observation); |
update_state($observation); |
||
standard_deviation);</ |
standard_deviation);</syntaxhighlight> |
||
'''Example 2''': |
'''Example 2''': |
||
simulate( range(0;10) ) |
simulate( range(0;10) ) |
||
Line 2,423: | Line 2,423: | ||
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. |
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. |
||
< |
<syntaxhighlight lang="sh">#!/bin/bash |
||
# jq is assumed to be on PATH |
# jq is assumed to be on PATH |
||
Line 2,460: | Line 2,460: | ||
sed -n 1p <<< "$result" |
sed -n 1p <<< "$result" |
||
state=$(sed -n 2p <<< "$result") |
state=$(sed -n 2p <<< "$result") |
||
done</ |
done</syntaxhighlight> |
||
'''Example 3''' |
'''Example 3''' |
||
< |
<syntaxhighlight lang="sh">$ ./standard_deviation_server.sh |
||
Next observation: 10 |
Next observation: 10 |
||
0 |
0 |
||
Line 2,469: | Line 2,469: | ||
Next observation: 0 |
Next observation: 0 |
||
8.16496580927726 |
8.16496580927726 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
Use a closure to create a running standard deviation function. |
Use a closure to create a running standard deviation function. |
||
< |
<syntaxhighlight lang="julia">function makerunningstd(::Type{T} = Float64) where T |
||
∑x = ∑x² = zero(T) |
∑x = ∑x² = zero(T) |
||
n = 0 |
n = 0 |
||
Line 2,492: | Line 2,492: | ||
for i in test |
for i in test |
||
println(" - add $i → ", rstd(i)) |
println(" - add $i → ", rstd(i)) |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,509: | Line 2,509: | ||
{{trans|Java}} |
{{trans|Java}} |
||
Using a class to keep the running sum, sum of squares and number of elements added so far: |
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 { |
class CumStdDev { |
||
Line 2,528: | Line 2,528: | ||
val csd = CumStdDev() |
val csd = CumStdDev() |
||
for (d in testData) println("Add $d => ${csd.sd(d)}") |
for (d in testData) println("Add $d => ${csd.sd(d)}") |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,544: | Line 2,544: | ||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |
||
Using a global array to maintain the state. Implements definition explicitly. |
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. |
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 |
' holds (space-separated) number of data items so far, current sum.of.values and current sum.of.squares |
||
Line 2,571: | Line 2,571: | ||
Data 2, 4, 4, 4, 5, 5, 7, 9 |
Data 2, 4, 4, 4, 5, 5, 7, 9 |
||
</syntaxhighlight> |
|||
</lang> |
|||
<pre> |
<pre> |
||
New data 2 so S.D. now = 0.000000 |
New data 2 so S.D. now = 0.000000 |
||
Line 2,584: | Line 2,584: | ||
=={{header|Lobster}}== |
=={{header|Lobster}}== |
||
<syntaxhighlight lang="lobster"> |
|||
<lang Lobster> |
|||
// Stats computes a running mean and variance |
// Stats computes a running mean and variance |
||
// See Knuth TAOCP vol 2, 3rd edition, page 232 |
// See Knuth TAOCP vol 2, 3rd edition, page 232 |
||
Line 2,613: | Line 2,613: | ||
test_stdv() |
test_stdv() |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,621: | Line 2,621: | ||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
Uses a closure. Translation of JavaScript. |
Uses a closure. Translation of JavaScript. |
||
< |
<syntaxhighlight lang="lua">function stdev() |
||
local sum, sumsq, k = 0,0,0 |
local sum, sumsq, k = 0,0,0 |
||
return function(n) |
return function(n) |
||
Line 2,632: | Line 2,632: | ||
for i, v in ipairs{2,4,4,4,5,5,7,9} do |
for i, v in ipairs{2,4,4,4,5,5,7,9} do |
||
print(ldev(v)) |
print(ldev(v)) |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
||
< |
<syntaxhighlight lang="mathematica">runningSTDDev[n_] := (If[Not[ValueQ[$Data]], $Data = {}];StandardDeviation[AppendTo[$Data, n]])</syntaxhighlight> |
||
=={{header|MATLAB}} / {{header|Octave}}== |
=={{header|MATLAB}} / {{header|Octave}}== |
||
The simple form is, computing only the standand deviation of the whole data set: |
The simple form is, computing only the standand deviation of the whole data set: |
||
< |
<syntaxhighlight lang="matlab"> x = [2,4,4,4,5,5,7,9]; |
||
n = length (x); |
n = length (x); |
||
Line 2,646: | Line 2,646: | ||
x2 = mean (x .* x); |
x2 = mean (x .* x); |
||
dev= sqrt (x2 - m * m) |
dev= sqrt (x2 - m * m) |
||
dev = 2 </ |
dev = 2 </syntaxhighlight> |
||
When the intermediate results are also needed, one can use this vectorized form: |
When the intermediate results are also needed, one can use this vectorized form: |
||
< |
<syntaxhighlight lang="matlab"> m = cumsum(x) ./ [1:n]; % running mean |
||
x2= cumsum(x.^2) ./ [1:n]; % running squares |
x2= cumsum(x.^2) ./ [1:n]; % running squares |
||
Line 2,657: | Line 2,657: | ||
0.00000 1.00000 0.94281 0.86603 0.97980 1.00000 1.39971 2.00000 |
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 |
Here is a vectorized one line solution as a function |
||
<syntaxhighlight lang="matlab"> |
|||
<lang Matlab> |
|||
function stdDevEval(n) |
function stdDevEval(n) |
||
disp(sqrt(sum((n-sum(n)/length(n)).^2)/length(n))); |
disp(sqrt(sum((n-sum(n)/length(n)).^2)/length(n))); |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|MiniScript}}== |
=={{header|MiniScript}}== |
||
< |
<syntaxhighlight lang="miniscript">StdDeviator = {} |
||
StdDeviator.count = 0 |
StdDeviator.count = 0 |
||
StdDeviator.sum = 0 |
StdDeviator.sum = 0 |
||
Line 2,687: | Line 2,687: | ||
sd.add x |
sd.add x |
||
end for |
end for |
||
print sd.stddev</ |
print sd.stddev</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>2</pre> |
<pre>2</pre> |
||
=={{header|МК-61/52}}== |
=={{header|МК-61/52}}== |
||
<lang>0 П4 П5 П6 С/П П0 ИП5 + П5 ИП0 |
<syntaxhighlight lang="text">0 П4 П5 П6 С/П П0 ИП5 + П5 ИП0 |
||
x^2 ИП6 + П6 КИП4 ИП6 ИП4 / ИП5 ИП4 |
x^2 ИП6 + П6 КИП4 ИП6 ИП4 / ИП5 ИП4 |
||
/ x^2 - КвКор БП 04</ |
/ x^2 - КвКор БП 04</syntaxhighlight> |
||
Instruction: В/О С/П ''number'' С/П ''number'' С/П ... |
Instruction: В/О С/П ''number'' С/П ''number'' С/П ... |
||
Line 2,700: | Line 2,700: | ||
=={{header|Nanoquery}}== |
=={{header|Nanoquery}}== |
||
{{trans|Java}} |
{{trans|Java}} |
||
< |
<syntaxhighlight lang="nanoquery">class StdDev |
||
declare n |
declare n |
||
declare sum |
declare sum |
||
Line 2,725: | Line 2,725: | ||
for x in testData |
for x in testData |
||
println sd.sd(x) |
println sd.sd(x) |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,740: | Line 2,740: | ||
===Using global variables=== |
===Using global variables=== |
||
< |
<syntaxhighlight lang="nim">import math, strutils |
||
var sdSum, sdSum2, sdN = 0.0 |
var sdSum, sdSum2, sdN = 0.0 |
||
Line 2,751: | Line 2,751: | ||
for value in [float 2,4,4,4,5,5,7,9]: |
for value in [float 2,4,4,4,5,5,7,9]: |
||
echo value, " ", formatFloat(sd(value), precision = -1)</ |
echo value, " ", formatFloat(sd(value), precision = -1)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,764: | Line 2,764: | ||
===Using an accumulator object=== |
===Using an accumulator object=== |
||
< |
<syntaxhighlight lang="nim">import math, strutils |
||
type SDAccum = object |
type SDAccum = object |
||
Line 2,779: | Line 2,779: | ||
for value in [float 2, 4, 4, 4, 5, 5, 7, 9]: |
for value in [float 2, 4, 4, 4, 5, 5, 7, 9]: |
||
echo value, " ", formatFloat(accum.add(value), precision = -1)</ |
echo value, " ", formatFloat(accum.add(value), precision = -1)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,785: | Line 2,785: | ||
===Using a closure=== |
===Using a closure=== |
||
< |
<syntaxhighlight lang="nim">import math, strutils |
||
func accumBuilder(): auto = |
func accumBuilder(): auto = |
||
Line 2,799: | Line 2,799: | ||
for value in [float 2, 4, 4, 4, 5, 5, 7, 9]: |
for value in [float 2, 4, 4, 4, 5, 5, 7, 9]: |
||
echo value, " ", formatFloat(std(value), precision = -1)</ |
echo value, " ", formatFloat(std(value), precision = -1)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,806: | Line 2,806: | ||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
{{trans|Java}} |
{{trans|Java}} |
||
< |
<syntaxhighlight lang="objeck"> |
||
use Structure; |
use Structure; |
||
Line 2,842: | Line 2,842: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Objective-C}}== |
=={{header|Objective-C}}== |
||
< |
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h> |
||
@interface SDAccum : NSObject |
@interface SDAccum : NSObject |
||
Line 2,899: | Line 2,899: | ||
} |
} |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
===Blocks=== |
===Blocks=== |
||
Line 2,905: | Line 2,905: | ||
{{works with|iOS|4+}} |
{{works with|iOS|4+}} |
||
< |
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h> |
||
typedef double (^Func)(double); // a block that takes a double and returns a double |
typedef double (^Func)(double); // a block that takes a double and returns a double |
||
Line 2,934: | Line 2,934: | ||
} |
} |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
< |
<syntaxhighlight lang="ocaml">let sqr x = x *. x |
||
let stddev l = |
let stddev l = |
||
Line 2,951: | Line 2,951: | ||
Printf.printf "List: "; |
Printf.printf "List: "; |
||
List.iter (Printf.printf "%g ") l; |
List.iter (Printf.printf "%g ") l; |
||
Printf.printf "\nStandard deviation: %g\n" (stddev l)</ |
Printf.printf "\nStandard deviation: %g\n" (stddev l)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,965: | Line 2,965: | ||
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. |
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. |
||
< |
<syntaxhighlight lang="oforth">Channel new [ ] over send drop const: StdValues |
||
: stddev(x) |
: stddev(x) |
||
| l | |
| l | |
||
StdValues receive x + dup ->l StdValues send drop |
StdValues receive x + dup ->l StdValues send drop |
||
#qs l map sum l size asFloat / l avg sq - sqrt ;</ |
#qs l map sum l size asFloat / l avg sq - sqrt ;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,989: | Line 2,989: | ||
=={{header|ooRexx}}== |
=={{header|ooRexx}}== |
||
{{works with|oorexx}} |
{{works with|oorexx}} |
||
< |
<syntaxhighlight lang="rexx">sdacc = .SDAccum~new |
||
x = .array~of(2,4,4,4,5,5,7,9) |
x = .array~of(2,4,4,4,5,5,7,9) |
||
sd = 0 |
sd = 0 |
||
Line 3,030: | Line 3,030: | ||
ans = ( prev + ( n / prev ) ) / 2 |
ans = ( prev + ( n / prev ) ) / 2 |
||
end |
end |
||
return ans</ |
return ans</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>#1 value = 2 stdev = 0 |
<pre>#1 value = 2 stdev = 0 |
||
Line 3,043: | Line 3,043: | ||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
Uses the Cramer-Young updating algorithm. For demonstration it displays the mean and variance at each step. |
Uses the Cramer-Young updating algorithm. For demonstration it displays the mean and variance at each step. |
||
< |
<syntaxhighlight lang="parigp">newpoint(x)={ |
||
myT=x; |
myT=x; |
||
myS=0; |
myS=0; |
||
Line 3,061: | Line 3,061: | ||
print("Standard deviation: ",sqrt(myS/myN)) |
print("Standard deviation: ",sqrt(myS/myN)) |
||
}; |
}; |
||
addpoints([2,4,4,4,5,5,7,9])</ |
addpoints([2,4,4,4,5,5,7,9])</syntaxhighlight> |
||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
===Std.Pascal=== |
===Std.Pascal=== |
||
{{trans|AWK}} |
{{trans|AWK}} |
||
< |
<syntaxhighlight lang="pascal">program stddev; |
||
uses math; |
uses math; |
||
const |
const |
||
Line 3,093: | Line 3,093: | ||
writeln(i,' item=',arr[i]:2:0,' stddev=',stddev(i):18:15) |
writeln(i,' item=',arr[i]:2:0,' stddev=',stddev(i):18:15) |
||
end |
end |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1 item= 2 stddev= 0.000000000000000 |
<pre>1 item= 2 stddev= 0.000000000000000 |
||
Line 3,104: | Line 3,104: | ||
8 item= 9 stddev= 2.000000000000000</pre> |
8 item= 9 stddev= 2.000000000000000</pre> |
||
==={{header|Delphi}}=== |
==={{header|Delphi}}=== |
||
< |
<syntaxhighlight lang="delphi">program prj_CalcStdDerv; |
||
{$APPTYPE CONSOLE} |
{$APPTYPE CONSOLE} |
||
Line 3,134: | Line 3,134: | ||
end; |
end; |
||
Readln; |
Readln; |
||
end. </ |
end. </syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,148: | Line 3,148: | ||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl">{ |
||
package SDAccum; |
package SDAccum; |
||
sub new { |
sub new { |
||
Line 3,184: | Line 3,184: | ||
return $self->stddev; |
return $self->stddev; |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="perl">my $sdacc = SDAccum->new; |
||
my $sd; |
my $sd; |
||
Line 3,192: | Line 3,192: | ||
$sd = $sdacc->value($v); |
$sd = $sdacc->value($v); |
||
} |
} |
||
print "std dev = $sd\n";</ |
print "std dev = $sd\n";</syntaxhighlight> |
||
A much shorter version using a closure and a property of the variance: |
A much shorter version using a closure and a property of the variance: |
||
< |
<syntaxhighlight lang="perl"># <(x - <x>)²> = <x²> - <x>² |
||
{ |
{ |
||
my $num, $sum, $sum2; |
my $num, $sum, $sum2; |
||
Line 3,209: | Line 3,209: | ||
} |
} |
||
print stddev($_), "\n" for qw(2 4 4 4 5 5 7 9);</ |
print stddev($_), "\n" for qw(2 4 4 4 5 5 7 9);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,222: | Line 3,222: | ||
one-liner: |
one-liner: |
||
< |
<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> |
||
small script: |
small script: |
||
< |
<syntaxhighlight lang="perl">use Math::StdDev; |
||
$d=new Math::StdDev; |
$d=new Math::StdDev; |
||
foreach my $v ( 2,4,4,4,5,5,7,9 ) { |
foreach my $v ( 2,4,4,4,5,5,7,9 ) { |
||
$d->Update($v); |
$d->Update($v); |
||
print $d->variance(),"\n" |
print $d->variance(),"\n" |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,245: | Line 3,245: | ||
=={{header|Phix}}== |
=={{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. |
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: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
||
Line 3,272: | Line 3,272: | ||
<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: #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> |
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,287: | Line 3,287: | ||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
This is just straight PHP class usage, respecting the specifications "stateful" and "one at a time": |
This is just straight PHP class usage, respecting the specifications "stateful" and "one at a time": |
||
< |
<syntaxhighlight lang="php"><?php |
||
class sdcalc { |
class sdcalc { |
||
private $cnt, $sumup, $square; |
private $cnt, $sumup, $square; |
||
Line 3,317: | Line 3,317: | ||
foreach ([2,4,4,4,5,5,7,9] as $v) { |
foreach ([2,4,4,4,5,5,7,9] as $v) { |
||
printf('Adding %g: result %g%s', $v, $c->add($v), PHP_EOL); |
printf('Adding %g: result %g%s', $v, $c->add($v), PHP_EOL); |
||
}</ |
}</syntaxhighlight> |
||
This will produce the output: |
This will produce the output: |
||
Line 3,332: | Line 3,332: | ||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">(scl 2) |
||
(de stdDev () |
(de stdDev () |
||
Line 3,349: | Line 3,349: | ||
(let Fun (stdDev) |
(let Fun (stdDev) |
||
(for N (2.0 4.0 4.0 4.0 5.0 5.0 7.0 9.0) |
(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)) ) )</ |
(prinl (format N *Scl) " -> " (format (Fun N) *Scl)) ) )</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>2.00 -> 0.00 |
<pre>2.00 -> 0.00 |
||
Line 3,361: | Line 3,361: | ||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
< |
<syntaxhighlight lang="pli">*process source attributes xref; |
||
stddev: proc options(main); |
stddev: proc options(main); |
||
declare a(10) float init(1,2,3,4,5,6,7,8,9,10); |
declare a(10) float init(1,2,3,4,5,6,7,8,9,10); |
||
Line 3,385: | Line 3,385: | ||
end std_dev; |
end std_dev; |
||
end;</ |
end;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>AVERAGE= 5.50000E+0000; |
<pre>AVERAGE= 5.50000E+0000; |
||
Line 3,393: | Line 3,393: | ||
This implementation takes the form of an advanced function |
This implementation takes the form of an advanced function |
||
which can act like a cmdlet and receive input from the pipeline. |
which can act like a cmdlet and receive input from the pipeline. |
||
< |
<syntaxhighlight lang="powershell">function Get-StandardDeviation { |
||
begin { |
begin { |
||
$avg = 0 |
$avg = 0 |
||
Line 3,405: | Line 3,405: | ||
[Math]::Sqrt($sum / $nums.Length) |
[Math]::Sqrt($sum / $nums.Length) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Usage as follows: |
Usage as follows: |
||
<pre>PS> 2,4,4,4,5,5,7,9 | Get-StandardDeviation |
<pre>PS> 2,4,4,4,5,5,7,9 | Get-StandardDeviation |
||
Line 3,418: | Line 3,418: | ||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
< |
<syntaxhighlight lang="purebasic">;Define our Standard deviation function |
||
Declare.d Standard_deviation(x) |
Declare.d Standard_deviation(x) |
||
Line 3,446: | Line 3,446: | ||
MyList: |
MyList: |
||
Data.i 2,4,4,4,5,5,7,9 |
Data.i 2,4,4,4,5,5,7,9 |
||
EndDataSection</ |
EndDataSection</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,464: | Line 3,464: | ||
The program should work with Python 2.x and 3.x, |
The program should work with Python 2.x and 3.x, |
||
although the output would not be a tuple in 3.x |
although the output would not be a tuple in 3.x |
||
< |
<syntaxhighlight lang="python">>>> from math import sqrt |
||
>>> def sd(x): |
>>> def sd(x): |
||
sd.sum += x |
sd.sum += x |
||
Line 3,485: | Line 3,485: | ||
(7, 1.3997084244475311) |
(7, 1.3997084244475311) |
||
(9, 2.0) |
(9, 2.0) |
||
>>></ |
>>></syntaxhighlight> |
||
===Python: Using a class instance=== |
===Python: Using a class instance=== |
||
< |
<syntaxhighlight lang="python">>>> class SD(object): # Plain () for python 3.x |
||
def __init__(self): |
def __init__(self): |
||
self.sum, self.sum2, self.n = (0,0,0) |
self.sum, self.sum2, self.n = (0,0,0) |
||
Line 3,500: | Line 3,500: | ||
>>> sd_inst = SD() |
>>> sd_inst = SD() |
||
>>> for value in (2,4,4,4,5,5,7,9): |
>>> for value in (2,4,4,4,5,5,7,9): |
||
print (value, sd_inst.sd(value))</ |
print (value, sd_inst.sd(value))</syntaxhighlight> |
||
====Python: Callable class==== |
====Python: Callable class==== |
||
Line 3,507: | Line 3,507: | ||
===Python: Using a Closure=== |
===Python: Using a Closure=== |
||
{{Works with|Python|3.x}} |
{{Works with|Python|3.x}} |
||
< |
<syntaxhighlight lang="python">>>> from math import sqrt |
||
>>> def sdcreator(): |
>>> def sdcreator(): |
||
sum = sum2 = n = 0 |
sum = sum2 = n = 0 |
||
Line 3,531: | Line 3,531: | ||
5 1.0 |
5 1.0 |
||
7 1.39970842445 |
7 1.39970842445 |
||
9 2.0</ |
9 2.0</syntaxhighlight> |
||
===Python: Using an extended generator=== |
===Python: Using an extended generator=== |
||
{{Works with|Python|2.5+}} |
{{Works with|Python|2.5+}} |
||
< |
<syntaxhighlight lang="python">>>> from math import sqrt |
||
>>> def sdcreator(): |
>>> def sdcreator(): |
||
sum = sum2 = n = 0 |
sum = sum2 = n = 0 |
||
Line 3,558: | Line 3,558: | ||
5 1.0 |
5 1.0 |
||
7 1.39970842445 |
7 1.39970842445 |
||
9 2.0</ |
9 2.0</syntaxhighlight> |
||
===Python: In a couple of 'functional' lines=== |
===Python: In a couple of 'functional' lines=== |
||
< |
<syntaxhighlight lang="python">>>> myMean = lambda MyList : reduce(lambda x, y: x + y, MyList) / float(len(MyList)) |
||
>>> myStd = lambda MyList : (reduce(lambda x,y : x + y , map(lambda x: (x-myMean(MyList))**2 , MyList)) / float(len(MyList)))**.5 |
>>> 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]) |
>>> print myStd([2,4,4,4,5,5,7,9]) |
||
2.0 |
2.0 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|R}}== |
=={{header|R}}== |
||
Line 3,574: | Line 3,574: | ||
If the goal is to get a vector of running standard deviations, the simplest is to do it with cumsum: |
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) |
n <- seq_along(x) |
||
sqrt(cumsum(x^2) / n - (cumsum(x) / n)^2) |
sqrt(cumsum(x^2) / n - (cumsum(x) / n)^2) |
||
Line 3,588: | Line 3,588: | ||
Vectorize(function(k) sd(x[1:k]) * sqrt((k - 1) / k))(seq_along(x)) |
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 |
# [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.</ |
# 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: |
The task requires an accumulator solution: |
||
< |
<syntaxhighlight lang="rsplus">accumsd <- function() { |
||
n <- 0 |
n <- 0 |
||
m <- 0 |
m <- 0 |
||
Line 3,607: | Line 3,607: | ||
f <- accumsd() |
f <- accumsd() |
||
sapply(x, f) |
sapply(x, f) |
||
# [1] 0.0000000 0.3380816 0.8752973 1.1783628 1.2345538 1.3757142 1.2867220 1.2229056 1.1665168 1.1096814</ |
# [1] 0.0000000 0.3380816 0.8752973 1.1783628 1.2345538 1.3757142 1.2867220 1.2229056 1.1665168 1.1096814</syntaxhighlight> |
||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
< |
<syntaxhighlight lang="racket"> |
||
#lang racket |
#lang racket |
||
(require math) |
(require math) |
||
Line 3,619: | Line 3,619: | ||
;; run it on each number, return the last result |
;; run it on each number, return the last result |
||
(last (map running-stddev '(2 4 4 4 5 5 7 9))) |
(last (map running-stddev '(2 4 4 4 5 5 7 9))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
Line 3,625: | Line 3,625: | ||
{{works with|Rakudo Star|2010.08}} |
{{works with|Rakudo Star|2010.08}} |
||
Using a closure: |
Using a closure: |
||
<lang |
<syntaxhighlight lang="raku" line>sub sd (@a) { |
||
my $mean = @a R/ [+] @a; |
my $mean = @a R/ [+] @a; |
||
sqrt @a R/ [+] map (* - $mean)**2, @a; |
sqrt @a R/ [+] map (* - $mean)**2, @a; |
||
Line 3,636: | Line 3,636: | ||
my &f = sdaccum; |
my &f = sdaccum; |
||
say f $_ for 2, 4, 4, 4, 5, 5, 7, 9;</ |
say f $_ for 2, 4, 4, 4, 5, 5, 7, 9;</syntaxhighlight> |
||
Using a state variable: |
Using a state variable: |
||
<lang |
<syntaxhighlight lang="raku" line># remember that <(x-<x>)²> = <x²> - <x>² |
||
sub stddev($x) { |
sub stddev($x) { |
||
sqrt |
sqrt |
||
Line 3,647: | Line 3,647: | ||
} |
} |
||
say stddev $_ for <2 4 4 4 5 5 7 9>;</ |
say stddev $_ for <2 4 4 4 5 5 7 9>;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,662: | Line 3,662: | ||
These REXX versions use ''running sums''. |
These REXX versions use ''running sums''. |
||
===show running sums=== |
===show running sums=== |
||
< |
<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*/ |
parse arg # /*obtain optional arguments from the CL*/ |
||
if #='' then #= 2 4 4 4 5 5 7 9 /*None specified? Then use the default*/ |
if #='' then #= 2 4 4 4 5 5 7 9 /*None specified? Then use the default*/ |
||
Line 3,680: | Line 3,680: | ||
do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ |
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*/ |
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</ |
numeric digits d; return g/1</syntaxhighlight> |
||
{{out|output|text= when using the default input of: <tt> 2 4 4 4 5 5 7 9 </tt>}} |
{{out|output|text= when using the default input of: <tt> 2 4 4 4 5 5 7 9 </tt>}} |
||
<pre> |
<pre> |
||
Line 3,695: | Line 3,695: | ||
===only show standard deviation=== |
===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*/ |
parse arg # /*obtain optional arguments from the CL*/ |
||
if #='' then #= 2 4 4 4 5 5 7 9 /*None specified? Then use the default*/ |
if #='' then #= 2 4 4 4 5 5 7 9 /*None specified? Then use the default*/ |
||
Line 3,711: | Line 3,711: | ||
do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ |
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*/ |
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</ |
numeric digits d; return g/1</syntaxhighlight> |
||
{{out|output|text= when using the default input of: <tt> 2 4 4 4 5 5 7 9 </tt>}} |
{{out|output|text= when using the default input of: <tt> 2 4 4 4 5 5 7 9 </tt>}} |
||
<pre> |
<pre> |
||
Line 3,718: | Line 3,718: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
# Project : Cumulative standard deviation |
# Project : Cumulative standard deviation |
||
Line 3,736: | Line 3,736: | ||
see "" + num + " value in = " + stddata + " Stand Dev = " + standdev + nl |
see "" + num + " value in = " + stddata + " Stand Dev = " + standdev + nl |
||
next |
next |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 3,755: | Line 3,755: | ||
"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]]. |
"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]]. |
||
< |
<syntaxhighlight lang="ruby">class StdDevAccumulator |
||
def initialize |
def initialize |
||
@n, @sum, @sumofsquares = 0, 0.0, 0.0 |
@n, @sum, @sumofsquares = 0, 0.0, 0.0 |
||
Line 3,779: | Line 3,779: | ||
sd = StdDevAccumulator.new |
sd = StdDevAccumulator.new |
||
i = 0 |
i = 0 |
||
[2,4,4,4,5,5,7,9].each {|n| puts "adding #{n}: stddev of #{i+=1} samples is #{sd << n}" }</ |
[2,4,4,4,5,5,7,9].each {|n| puts "adding #{n}: stddev of #{i+=1} samples is #{sd << n}" }</syntaxhighlight> |
||
<pre>adding 2: stddev of 1 samples is 0.0 |
<pre>adding 2: stddev of 1 samples is 0.0 |
||
Line 3,791: | Line 3,791: | ||
=== Closure === |
=== Closure === |
||
< |
<syntaxhighlight lang="ruby">def sdaccum |
||
n, sum, sum2 = 0, 0.0, 0.0 |
n, sum, sum2 = 0, 0.0, 0.0 |
||
lambda do |num| |
lambda do |num| |
||
Line 3,802: | Line 3,802: | ||
sd = sdaccum |
sd = sdaccum |
||
[2,4,4,4,5,5,7,9].each {|n| print sd.call(n), ", "}</ |
[2,4,4,4,5,5,7,9].each {|n| print sd.call(n), ", "}</syntaxhighlight> |
||
<pre>0.0, 1.0, 0.942809041582063, 0.866025403784439, 0.979795897113272, 1.0, 1.39970842444753, 2.0, </pre> |
<pre>0.0, 1.0, 0.942809041582063, 0.866025403784439, 0.979795897113272, 1.0, 1.39970842444753, 2.0, </pre> |
||
=={{header|Run BASIC}}== |
=={{header|Run BASIC}}== |
||
< |
<syntaxhighlight lang="runbasic">dim sdSave$(100) 'can call up to 100 versions |
||
'holds (space-separated) number of data , sum of values and sum of squares |
'holds (space-separated) number of data , sum of values and sum of squares |
||
sd$ = "2,4,4,4,5,5,7,9" |
sd$ = "2,4,4,4,5,5,7,9" |
||
Line 3,822: | Line 3,822: | ||
print num;" value in = ";stdData; " Stand Dev = "; using("###.######", standDev) |
print num;" value in = ";stdData; " Stand Dev = "; using("###.######", standDev) |
||
next num</ |
next num</syntaxhighlight> |
||
<pre>1 value in = 2 Stand Dev = 0.000000 |
<pre>1 value in = 2 Stand Dev = 0.000000 |
||
2 value in = 4 Stand Dev = 1.000000 |
2 value in = 4 Stand Dev = 1.000000 |
||
Line 3,835: | Line 3,835: | ||
Using a struct: |
Using a struct: |
||
{{trans|Java}} |
{{trans|Java}} |
||
< |
<syntaxhighlight lang="rust">pub struct CumulativeStandardDeviation { |
||
n: f64, |
n: f64, |
||
sum: f64, |
sum: f64, |
||
Line 3,866: | Line 3,866: | ||
println!("{}", cum_stdev.push(*num as f64)); |
println!("{}", cum_stdev.push(*num as f64)); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,880: | Line 3,880: | ||
Using a closure: |
Using a closure: |
||
< |
<syntaxhighlight lang="rust">fn sd_creator() -> impl FnMut(f64) -> f64 { |
||
let mut n = 0.0; |
let mut n = 0.0; |
||
let mut sum = 0.0; |
let mut sum = 0.0; |
||
Line 3,899: | Line 3,899: | ||
println!("{}", sd_acc(*num as f64)); |
println!("{}", sd_acc(*num as f64)); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,913: | Line 3,913: | ||
=={{header|SAS}}== |
=={{header|SAS}}== |
||
<syntaxhighlight lang="sas"> |
|||
<lang SAS> |
|||
*--Load the test data; |
*--Load the test data; |
||
data test1; |
data test1; |
||
Line 3,946: | Line 3,946: | ||
var n sd /*mean*/; |
var n sd /*mean*/; |
||
run; |
run; |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 3,965: | Line 3,965: | ||
===Generic for any numeric type=== |
===Generic for any numeric type=== |
||
{{libheader|Scala}} |
{{libheader|Scala}} |
||
< |
<syntaxhighlight lang="scala">import scala.math.sqrt |
||
object StddevCalc extends App { |
object StddevCalc extends App { |
||
Line 3,990: | Line 3,990: | ||
println(s"Successfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart}ms]") |
println(s"Successfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart}ms]") |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
< |
<syntaxhighlight lang="scheme"> |
||
(define (standart-deviation-generator) |
(define (standart-deviation-generator) |
||
(let ((nums '())) |
(let ((nums '())) |
||
Line 4,010: | Line 4,010: | ||
(newline) |
(newline) |
||
(loop f (cdr input))))) |
(loop f (cdr input))))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Scilab}}== |
=={{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. |
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. |
||
<lang>T=[2,4,4,4,5,5,7,9]; |
<syntaxhighlight lang="text">T=[2,4,4,4,5,5,7,9]; |
||
stdev(T)*sqrt((length(T)-1)/length(T))</ |
stdev(T)*sqrt((length(T)-1)/length(T))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>-->T=[2,4,4,4,5,5,7,9]; |
<pre>-->T=[2,4,4,4,5,5,7,9]; |
||
Line 4,023: | Line 4,023: | ||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
Using an object to keep state: |
Using an object to keep state: |
||
< |
<syntaxhighlight lang="ruby">class StdDevAccumulator(n=0, sum=0, sumofsquares=0) { |
||
method <<(num) { |
method <<(num) { |
||
n += 1 |
n += 1 |
||
Line 4,044: | Line 4,044: | ||
[2,4,4,4,5,5,7,9].each {|n| |
[2,4,4,4,5,5,7,9].each {|n| |
||
say "adding #{n}: stddev of #{i+=1} samples is #{sd << n}" |
say "adding #{n}: stddev of #{i+=1} samples is #{sd << n}" |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 4,058: | Line 4,058: | ||
Using ''static'' variables: |
Using ''static'' variables: |
||
< |
<syntaxhighlight lang="ruby">func stddev(x) { |
||
static(num=0, sum=0, sum2=0) |
static(num=0, sum=0, sum2=0) |
||
num++ |
num++ |
||
Line 4,067: | Line 4,067: | ||
} |
} |
||
%n(2 4 4 4 5 5 7 9).each { say stddev(_) }</ |
%n(2 4 4 4 5 5 7 9).each { say stddev(_) }</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 4,083: | Line 4,083: | ||
{{works with|GNU Smalltalk}} |
{{works with|GNU Smalltalk}} |
||
< |
<syntaxhighlight lang="smalltalk">Object subclass: SDAccum [ |
||
|sum sum2 num| |
|sum sum2 num| |
||
SDAccum class >> new [ |o| |
SDAccum class >> new [ |o| |
||
Line 4,102: | Line 4,102: | ||
] |
] |
||
stddev [ ^ (self variance) sqrt ] |
stddev [ ^ (self variance) sqrt ] |
||
].</ |
].</syntaxhighlight> |
||
< |
<syntaxhighlight lang="smalltalk">|sdacc sd| |
||
sdacc := SDAccum new. |
sdacc := SDAccum new. |
||
#( 2 4 4 4 5 5 7 9 ) do: [ :v | sd := sdacc value: v ]. |
#( 2 4 4 4 5 5 7 9 ) do: [ :v | sd := sdacc value: v ]. |
||
('std dev = %1' % { sd }) displayNl.</ |
('std dev = %1' % { sd }) displayNl.</syntaxhighlight> |
||
=={{header|SQL}}== |
=={{header|SQL}}== |
||
{{works with|Postgresql}} |
{{works with|Postgresql}} |
||
< |
<syntaxhighlight lang="sql">-- the minimal table |
||
create table if not exists teststd (n double precision not null); |
create table if not exists teststd (n double precision not null); |
||
Line 4,146: | Line 4,146: | ||
-- cleanup test data |
-- cleanup test data |
||
delete from teststd; |
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) |
With a command like '''psql <rosetta-std-dev.sql''' you will get an output like this: (duplicate lines generously deleted, locale is DE) |
||
<pre> |
<pre> |
||
Line 4,172: | Line 4,172: | ||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
< |
<syntaxhighlight lang="swift">import Darwin |
||
class stdDev{ |
class stdDev{ |
||
Line 4,199: | Line 4,199: | ||
} |
} |
||
var aa = stdDev()</ |
var aa = stdDev()</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 4,214: | Line 4,214: | ||
Functional: |
Functional: |
||
<syntaxhighlight lang="swift"> |
|||
<lang Swift> |
|||
func standardDeviation(arr : [Double]) -> Double |
func standardDeviation(arr : [Double]) -> Double |
||
{ |
{ |
||
Line 4,227: | Line 4,227: | ||
standardDeviation(responseTimes) // 20.8742514835862 |
standardDeviation(responseTimes) // 20.8742514835862 |
||
standardDeviation([2,4,4,4,5,5,7,9]) // 2.0 |
standardDeviation([2,4,4,4,5,5,7,9]) // 2.0 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
===With a Class=== |
===With a Class=== |
||
{{works with|Tcl|8.6}} or {{libheader|TclOO}} |
{{works with|Tcl|8.6}} or {{libheader|TclOO}} |
||
< |
<syntaxhighlight lang="tcl">oo::class create SDAccum { |
||
variable sum sum2 num |
variable sum sum2 num |
||
constructor {} { |
constructor {} { |
||
Line 4,264: | Line 4,264: | ||
set sd [$sdacc value $val] |
set sd [$sdacc value $val] |
||
} |
} |
||
puts "the standard deviation is: $sd"</ |
puts "the standard deviation is: $sd"</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>the standard deviation is: 2.0</pre> |
<pre>the standard deviation is: 2.0</pre> |
||
Line 4,270: | Line 4,270: | ||
===With a Coroutine=== |
===With a Coroutine=== |
||
{{works with|Tcl|8.6}} |
{{works with|Tcl|8.6}} |
||
< |
<syntaxhighlight lang="tcl"># Make a coroutine out of a lambda application |
||
coroutine sd apply {{} { |
coroutine sd apply {{} { |
||
set sum 0.0 |
set sum 0.0 |
||
Line 4,289: | Line 4,289: | ||
} |
} |
||
sd stop |
sd stop |
||
puts "the standard deviation is: $sd"</ |
puts "the standard deviation is: $sd"</syntaxhighlight> |
||
[[Category:Stateful transactions]] |
[[Category:Stateful transactions]] |
||
Line 4,303: | Line 4,303: | ||
=={{header|VBScript}}== |
=={{header|VBScript}}== |
||
< |
<syntaxhighlight lang="vb">data = Array(2,4,4,4,5,5,7,9) |
||
For i = 0 To UBound(data) |
For i = 0 To UBound(data) |
||
Line 4,323: | Line 4,323: | ||
variance = variance/(n+1) |
variance = variance/(n+1) |
||
sd = FormatNumber(Sqr(variance),6) |
sd = FormatNumber(Sqr(variance),6) |
||
End Function</ |
End Function</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 4,341: | Line 4,341: | ||
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. |
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. |
||
< |
<syntaxhighlight lang="vb">Function avg(what() As Variant) As Variant |
||
'treats non-numeric strings as zero |
'treats non-numeric strings as zero |
||
Dim L0 As Variant, total As Variant |
Dim L0 As Variant, total As Variant |
||
Line 4,390: | Line 4,390: | ||
Debug.Print standardDeviation(x(L0)) |
Debug.Print standardDeviation(x(L0)) |
||
Next |
Next |
||
End Sub</ |
End Sub</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,407: | Line 4,407: | ||
{{libheader|Wren-fmt}} |
{{libheader|Wren-fmt}} |
||
{{libheader|Wren-math}} |
{{libheader|Wren-math}} |
||
< |
<syntaxhighlight lang="ecmascript">import "/fmt" for Fmt |
||
import "/math" for Nums |
import "/math" for Nums |
||
Line 4,423: | Line 4,423: | ||
if (cumStdDev.isDone) return |
if (cumStdDev.isDone) return |
||
System.print("Std Dev : %(Fmt.f(10, sd, 8))\n") |
System.print("Std Dev : %(Fmt.f(10, sd, 8))\n") |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,453: | Line 4,453: | ||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations |
||
int A, I; |
int A, I; |
||
real N, S, S2; |
real N, S, S2; |
||
Line 4,465: | Line 4,465: | ||
]; |
]; |
||
CrLf(0); |
CrLf(0); |
||
]</ |
]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,473: | Line 4,473: | ||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
< |
<syntaxhighlight lang="zkl">fcn sdf{ fcn(x,xs){ |
||
m:=xs.append(x.toFloat()).sum(0.0)/xs.len(); |
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() |
(xs.reduce('wrap(p,x){(x-m)*(x-m) +p},0.0)/xs.len()).sqrt() |
||
}.fp1(L()) |
}.fp1(L()) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |