Skip to content

Instantly share code, notes, and snippets.

@quephird
Created January 21, 2016 00:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quephird/039b0254a5a5696346ae to your computer and use it in GitHub Desktop.
Save quephird/039b0254a5a5696346ae to your computer and use it in GitHub Desktop.
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