fork download
  1. {-# LANGUAGE BangPatterns #-}
  2. import qualified Data.IntMap as I
  3. import System.Random
  4.  
  5. main :: IO ()
  6. main = do
  7. rd <- rollDice
  8. let (a, b) = dicePi 4 300000 rd
  9.  
  10. putStrLn $ "pi = " ++ show a
  11.  
  12. dicePi :: Int -> Double -> [Int] -> (Double, [(Int, Int)])
  13. dicePi diceNum n rd = (4 * c / n, I.assocs im)
  14. where
  15. (c, im) = go n 0 rd (I.fromList $ zip [1..6] [0,0..])
  16. go 0 count _ im = (count, im)
  17. go m count rolls im =
  18. let !h = sqrt $! x * x + y * y :: Double
  19. (r1, rs) = splitAt diceNum rolls
  20. r2 = take diceNum rs
  21. !x = dicesToRandom r1
  22. !y = dicesToRandom r2
  23. !count' = if h < 1.0 then count + 1 else count
  24. rolls' = drop diceNum rs
  25. !im' = foldr (I.update ((Just $!) . succ)) im $! r1 ++ r2
  26. in go (m - 1) count' rolls' im'
  27. diceToRandom :: [Int] -> Double
  28. diceToRandom xxs = (/ (6 ^ diceNum)) $ fromIntegral $ foldl g 0 xxs
  29. where
  30. g !x !y = 6 * x + y - 1
  31.  
  32. rollDice :: IO [Int]
  33. rollDice = getStdGen >>= (return . randomRs (1, 6))
  34.  
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.hs:3:8:
    Could not find module `System.Random'
    Use -v to see a list of the files searched for.
stdout
Standard output is empty