> module NumericUtilities
> (average,
> correlation,
> digitize,
> standardDeviation,
> standardDeviationUnbiased,
> nudge)
> where
> import VectorOperations(innerProduct, norm)
n-way analog-to-digital converter for a <= x < b
> digitize:: RealFrac num => Int -> num -> num -> num -> Int
> digitize n a b x
> | xDist < halfstep = 0 -- avoid boundary glitches
> | xDist > lastHalfstep = n
> | otherwise = floor(xDist/dx)
> where
> xDist = x - a
> dx = span/(fromIntegral n)
> halfstep = dx/2
> lastHalfstep = span - halfstep
> span = b - a
increase magnitude by an almost negligible amount
> nudge :: RealFrac num => num -> num
> nudge x = (last . takeWhile(/= x) . take 100 .
> map (x+) . iterate (/2)) x
arithmetic mean
> average :: Fractional num => [num] -> num
> average = foldl includeAnotherSample 0 . zip[1 ..]
> where
> includeAnotherSample runningAverage (sampleNumber, sample) =
> runningAverage + (sample - runningAverage)/fromRealFrac sampleNumber
standard deviation
> standardDeviation :: Floating num => [num] -> num
> standardDeviation samples =
> (sqrt . average . map deviationSquared) samples
> where
> mu = average samples
> deviationSquared x = abs(x - mu)^2
standard deviation - unbiased estimate
> standardDeviationUnbiased :: Floating num => [num] -> num
> standardDeviationUnbiased samples =
> (standardDeviation samples)*((fromIntegral n)/fromIntegral(n - 1))
> where
> n = length samples
correlation
> correlation :: RealFloat num => [num] -> [num] -> num
> correlation xs ys = innerProduct xs ys / (norm xs * norm ys)