Cumulative standard deviation: Difference between revisions
Content added Content deleted
m (→{{header|AppleScript}}: Updated primitives) |
(→{{header|Haskell}}: Switched foldl version to a more natural expression in terms of mapAccumL) |
||
Line 1,828: | Line 1,828: | ||
Or, as a map-accumulation over an indexed list |
|||
Or, simply accumulating across a fold: |
|||
{{Trans|AppleScript}} |
|||
<lang Haskell> |
<lang Haskell>import Data.List (mapAccumL) |
||
type DataPoint = Float |
|||
-------------- CUMULATIVE STANDARD DEVIATION ------------- |
|||
type Sum = Float |
|||
cumulativeStdDevns :: [Float] -> [Float] |
|||
type SumOfSquares = Float |
|||
cumulativeStdDevns xs = snd $ mapAccumL go (0, 0) $ zip [1 ..] xs |
|||
type Deviations = [Float] |
|||
type Accumulator = (Sum, SumOfSquares, Deviations) |
|||
stdDevInc :: Accumulator -> (DataPoint, Index) -> Accumulator |
|||
stdDevInc (s, q, ds) (x, i) = (_s, _q, _ds) |
|||
where |
where |
||
go (s, q) (i, x) = |
|||
let _s = s + x |
|||
_q = q + (x ^ 2) |
|||
_i = fromIntegral i |
|||
in ((_s, _q), sqrt ((_q / _i) - ((_s / _i) ^ 2))) |
|||
sample :: [DataPoint] |
|||
sample = [2, 4, 4, 4, 5, 5, 7, 9] |
|||
-- The Prelude definition of foldl' --' |
|||
--------------------------- TEST ------------------------- |
|||
-- adjusted to avoid wiki formatting glitches. |
|||
foldl_ :: Foldable t => (b -> a -> b) -> b -> t a -> b |
|||
foldl_ f z0 xs = foldr f_ id xs z0 |
|||
where f_ x k z = k $! f z x |
|||
main :: IO () |
main :: IO () |
||
main = mapM_ print |
main = mapM_ print $ cumulativeStdDevns [2, 4, 4, 4, 5, 5, 7, 9]</lang> |
||
where |
|||
(_, _, devns) = foldl_ stdDevInc (0, 0, []) $ zip sample [1 .. ]</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre>0.0 |
<pre>0.0 |