commit 952dc91af3fa62c50b9d3ca1379d5b3727c0e2f5
parent 35b056093e0b817dd0a7240416ce07b51287f5e1
Author: Jared Tobin <jared@jtobin.ca>
Date: Sat, 19 Oct 2013 21:15:13 +1300
Add 'to', 'cdf'.
Diffstat:
2 files changed, 46 insertions(+), 3 deletions(-)
diff --git a/src/Measurable.hs b/src/Measurable.hs
@@ -110,3 +110,32 @@ weightedAverage :: Fractional c => (a -> c) -> [a] -> c
weightedAverage f = average . map f
{-# INLINE weightedAverage #-}
+-- | Integrate from a to b.
+to :: (Num a, Ord a) => a -> a -> a -> a
+to a b x | x >= a && x <= b = 1
+ | otherwise = 0
+
+-- | Cumulative distribution function for a measure.
+--
+-- Really cool; works perfectly in both discrete and continuous cases.
+--
+-- > let f = cdf (fromObservations [1..10])
+-- > cdf 0
+-- 0.0
+-- > cdf 1
+-- 0.1
+-- > cdf 10
+-- 1.0
+-- > cdf 11
+-- 1.0
+--
+-- > let g = cdf (fromDensity standardNormal)
+-- > cdf 0
+-- 0.504
+-- > cdf 1
+-- 0.838
+-- > cdf (1 / 0)
+-- 0.999
+cdf :: Measure Double -> Double -> Double
+cdf mu b = mean $ negate (1 / 0) `to` b <$> mu
+
diff --git a/tests/Test.hs b/tests/Test.hs
@@ -1,6 +1,8 @@
-- Simple examples that demonstrate some measure-foo.
+import Control.Applicative
import Control.Monad
+import Control.Monad.Trans
import Measurable
import Statistics.Distribution hiding (mean, variance)
import Statistics.Distribution.Normal
@@ -20,8 +22,8 @@ main = do
let mu = fromDensity standardNormal
nu = fromObservations expSamples
- rho = (fmap cos mu) + (fmap sin nu)
- eta = fmap exp rho
+ rho = (cos <$> mu) + (sin <$> nu)
+ eta = exp <$> rho
putStrLn $ "mean of normal samples (should be around 0): " ++
show (mean . fromObservations $ normSamples)
@@ -55,7 +57,19 @@ main = do
show (variance zeta)
let alpha = fromDensity $ density $ chiSquared 5
+ beta = (exp . tanh) <$> (phi * alpha)
putStrLn $ "let X ~ N(2, 1), Y ~ chisq(5). variance of exp (tanh XY) " ++
- show (variance . fmap (exp . tanh) $ phi * alpha)
+ show (variance beta)
+
+ putStrLn ""
+ putStrLn "Some probability examples:"
+ putStrLn ""
+
+ putStrLn $ "let X ~ N(0, 1). P(X < 0) (should be ~ 0.5): " ++
+ show (mean $ negate (1 / 0) `to` 0 <$> mu)
+
+ putStrLn $ "let X ~ N(0, 1). P(0 < X < 1) (should be ~ 0.341): " ++
+ show (mean $ 0 `to` 1 <$> mu)
+