{-# LANGUAGE
MultiParamTypeClasses,
FlexibleInstances, FlexibleContexts,
UndecidableInstances
#-}
module Data.Random.Distribution.Triangular where
import Data.Random.RVar
import Data.Random.Distribution
import Data.Random.Distribution.Uniform
data Triangular a = Triangular {
triLower :: a,
triMid :: a,
triUpper :: a}
deriving (Eq, Show)
floatingTriangular :: (Floating a, Ord a, Distribution StdUniform a) => a -> a -> a -> RVarT m a
floatingTriangular a b c
| a > b = floatingTriangular b a c
| b > c = floatingTriangular a c b
| otherwise = do
let p = (c-b)/(c-a)
u <- stdUniformT
let d | u >= p = a
| otherwise = c
x | u >= p = (u - p) / (1 - p)
| otherwise = u / p
return (b - ((1 - sqrt x) * (b-d)))
triangularCDF :: RealFrac a => a -> a -> a -> a -> Double
triangularCDF a b c x
| x < a
= 0
| x <= b
= realToFrac ((x - a)^(2 :: Int) / ((c - a) * (b - a)))
| x <= c
= realToFrac (1 - (c - x)^(2 :: Int) / ((c - a) * (c - b)))
| otherwise
= 1
instance (RealFloat a, Ord a, Distribution StdUniform a) => Distribution Triangular a where
rvarT (Triangular a b c) = floatingTriangular a b c
instance (RealFrac a, Distribution Triangular a) => CDF Triangular a where
cdf (Triangular a b c) = triangularCDF a b c