Created
May 13, 2013 16:07
-
-
Save mstksg/5569453 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import System.Random | |
import Control.Monad.Random | |
import Control.Monad | |
metroStep :: (RandomGen g) => (Double -> Double) -> Double -> Double -> Rand g Double | |
metroStep p step x = do | |
dx <- getRandomR (-step, step) | |
let | |
newx = x + dx | |
p0 = p x | |
p1 = p newx | |
weightselect = do | |
let odds = exp (p1 - p0) | |
select <- getRandom | |
return (if (select < odds) then newx else x) | |
if (p1 > p0) | |
then return newx | |
else weightselect | |
metroChain :: (RandomGen g) => | |
(Double -> Double) | |
-> Double | |
-> Double | |
-> Int | |
-> Rand g Double | |
metroChain p step start n = (iterate mstep (return start)) !! n | |
where | |
mstep a = do | |
xval <- a | |
metroStep p step xval | |
main = do | |
let | |
p x = exp (-1*x) * (if (x>0) then 1 else 0) | |
res <- evalRandIO (replicateM 100 (metroChain p 0.1 0.5 10000)) | |
mapM_ print res |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's a refactoring that uses
mtl
transformer stacks.