MUD.hs/src/AcceptReject.hs
Michael Pilosov 6eee88fd4c cleanup
2024-05-18 20:59:44 +00:00

33 lines
1.2 KiB
Haskell

module AcceptReject (main) where
import System.Random
import Control.Monad (replicateM)
-- Acceptance-Rejection sampling for normal distribution
generateNormalPointsAR :: Int -> Double -> Double -> IO [Double]
generateNormalPointsAR n mu sigma = do
gen <- newStdGen
let samples = take n $ filter acceptCandidate $ randomPairs gen
return $ map ((\x -> mu + sigma * x) . fst) samples
where
acceptCandidate (u1, u2) =
let x = sqrt (-2 * log u1) * cos (2 * pi * u2)
in u2 < exp (-0.5 * x * x)
randomPairs g = zip (randoms g) (randoms g)
-- Generate random points from a uniform distribution in the range [a, b]
generateUniformPoints :: Int -> Double -> Double -> IO [Double]
generateUniformPoints n a b = replicateM n (randomRIO (a, b))
main :: IO ()
main = do
-- Generate 10 random points from a uniform distribution in the range [-1, 1]
uniformPoints <- generateUniformPoints 10 (-1) 1
putStrLn "Uniform distribution points:"
print uniformPoints
-- Generate 10 random points from a normal distribution using acceptance-rejection sampling
normalPointsAR <- generateNormalPointsAR 10 0 1
putStrLn "Normal distribution points (Acceptance-Rejection):"
print normalPointsAR