Skip to content

Instantly share code, notes, and snippets.

Created Jan 21, 2016
What would you like to do?
Just an exercise to compute pi based on random number generation
module Pi where
import Data.List.Split (chunksOf)
import System.Random (newStdGen, randoms)
randomTuples :: Int -> IO [(Float, Float)]
randomTuples n = do
seed1 <- newStdGen
seed2 <- newStdGen
let xs = randoms seed1 :: [Float]
ys = randoms seed2 :: [Float]
return $ take n $ zipWith (,) xs ys
isInUnitCircle :: (Float, Float) -> Bool
isInUnitCircle (x,y) =
(x-0.5)**2 + (y-0.5)**2 < 0.25
main = do
putStrLn "How many random tuples do you want to use to approximate π?"
count <- getLine
allTuples <- randomTuples $ read count
let insideTuples = filter isInUnitCircle allTuples
pi = 4.0 * (fromIntegral $ length insideTuples) / (fromIntegral $ length allTuples)
putStrLn $ show pi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment