File: SplitMixPi32.hs

package info (click to toggle)
haskell-splitmix 0.1.3.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 200 kB
  • sloc: haskell: 1,337; ansic: 125; sh: 53; makefile: 3
file content (27 lines) | stat: -rw-r--r-- 667 bytes parent folder | download | duplicates (4)
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.SplitMix32

doubles :: SMGen -> [Float]
doubles = unfoldr (Just . nextFloat)

monteCarloPi :: SMGen -> Float
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 :: Float)
    print pi'
    print (pi - pi')