]> gitweb.factorcode.org Git - factor.git/blob - extra/rosetta-code/standard-deviation/standard-deviation.factor
Switch to https urls
[factor.git] / extra / rosetta-code / standard-deviation / standard-deviation.factor
1 ! Copyright (c) 2012 Anonymous
2 ! See https://factorcode.org/license.txt for BSD license.
3 USING: accessors io kernel math math.functions math.parser
4 sequences ;
5 IN: rosetta-code.standard-deviation
6
7 ! https://rosettacode.org/wiki/Standard_deviation
8
9 ! Write a stateful function, class, generator or coroutine that
10 ! takes a series of floating point numbers, one at a time, and
11 ! returns the running standard deviation of the series. The task
12 ! implementation should use the most natural programming style of
13 ! those listed for the function in the implementation language;
14 ! the task must state which is being used. Do not apply Bessel's
15 ! correction; the returned standard deviation should always be
16 ! computed as if the sample seen so far is the entire population.
17
18 ! Use this to compute the standard deviation of this
19 ! demonstration set, {2,4,4,4,5,5,7,9}, which is 2.
20
21 TUPLE: standard-deviator sum sum^2 n ;
22
23 : <standard-deviator> ( -- standard-deviator )
24     0.0 0.0 0 standard-deviator boa ;
25
26 : current-std ( standard-deviator -- std )
27     [ [ sum^2>> ] [ n>> ] bi / ]
28     [ [ sum>> ] [ n>> ] bi / sq ] bi - sqrt ;
29
30 : add-value ( value standard-deviator -- )
31     [ nip [ 1 + ] change-n drop ]
32     [ [ + ] change-sum drop ]
33     [ [ [ sq ] dip + ] change-sum^2 drop ] 2tri ;
34
35 : std-main ( -- )
36     { 2 4 4 4 5 5 7 9 }
37     <standard-deviator> [ [ add-value ] curry each ] keep
38     current-std number>string print ;