measurable

A simple shallowly-embedded DSL for dealing with measures.
Log | Files | Refs | README | LICENSE

commit 66cb8fd8695ca17cc9a9775bb4aebf4173502ce4
parent 2d5933893beac67d65e93928e34000d99ec997d5
Author: Jared Tobin <jared@jtobin.ca>
Date:   Sat, 19 Oct 2013 17:26:29 +1300

Add Num instance, wacky tanh example.

Diffstat:
Msrc/Measurable.hs | 14+++++++++++---
Mtests/Test.hs | 11++++++++---
2 files changed, 19 insertions(+), 6 deletions(-)

diff --git a/src/Measurable.hs b/src/Measurable.hs @@ -48,6 +48,14 @@ import Numeric.Integration.TanhSinh newtype Measure a = Measure { measure :: (a -> Double) -> Double } +instance Num a => Num (Measure a) where + (+) = convolute + (-) = msubtract + (*) = mproduct + abs = id + signum mu = error "fromInteger: not supported for Measures" + fromInteger = error "fromInteger: not supported for Measures" + instance Fractional a => Monoid (Measure a) where mempty = identityMeasure mappend = convolute @@ -94,19 +102,19 @@ fromDensity :: (Double -> Double) -> Measure Double fromDensity d = Measure $ \f -> quadratureTanhSinh $ liftM2 (*) f d where quadratureTanhSinh = result . last . everywhere trap --- | Measure addition is convolution. +-- | Measure addition is convolution. Assumes independence. convolute :: Num a => Measure a -> Measure a -> Measure a convolute mu nu = Measure $ \f -> measure nu $ \y -> measure mu $ \x -> f (x + y) --- | Measure subtraction. (does this make sense?) +-- | Measure subtraction. Assumes independence. msubtract :: Num a => Measure a -> Measure a -> Measure a msubtract mu nu = Measure $ \f -> measure nu $ \y -> measure mu $ \x -> f (x - y) --- | Measure multiplication. (does this make sense?) +-- | Measure multiplication. Assumes independence. mproduct :: Num a => Measure a -> Measure a -> Measure a mproduct mu nu = Measure $ \f -> measure nu $ \y -> measure mu diff --git a/tests/Test.hs b/tests/Test.hs @@ -29,7 +29,7 @@ main = do let mu = fromDensity standardNormal nu = fromObservations expSamples - rho = convolute (push cos mu) (push sin nu) + rho = (push cos mu) * (push sin nu) eta = push exp rho putStrLn $ "mean of normal samples (should be around 0): " ++ @@ -45,7 +45,7 @@ main = do -- Subtraction of measures? - let iota = mu `msubtract` mu + let iota = mu - mu putStrLn $ "let X, Y be independent N(0, 1). mean of X - Y: " ++ show (mean iota) @@ -56,10 +56,15 @@ main = do let phi = fromDensity $ genLocationNormal 2 xi = fromDensity $ genLocationNormal 3 - zeta = mproduct phi xi + zeta = phi * xi putStrLn $ "let X ~ N(2, 1), Y ~ N(3, 1). mean of XY (should be 6) " ++ show (mean zeta) putStrLn $ "let X ~ N(2, 1), Y ~ N(3, 1). variance of XY (should be 14) " ++ show (variance zeta) + let alpha = fromDensity $ density $ chiSquared 5 + + putStrLn $ "let X ~ N(2, 1), Y ~ chisq(5). variance of exp (tanh XY) " ++ + show (variance . push (exp . tanh) $ mu * nu) +