module Statistics.Distribution.Beta
( BetaDistribution
, betaDistr
, improperBetaDistr
, bdAlpha
, bdBeta
) where
import Data.Binary (Binary)
import Data.Data (Data, Typeable)
import GHC.Generics (Generic)
import Numeric.SpecFunctions (
incompleteBeta, invIncompleteBeta, logBeta, digamma)
import Numeric.MathFunctions.Constants (m_NaN)
import qualified Statistics.Distribution as D
import Data.Binary (put, get)
import Control.Applicative ((<$>), (<*>))
data BetaDistribution = BD
{ bdAlpha :: !Double
, bdBeta :: !Double
} deriving (Eq, Read, Show, Typeable, Data, Generic)
instance Binary BetaDistribution where
put (BD x y) = put x >> put y
get = BD <$> get <*> get
betaDistr :: Double
-> Double
-> BetaDistribution
betaDistr a b
| a > 0 && b > 0 = improperBetaDistr a b
| otherwise =
error $ "Statistics.Distribution.Beta.betaDistr: "
++ "shape parameters must be positive. Got a = "
++ show a
++ " b = "
++ show b
improperBetaDistr :: Double
-> Double
-> BetaDistribution
improperBetaDistr = BD
instance D.Distribution BetaDistribution where
cumulative (BD a b) x
| x <= 0 = 0
| x >= 1 = 1
| otherwise = incompleteBeta a b x
instance D.Mean BetaDistribution where
mean (BD a b) = a / (a + b)
instance D.MaybeMean BetaDistribution where
maybeMean = Just . D.mean
instance D.Variance BetaDistribution where
variance (BD a b) = a*b / (apb*apb*(apb+1))
where apb = a + b
instance D.MaybeVariance BetaDistribution where
maybeVariance = Just . D.variance
instance D.Entropy BetaDistribution where
entropy (BD a b) =
logBeta a b
(a1) * digamma a
(b1) * digamma b
+ (a+b2) * digamma (a+b)
instance D.MaybeEntropy BetaDistribution where
maybeEntropy = Just . D.entropy
instance D.ContDistr BetaDistribution where
density (BD a b) x
| a <= 0 || b <= 0 = m_NaN
| x <= 0 = 0
| x >= 1 = 0
| otherwise = exp $ (a1)*log x + (b1)*log (1x) logBeta a b
quantile (BD a b) p
| p == 0 = 0
| p == 1 = 1
| p > 0 && p < 1 = invIncompleteBeta a b p
| otherwise =
error $ "Statistics.Distribution.Gamma.quantile: p must be in [0,1] range. Got: "++show p
instance D.ContGen BetaDistribution where
genContVar = D.genContinous