[Haskell-beginners] PI calculation - Newbie question
Gabi
bugspynet at gmail.com
Fri Jan 29 05:59:30 EST 2010
Hi Group,
I am just trying to learn the lang and Implemented this PI calculator.
It is really slow and very memory consuming (much much slower than its
equivalent in Clojure for instance)
I think the problem is in "rs <- sequence (replicate n isRandIn)" -
But I don't know how to get around it (how do I get a lazy sequence of
rs? Is it the problem anyway?)
-- p.hs simple PI calculator, using the Monte Carlo Method
import System( getArgs )
import System.Random
inCirc :: (Double, Double) -> Int
inCirc (x,y) = if ((dx * dx) + (dy * dy)) < 0.25
then 1
else 0
where dx = x - 0.5
dy = y - 0.5
randPoint :: IO (Double, Double)
randPoint = do
x <-getStdRandom (randomR (0, 1 :: Double))
y <-getStdRandom (randomR (0, 1 :: Double))
return (x, y)
isRandIn = do
p <- randPoint
return (inCirc p)
main = do
args <- getArgs
let n = if null args
then 10000
else read $ (head args)::Int
rs <- sequence (replicate n isRandIn)
let pi = (fromIntegral(sum rs) / fromIntegral n) * 4
print pi
More information about the Beginners
mailing list