File: SplitMixPi.hs

package info (click to toggle)
haskell-splitmix 0.1.0.5-2
  • links: PTS
  • area: main
  • in suites: forky, sid, trixie
  • size: 196 kB
  • sloc: haskell: 1,366; ansic: 151; sh: 53; makefile: 9
file content (27 lines) | stat: -rw-r--r-- 669 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
module Main (main) where

import Data.List (unfoldr, foldl')
import System.Random.SplitMix

doubles :: SMGen -> [Double]
doubles = unfoldr (Just . nextDouble)

monteCarloPi :: SMGen -> Double
monteCarloPi = (4 *) . calc . foldl' accum (P 0 0) . take 50000000 . pairs . doubles
  where
    calc (P n m) = fromIntegral n / fromIntegral m

    pairs (x : y : xs) = (x, y) : pairs xs
    pairs _ = []

    accum (P n m) (x, y) | x * x + y * y >= 1 = P n (m + 1)
                         | otherwise          = P (n + 1) (m + 1)

data P = P !Int !Int

main :: IO ()
main = do
    pi' <- fmap monteCarloPi newSMGen
    print (pi :: Double)
    print pi'
    print (pi - pi')