# [Haskell-cafe] Monte Carlo Pi calculation (newbie learnings)

Alex Young alex at blackkettle.org
Mon Nov 5 16:21:04 EST 2007

```Don Stewart wrote:
> alex:
<snip>
> You can replace most of your loops with Data.List functions, and
> simplify the code overall by threading around a lazy list of randoms,
> rather than calling into IO all the time:
>
>     import System.Random
>     import System.Environment
>     import Data.List
>
>     randMax    = 32767
>     unitRadius = randMax * randMax
>
>     countPair :: (Int, Int) -> Int
>     countPair (x, y) = fromEnum (x*x + y*y < unitRadius)
>
>     calculatePi total g = fromIntegral (4*count) / fromIntegral total
>      where
>       count = sum
>             . map countPair
>             . take total
>             \$ zip (randomRs (0,randMax) a)
I wish I'd known about randomRs a couple of hours ago :-)

>                   (randomRs (0,randMax) b)
>
>       (a,b) = split g
>
>     main = do
>       [v] <- getArgs
>       g <- newStdGen
>       print \$ calculatePi (read v) g
>
> Compiled like so:
>
>     \$ ghc -O2 A.hs -o A
>
>     \$ time ./A 100000
>     3.13548
>     ./A 100000  0.08s user 0.02s system 98% cpu 0.101 total
>
> We get no stack overflow.
Not with -O2, but:

Stack space overflow: current size 8388608 bytes.
Use `+RTS -Ksize' to increase it.

But:

3.140636

This is a little confusing.  Is there a simple explanation for this
behaviour, or is it just a matter of "always use -O2 unless there's a
reason not to?"

Thanks - I really appreciate the explanations.

(P.S.  Again - sorry for the duplication.  I really need to watch my
mail client more closely :-)

--
Alex
```