Created
February 21, 2012 04:56
-
-
Save mitsuji/1873842 to your computer and use it in GitHub Desktop.
Monte Carlo method pi calculation in Haskell
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.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