Cumulative standard deviation: Difference between revisions

→‎{{header|Forth}}: Fixed to return the running standard deviation
(→‎{{header|Forth}}: Fixed to return the running standard deviation)
Line 1,152:
 
=={{header|Forth}}==
{{incorrect|Forth|It does not return the ''running'' standard deviation of the series.}}
<lang forth>: f+! ( x addr -- ) dup f@ f+ f! ;
 
Line 1,158 ⟶ 1,157:
: st-sum ( stats -- sum ) float+ f@ ;
: st-sumsq ( stats -- sum*sum ) 2 floats + f@ ;
 
: st-add ( fnum stats -- )
1e dup f+! float+
fdup dup f+! float+
fdup f* f+! ;
 
: st-mean ( stats -- mean )
Line 1,173 ⟶ 1,167:
 
: st-stddev ( stats -- stddev )
st-variance fsqrt ;</lang>
 
: st-add ( fnum stats -- )
dup
1e dup f+! float+
fdup dup f+! float+
fdup f* f+! ;
stats st std-stddev f. \ 2.;</lang>
 
This variation is more numerically stable when there are large numbers of samples or large sample ranges.
<lang forth>: st-count ( stats -- n ) f@ ;
Line 1,183 ⟶ 1,185:
 
: st-add ( x stats -- )
dup
1e dup f+! \ update count
fdup dup st-mean f- fswap
Line 1,190 ⟶ 1,193:
float+ dup f+! \ update mean
( delta x )
dup f@ f- f* float+ f+! ; \ update nvar</lang>
st-stddev ;</lang>
Usage example:
<lang forth>create stats 0e f, 0e f, 0e f,
 
2e stats st-add f. \ 0.
4e stats st-add f. \ 1.
4e stats st-add f. \ 0.942809041582063
4e stats st-add f. \ 0.866025403784439
5e stats st-add f. \ 0.979795897113271
5e stats st-add f. \ 1.
7e stats st-add f. \ 1.39970842444753
9e stats st-add f. \ 2.
</lang>
 
stats st-stddev f. \ 2.</lang>
 
=={{header|Fortran}}==