user
Task

Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, *one at a time*, and returns the running standard deviation of the series.

The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task *must* state which is being used.

Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.

Test case

Use this to compute the standard deviation of this demonstration set, 

{
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
}
{\displaystyle {\displaystyle \{2,4,4,4,5,5,7,9\}}}
, which is 

2
{\displaystyle {\displaystyle 2}}
.

Related tasks

* Random numbers

|  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| | Tasks for calculating statistical measures | | | --- | --- | |  | | |  |  |  |  |  | | --- | --- | --- | --- | --- | |  | | in one go | moving *(sliding window)* | moving *(cumulative)* | | Mean | Arithmetic | Statistics/Basic  Averages/Arithmetic mean  Averages/Pythagorean means | Averages/Simple moving average |  | | Geometric | Averages/Pythagorean means |  |  | | Harmonic | Averages/Pythagorean means |  |  | | Quadratic | Averages/Root mean square |  |  | | Circular | Averages/Mean angle  Averages/Mean time of day |  |  | | Median | | Averages/Median |  |  | | Mode | | Averages/Mode |  |  | | Standard deviation | | Statistics/Basic |  | Cumulative standard deviation | | | |

---
assistant
(formerly Perl 6)

Using a closure:

```
sub sd (@a) {
    my $mean = @a R/ [+] @a;
    sqrt @a R/ [+] map (* - $mean)², @a;
}
 
sub sdaccum {
    my @a;
    return { push @a, $^x; sd @a; };
}
 
my &f = sdaccum;
say f $_ for 2, 4, 4, 4, 5, 5, 7, 9;

```

Using a state variable (remember that <(x-<x>)²> = <x²> - <x>²):

```
sub stddev($x) {
    sqrt
        ( .[2] += $x²) / ++.[0]
      - ((.[1] += $x ) /   .[0])²
    given state @;
}

say .&stddev for <2 4 4 4 5 5 7 9>;

```

Output:

```
0
1
0.942809041582063
0.866025403784439
0.979795897113271
1
1.39970842444753
2
```