Skip to content

Instantly share code, notes, and snippets.

@mitsuji
Created February 21, 2012 04:56
Show Gist options
  • Save mitsuji/1873842 to your computer and use it in GitHub Desktop.
Save mitsuji/1873842 to your computer and use it in GitHub Desktop.
Monte Carlo method pi calculation in Haskell
import System.Random.Mersenne( getStdGen, randoms )
import Time
data Point = Point { x::Double, y::Double } deriving( Show )
total = 10000000
main = do
testStart <- getClockTime
gen <- getStdGen
rs <- randoms' gen
print $ pi' rs
testEnd <- getClockTime
print $ tdSec' $ diffClockTimes testEnd testStart
where
tdSec' td = fromIntegral(tdSec td)
+ ( fromIntegral(tdPicosec td) / 1000 / 1000 / 1000 / 1000 )
pi' rs = 4.0 * (fromIntegral count) / (fromIntegral total)
where
count = length $ filter isInCircle $ points rs
isInCircle pt = sqrt( (x pt)^2 + (y pt)^2 ) < 1
points (x':y':xs) = Point { x=x', y=y' } : points xs
points _ = []
randoms' gen = do
rs <- randoms gen :: IO [Double]
return( take (total*2) rs )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment