Skip to content

Instantly share code, notes, and snippets.

@seanparsons
Last active March 26, 2017 23:38
Show Gist options
  • Save seanparsons/8c44ed8f597ab62b729b6be4c49f2e25 to your computer and use it in GitHub Desktop.
Save seanparsons/8c44ed8f597ab62b729b6be4c49f2e25 to your computer and use it in GitHub Desktop.
Back calculate pi from randomly generated numbers.
#!/usr/bin/env stack
-- stack --resolver lts-8.5 --nix runghc --package random
-- Requires the Haskell build tool Stack to be installed: https://docs.haskellstack.org/en/stable/README/
-- Create this file and make it executable using "chmod u+x pifromrandomnumbers.hs"
-- and run it with "./pifromrandomnumbers.hs" from a terminal.
{-# LANGUAGE StrictData #-}
{-# LANGUAGE Strict #-}
import System.Random
range :: (Int, Int)
range = (1, 10000000000)
numberOfRolls :: Int
numberOfRolls = 100000
coprimeRoll :: IO Bool
coprimeRoll = do
first <- randomRIO range
second <- randomRIO range
return $ gcd first second <= 1
rollDice :: Int -> Int -> Int -> IO (Int, Int)
rollDice 0 coprimesSoFar countSoFar = return (coprimesSoFar, countSoFar)
rollDice rollsLeft coprimesSoFar countSoFar = do
if rollsLeft < 0 then fail "Uh oh" else return ()
isCoprime <- coprimeRoll
let newCoprimesSoFar = if isCoprime then coprimesSoFar + 1 else coprimesSoFar
rollDice (rollsLeft - 1) newCoprimesSoFar (countSoFar + 1)
main = do
(coprime, total) <- rollDice numberOfRolls 0 0
let probability = (fromIntegral coprime) / (fromIntegral total) :: Double
let pi = sqrt (6 / probability)
let result = "Estimated pi: " ++ (show pi)
putStrLn result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment