File: Gamma.hs

package info (click to toggle)
haskell-statistics 0.5.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 180 kB
  • sloc: haskell: 1,265; makefile: 2
file content (66 lines) | stat: -rw-r--r-- 1,936 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
{-# LANGUAGE DeriveDataTypeable #-}
-- |
-- Module    : Statistics.Distribution.Gamma
-- Copyright : (c) 2009 Bryan O'Sullivan
-- License   : BSD3
--
-- Maintainer  : bos@serpentine.com
-- Stability   : experimental
-- Portability : portable
--
-- The gamma distribution.  This is a continuous probability
-- distribution with two parameters, /k/ and ϑ. If /k/ is
-- integral, the distribution represents the sum of /k/ independent
-- exponentially distributed random variables, each of which has a
-- mean of ϑ.

module Statistics.Distribution.Gamma
    (
      GammaDistribution
    -- * Constructors
    --, fromParams
    --, fromSample
    --, standard
    -- * Accessors
    , gdShape
    , gdScale
    ) where

import Data.Typeable (Typeable)
import Statistics.Constants (m_huge)
import Statistics.Math (incompleteGamma, logGamma)
import qualified Statistics.Distribution as D

-- | The gamma distribution.
data GammaDistribution = GD {
      gdShape :: {-# UNPACK #-} !Double -- ^ Shape parameter, /k/.
    , gdScale :: {-# UNPACK #-} !Double -- ^ Scale parameter, ϑ.
    } deriving (Eq, Read, Show, Typeable)

instance D.Distribution GammaDistribution where
    density    = density
    cumulative = cumulative
    quantile   = quantile

instance D.Variance GammaDistribution where
    variance (GD a l) = a / (l * l)
    {-# INLINE variance #-}

instance D.Mean GammaDistribution where
    mean (GD a l) = a / l
    {-# INLINE mean #-}

density :: GammaDistribution -> Double -> Double
density (GD a l) x = x ** (a-1) * exp (-x/l) / (exp (logGamma a) * l ** a)
{-# INLINE density #-}

cumulative :: GammaDistribution -> Double -> Double
cumulative (GD a l) x = incompleteGamma a (x/l) / exp (logGamma a)
{-# INLINE cumulative #-}

quantile :: GammaDistribution -> Double -> Double
quantile d p
  | p == 0    = -1/0
  | p == 1    = 1/0
  | otherwise = D.findRoot d p (gdShape d) 0 m_huge
{-# INLINE quantile #-}