Just an exercise to compute pi based on random number generation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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