Cumulative standard deviation: Difference between revisions

→‎{{header|Haskell}}: Switched foldl version to a more natural expression in terms of mapAccumL
m (→‎{{header|AppleScript}}: Updated primitives)
(→‎{{header|Haskell}}: Switched foldl version to a more natural expression in terms of mapAccumL)
Line 1,828:
 
 
Or, as a map-accumulation over an indexed list
Or, simply accumulating across a fold:
{{Trans|AppleScript}}
 
<lang Haskell>typeimport IndexData.List = Int(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
_s =go (s, +q) (i, x) =
_q let _s = qs + (x ^ 2)
_i _q = fromIntegralq + (x ^ i2)
_ds = ds ++ [sqrt ((_q / _i) - ((_s / _i)= ^fromIntegral 2))]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 = mapM_ print devns$ cumulativeStdDevns [2, 4, 4, 4, 5, 5, 7, 9]</lang>
where
(_, _, devns) = foldl_ stdDevInc (0, 0, []) $ zip sample [1 .. ]</lang>
{{Out}}
<pre>0.0
9,655

edits