Cumulative standard deviation: Difference between revisions
m
→{{header|Wren}}: Minor tidy
(Emacs Lisp: Improve solutions) |
m (→{{header|Wren}}: Minor tidy) |
||
(11 intermediate revisions by 7 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 169:
{{libheader|Action! Tool Kit}}
{{libheader|Action! Real Math}}
<
REAL sum,sum2
Line 214:
Print(" sd=") PrintRE(sd)
OD
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Cumulative_standard_deviation.png Screenshot from Atari 8-bit computer]
Line 229:
=={{header|Ada}}==
<
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;
Line 265:
end loop;
end Test_Deviation;
</syntaxhighlight>
{{out}}
<pre>
Line 287:
<!-- {{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8.8d.fc9.i386]}} -->
Note: the use of a UNION to mimic C's enumerated types is "experimental" and probably not typical of "production code". However it is a example of '''ALGOL 68'''s ''conformity CASE clause'' useful for classroom dissection.
<
STDDEV = STRUCT(CHAR stddev),
MEAN = STRUCT(CHAR mean),
Line 338:
OD
)</
{{out}}
<pre>
Line 357:
A code sample in an object oriented style:
<
LONG REAL sum,
LONG REAL sum2,
Line 432:
)
</syntaxhighlight>
{{out}}
<pre>
Line 451:
A simple - but "unpackaged" - code example, useful if the standard deviation is required on only one set of concurrent data:
<
INT n;
Line 466:
LONG REAL value = values[i];
printf(($2(xg(0,6))l$, value, sd(value)))
OD</
{{out}}
<pre>
Line 482:
{{Trans|ALGOL 68}}
This is an Algol W version of the third, "unpackaged" Algol 68 sample, which was itself translated from Python.
<
long real sum, sum2;
Line 506:
end for_i
end.</
{{out}}
<pre>
Line 523:
Accumulation over a fold:
<
-- stdDevInc :: Accumulator -> Num -> Index -> Accumulator
Line 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 652:
end script
end if
end mReturn</
{{Out}}
Line 659:
=={{header|Arturo}}==
<
loop [2 4 4 4 5 5 7 9] 'value [
'arr ++ value
print [value "->" deviation arr]
]</
{{out}}
Line 677:
=={{header|AutoHotkey}}==
<
for k, v in Data {
Line 691:
return sqrt((sum2/n) - (((sum*sum)/n)/n))
}</
{{out}}
<pre>
Line 705:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f STANDARD_DEVIATION.AWK
BEGIN {
Line 725:
return(sqrt(variance))
}
</syntaxhighlight>
{{out}}
<pre>
Line 740:
=={{header|Axiom}}==
{{incorrect|Axiom|It does not return the ''running'' standard deviation of the series.}}
We implement a domain with dependent type T with the operation + and identity 0:<
TestDomain(T : Join(Field,RadicalCategory)): Exports == Implementation where
R ==> Record(n : Integer, sum : T, ssq : T)
Line 756:
sd obj ==
mean : T := obj.sum / (obj.n::T)
sqrt(obj.ssq / (obj.n::T) - mean*mean)</
D ==> TestDomain(T)
items := [2,4,4,4,5,5,7,9+x] :: List T;
Line 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 788:
i% += 1
list(i%) = n
= SQR(MOD(list())^2/i% - (SUM(list())/i%)^2)</
{{out}}
<pre>
Line 803:
=={{header|C}}==
<
#include <stdlib.h>
#include <math.h>
Line 850:
so->sum2 += v*v;
return stat_obj_value(so, so->action);
}</
<
int main()
Line 864:
FREE_STAT_OBJECT(so);
return 0;
}</
=={{header|C sharp|C#}}==
<
using System.Collections.Generic;
using System.Linq;
Line 891:
}
}
}</
<pre>0
1
Line 903:
=={{header|C++}}==
No attempt to handle different types -- standard deviation is intrinsically a real number.
<
#include <
#include <cmath>
#include <vector>
Line 943:
}
}
</syntaxhighlight>
=={{header|Clojure}}==
<
(defn stateful-std-deviation[x]
(letfn [(std-dev[x]
Line 957:
(intern *ns* 'v (atom [])))
(std-dev x)))
</syntaxhighlight>
=={{header|COBOL}}==
{{works with|OpenCOBOL|1.1}}
<
PROGRAM-ID. run-stddev.
environment division.
Line 1,033:
goback.
end program stddev.
</syntaxhighlight>
<
inp=002 stddev=+00000.0000
inp=004 stddev=+00001.0000
Line 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 1,076:
"""
</syntaxhighlight>
{{out}}
Line 1,106:
=={{header|Common Lisp}}==
Since we don't care about the sample values once std dev is computed, we only need to keep track of their sum and square sums, hence:<
(let ((sum 0) (sq 0) (n 0))
(lambda (x)
Line 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,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,192:
END Do;
END StandardDeviation.
</syntaxhighlight>
Execute: ^Q StandardDeviation.Do 2 4 4 4 5 5 7 9 ~<br/>
{{out}}
Line 1,210:
Use an object to keep state.
{{trans|Ruby}}
<
def initialize
@n, @sum, @sum2 = 0, 0.0, 0.0
Line 1,225:
sd = StdDevAccumulator.new
i = 0
[2,4,4,4,5,5,7,9].each { |n| puts "adding #{n}: stddev of #{i+=1} samples is #{sd << n}" }</
{{out}}
<pre>
Line 1,240:
===Closure===
{{trans|Ruby}}
<
n, sum, sum2 = 0, 0.0, 0.0
->(num : Int32) do
Line 1,251:
sd = sdaccum
[2,4,4,4,5,5,7,9].each {|n| print sd.call(n), ", "}</
{{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,283:
writefln("%e", stdev.getStdDev());
}
}</
{{out}}
<pre>0.000000e+00
Line 1,305:
The algorithm is {{trans|Perl}} and the results were checked against [[#Python]].
<
var sum := 0.0
var sumSquares := 0.0
Line 1,328:
return [insert, stddev]
}</
<
# value: <insert>, <stddev>
Line 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,393 ⟶ 1,410:
end
Standard_deviation.task</
{{out}}
Line 1,409 ⟶ 1,426:
=={{header|Emacs Lisp}}==
<
(let ((running-sum 0)
(running-len 0)
Line 1,424 ⟶ 1,441:
result))
(running-std '(2 4 4 4 5 5 7 9))</
{{out}}
Line 1,440 ⟶ 1,457:
{{libheader|Calc}}
<
(string-to-number (calc-eval "sqrt(vpvar($1))" nil (append '(vec) x))))</
{{libheader|generator.el}}
<
(require 'generator)
Line 1,468 ⟶ 1,485:
(generator (std-dev-gen test-data)))
(dolist (i test-data)
(message "with %d: %f" i (iter-next generator))))</
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
-module( standard_deviation ).
Line 1,511 ⟶ 1,528:
loop_calculate_average( Ns ) -> lists:sum( Ns ) / erlang:length( Ns ).
</syntaxhighlight>
{{out}}
<pre>
Line 1,526 ⟶ 1,543:
=={{header|Factor}}==
<
sequences ;
IN: standard-deviator
Line 1,547 ⟶ 1,564:
{ 2 4 4 4 5 5 7 9 }
<standard-deviator> [ [ add-value ] curry each ] keep
current-std number>string print ;</
=={{header|FOCAL}}==
<
01.10 S T(1)=2;S T(2)=4;S T(3)=4;S T(4)=4
01.20 S T(5)=5;S T(6)=5;S T(7)=7;S T(8)=9
Line 1,564 ⟶ 1,581:
02.10 S XN=0;S XS=0;S XQ=0
02.20 S XN=XN+1;S XS=XS+A;S XQ=XQ+A*A
02.30 S A=FSQT(XQ/XN - (XS/XN)^2)</
{{out}}
Line 1,579 ⟶ 1,596:
=={{header|Forth}}==
<
: st-count ( stats -- n ) f@ ;
Line 1,601 ⟶ 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,621 ⟶ 1,638:
( delta x )
dup f@ f- f* float+ f+! \ update nvar
st-stddev ;</
Usage example:
<
2e stats st-add f. \ 0.
Line 1,633 ⟶ 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,687 ⟶ 1,704:
end function stddev
end program standard_deviation
</syntaxhighlight>
{{out}}
<pre>
Line 1,708 ⟶ 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,783 ⟶ 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,862 ⟶ 1,879:
=={{header|FreeBASIC}}==
<
Function calcStandardDeviation(number As Double) As Double
Line 1,891 ⟶ 1,908:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 1,909 ⟶ 1,926:
State maintained with a closure.
<
import (
Line 1,931 ⟶ 1,948:
fmt.Println(r(x))
}
}</
{{out}}
<pre>
Line 1,946 ⟶ 1,963:
=={{header|Groovy}}==
Solution:
<
def stdDev = { def sample ->
Line 1,958 ⟶ 1,975:
[2,4,4,4,5,5,7,9].each {
println "${stdDev(it)}"
}</
{{out}}
Line 1,974 ⟶ 1,991:
We store the state in the <code>ST</code> monad using an <code>STRef</code>.
<
import Data.List (foldl') -- '
Line 2,001 ⟶ 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:
<
Line 2,023 ⟶ 2,040:
--------------------------- TEST -------------------------
main :: IO ()
main = mapM_ print $ cumulativeStdDevns [2, 4, 4, 4, 5, 5, 7, 9]</
{{Out}}
<pre>0.0
Line 2,035 ⟶ 2,052:
=={{header|Haxe}}==
<
class Main {
Line 2,057 ⟶ 2,074:
return Math.sqrt(average(store));
}
}</
<pre>0
1
Line 2,068 ⟶ 2,085:
=={{header|HicEst}}==
<
set = (2,4,4,4,5,5,7,9)
Line 2,083 ⟶ 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 2,094 ⟶ 2,111:
=={{header|Icon}} and {{header|Unicon}}==
<
stddev() # reset state / empty
Line 2,115 ⟶ 2,132:
return sqrt( (sum2X / *X) - (sumX / *X)^2 )
}
end</
{{out}}
<pre>stddev (so far) := 0.0
Line 2,127 ⟶ 2,144:
=={{header|IS-BASIC}}==
<
110 LET N=8
120 NUMERIC ARR(1 TO N)
Line 2,143 ⟶ 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,156 ⟶ 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,170 ⟶ 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,201 ⟶ 2,218:
}
}
}</
=={{header|JavaScript}}==
Line 2,208 ⟶ 2,225:
Uses a closure.
<
var n = 0;
var sum = 0.0;
Line 2,227 ⟶ 2,244:
// using WSH
WScript.Echo(stddev.join(', ');</
{{out}}
Line 2,236 ⟶ 2,253:
Accumulating across a fold
<
return xs.reduce(function (a, x, i) {
Line 2,257 ⟶ 2,274:
}).stages
})([2, 4, 4, 4, 5, 5, 7, 9]);</
{{Out}}
<
0.9797958971132716, 1, 1.3997084244475297, 2]</
====ES6====
As a map-accumulation:
<
'use strict';
Line 2,320 ⟶ 2,337:
// MAIN ---
return main();
})();</
{{Out}}
<pre>[
Line 2,349 ⟶ 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,374 ⟶ 2,391:
# Begin:
simulate</
'''Example 1'''
# observations.txt
Line 2,386 ⟶ 2,403:
9
{{Out}}
<syntaxhighlight lang="sh">
$ jq -s -f Dynamic_standard_deviation.jq observations.txt
0
Line 2,396 ⟶ 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,423 ⟶ 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,460 ⟶ 2,477:
sed -n 1p <<< "$result"
state=$(sed -n 2p <<< "$result")
done</
'''Example 3'''
<
Next observation: 10
0
Line 2,469 ⟶ 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,492 ⟶ 2,509:
for i in test
println(" - add $i → ", rstd(i))
end</
{{out}}
Line 2,509 ⟶ 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,528 ⟶ 2,545:
val csd = CumStdDev()
for (d in testData) println("Add $d => ${csd.sd(d)}")
}</
{{out}}
Line 2,544 ⟶ 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,571 ⟶ 2,588:
Data 2, 4, 4, 4, 5, 5, 7, 9
</syntaxhighlight>
<pre>
New data 2 so S.D. now = 0.000000
Line 2,584 ⟶ 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,613 ⟶ 2,630:
test_stdv()
</syntaxhighlight>
{{out}}
<pre>
Line 2,621 ⟶ 2,638:
=={{header|Lua}}==
Uses a closure. Translation of JavaScript.
<
local sum, sumsq, k = 0,0,0
return function(n)
Line 2,632 ⟶ 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,646 ⟶ 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,657 ⟶ 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,687 ⟶ 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,700 ⟶ 2,717:
=={{header|Nanoquery}}==
{{trans|Java}}
<
declare n
declare sum
Line 2,725 ⟶ 2,742:
for x in testData
println sd.sd(x)
end</
{{out}}
Line 2,740 ⟶ 2,757:
===Using global variables===
<
var sdSum, sdSum2, sdN = 0.0
Line 2,751 ⟶ 2,768:
for value in [float 2,4,4,4,5,5,7,9]:
echo value, " ", formatFloat(sd(value), precision = -1)</
{{out}}
Line 2,764 ⟶ 2,781:
===Using an accumulator object===
<
type SDAccum = object
Line 2,779 ⟶ 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,785 ⟶ 2,802:
===Using a closure===
<
func accumBuilder(): auto =
Line 2,799 ⟶ 2,816:
for value in [float 2, 4, 4, 4, 5, 5, 7, 9]:
echo value, " ", formatFloat(std(value), precision = -1)</
{{out}}
Line 2,806 ⟶ 2,823:
=={{header|Objeck}}==
{{trans|Java}}
<
use Structure;
Line 2,842 ⟶ 2,859:
}
}
</syntaxhighlight>
=={{header|Objective-C}}==
<
@interface SDAccum : NSObject
Line 2,899 ⟶ 2,916:
}
return 0;
}</
===Blocks===
Line 2,905 ⟶ 2,922:
{{works with|iOS|4+}}
<
typedef double (^Func)(double); // a block that takes a double and returns a double
Line 2,934 ⟶ 2,951:
}
return 0;
}</
=={{header|OCaml}}==
<
let stddev l =
Line 2,951 ⟶ 2,968:
Printf.printf "List: ";
List.iter (Printf.printf "%g ") l;
Printf.printf "\nStandard deviation: %g\n" (stddev l)</
{{out}}
Line 2,965 ⟶ 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,989 ⟶ 3,006:
=={{header|ooRexx}}==
{{works with|oorexx}}
<
x = .array~of(2,4,4,4,5,5,7,9)
sd = 0
Line 3,030 ⟶ 3,047:
ans = ( prev + ( n / prev ) ) / 2
end
return ans</
{{out}}
<pre>#1 value = 2 stdev = 0
Line 3,043 ⟶ 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 3,061 ⟶ 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 3,093 ⟶ 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 3,104 ⟶ 3,121:
8 item= 9 stddev= 2.000000000000000</pre>
==={{header|Delphi}}===
<
{$APPTYPE CONSOLE}
Line 3,134 ⟶ 3,151:
end;
Readln;
end. </
{{out}}
<pre>
Line 3,148 ⟶ 3,165:
=={{header|Perl}}==
<
package SDAccum;
sub new {
Line 3,184 ⟶ 3,201:
return $self->stddev;
}
}</
<
my $sd;
Line 3,192 ⟶ 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,209 ⟶ 3,226:
}
print stddev($_), "\n" for qw(2 4 4 4 5 5 7 9);</
{{out}}
Line 3,222 ⟶ 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,245 ⟶ 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.
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
Line 3,272 ⟶ 3,289:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"N=%d Item=%d Avg=%5.3f StdDev=%5.3f\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ti</span><span style="color: #0000FF;">,</span><span style="color: #000000;">sdavg</span><span style="color: #0000FF;">(),</span><span style="color: #000000;">sddev</span><span style="color: #0000FF;">()})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</
{{out}}
<pre>
Line 3,287 ⟶ 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,317 ⟶ 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,332 ⟶ 3,349:
=={{header|PicoLisp}}==
<
(de stdDev ()
Line 3,349 ⟶ 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,361 ⟶ 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,385 ⟶ 3,402:
end std_dev;
end;</
{{out}}
<pre>AVERAGE= 5.50000E+0000;
Line 3,393 ⟶ 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,405 ⟶ 3,422:
[Math]::Sqrt($sum / $nums.Length)
}
}</
Usage as follows:
<pre>PS> 2,4,4,4,5,5,7,9 | Get-StandardDeviation
Line 3,418 ⟶ 3,435:
=={{header|PureBasic}}==
<
Declare.d Standard_deviation(x)
Line 3,446 ⟶ 3,463:
MyList:
Data.i 2,4,4,4,5,5,7,9
EndDataSection</
{{out}}
Line 3,464 ⟶ 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,485 ⟶ 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,500 ⟶ 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,507 ⟶ 3,524:
===Python: Using a Closure===
{{Works with|Python|3.x}}
<
>>> def sdcreator():
sum = sum2 = n = 0
Line 3,531 ⟶ 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,558 ⟶ 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) {
n <- seq_along(x)
sqrt(cumsum(x^2) / n - (cumsum(x) / n)^2)
}
set.seed(12345L)
x <- rnorm(10)
cumsd(x)
# [1] 0.0000000 0.3380816 0.8752973 1.1783628 1.2345538 1.3757142 1.2867220 1.2229056 1.1665168 1.1096814
# Compare to the naive implementation, i.e. compute sd on each sublist:
Vectorize(function(k) sd(x[1:k]) * sqrt((k - 1) / k))(seq_along(x))
# [1] NA 0.3380816 0.8752973 1.1783628 1.2345538 1.3757142 1.2867220 1.2229056 1.1665168 1.1096814
# Note that the first is NA because sd is unbiased formula, hence there is a division by n-1, which is 0 for n=1.</syntaxhighlight>
The task requires an accumulator solution:
<syntaxhighlight lang="rsplus">accumsd <- function() {
n <- 0
m <- 0
s <- 0
function(x) {
n <<- n + 1
m <<- m + x
s <<- s + x * x
sqrt(s / n - (m / n)^2)
}
}
f <- accumsd()
sapply(x, f)
# [1] 0.0000000 0.3380816 0.8752973 1.1783628 1.2345538 1.3757142 1.2867220 1.2229056 1.1665168 1.1096814</syntaxhighlight>
=={{header|Racket}}==
<
#lang racket
(require math)
Line 3,647 ⟶ 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,664 ⟶ 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,690 ⟶ 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,708 ⟶ 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,723 ⟶ 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,739 ⟶ 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,746 ⟶ 3,734:
=={{header|Ring}}==
<
# Project : Cumulative standard deviation
Line 3,764 ⟶ 3,752:
see "" + num + " value in = " + stddata + " Stand Dev = " + standdev + nl
next
</syntaxhighlight>
Output:
<pre>
Line 3,775 ⟶ 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,783 ⟶ 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,807 ⟶ 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,819 ⟶ 3,827:
=== Closure ===
<
n, sum, sum2 = 0, 0.0, 0.0
lambda do |num|
Line 3,830 ⟶ 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,850 ⟶ 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,863 ⟶ 3,871:
Using a struct:
{{trans|Java}}
<
n: f64,
sum: f64,
Line 3,894 ⟶ 3,902:
println!("{}", cum_stdev.push(*num as f64));
}
}</
{{out}}
<pre>
Line 3,908 ⟶ 3,916:
Using a closure:
<
let mut n = 0.0;
let mut sum = 0.0;
Line 3,927 ⟶ 3,935:
println!("{}", sd_acc(*num as f64));
}
}</
{{out}}
<pre>
Line 3,941 ⟶ 3,949:
=={{header|SAS}}==
<syntaxhighlight lang="sas">
*--Load the test data;
data test1;
Line 3,974 ⟶ 3,982:
var n sd /*mean*/;
run;
</syntaxhighlight>
{{out}}
Line 3,993 ⟶ 4,001:
===Generic for any numeric type===
{{libheader|Scala}}
<
object StddevCalc extends App {
Line 4,018 ⟶ 4,026:
println(s"Successfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart}ms]")
}</
=={{header|Scheme}}==
<
(define (standart-deviation-generator)
(let ((nums '()))
Line 4,033 ⟶ 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 4,051 ⟶ 4,058:
=={{header|Sidef}}==
Using an object to keep state:
<
method <<(num) {
n += 1
Line 4,072 ⟶ 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 4,086 ⟶ 4,093:
Using ''static'' variables:
<
static(num=0, sum=0, sum2=0)
num++
Line 4,095 ⟶ 4,102:
}
%n(2 4 4 4 5 5 7 9).each { say stddev(_) }</
{{out}}
<pre>
Line 4,111 ⟶ 4,118:
{{works with|GNU Smalltalk}}
<
|sum sum2 num|
SDAccum class >> new [ |o|
Line 4,130 ⟶ 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,174 ⟶ 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,200 ⟶ 4,207:
=={{header|Swift}}==
<
class stdDev{
Line 4,227 ⟶ 4,234:
}
var aa = stdDev()</
{{out}}
<pre>
Line 4,242 ⟶ 4,249:
Functional:
<syntaxhighlight lang="swift">
func standardDeviation(arr : [Double]) -> Double
{
Line 4,255 ⟶ 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,292 ⟶ 4,299:
set sd [$sdacc value $val]
}
puts "the standard deviation is: $sd"</
{{out}}
<pre>the standard deviation is: 2.0</pre>
Line 4,298 ⟶ 4,305:
===With a Coroutine===
{{works with|Tcl|8.6}}
<
coroutine sd apply {{} {
set sum 0.0
Line 4,317 ⟶ 4,324:
}
sd stop
puts "the standard deviation is: $sd"</
[[Category:Stateful transactions]]
Line 4,331 ⟶ 4,338:
=={{header|VBScript}}==
<
For i = 0 To UBound(data)
Line 4,351 ⟶ 4,358:
variance = variance/(n+1)
sd = FormatNumber(Sqr(variance),6)
End Function</
{{Out}}
Line 4,369 ⟶ 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,418 ⟶ 4,425:
Debug.Print standardDeviation(x(L0))
Next
End Sub</
{{out}}
Line 4,435 ⟶ 4,442:
{{libheader|Wren-fmt}}
{{libheader|Wren-math}}
<
import "./math" for Nums
var cumStdDev = Fiber.new { |a|
Line 4,450 ⟶ 4,457:
var sd = cumStdDev.call(a)
if (cumStdDev.isDone) return
}</
{{out}}
Line 4,481 ⟶ 4,488:
=={{header|XPL0}}==
<
int A, I;
real N, S, S2;
Line 4,493 ⟶ 4,500:
];
CrLf(0);
]</
{{out}}
Line 4,501 ⟶ 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>
|