Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,13 @@
import Control.Monad
import System.Random
getPi throws = do
results <- replicateM throws one_trial
return (4 * fromIntegral (sum results) / fromIntegral throws)
where
one_trial = do
rand_x <- randomRIO (-1, 1)
rand_y <- randomRIO (-1, 1)
let dist :: Double
dist = sqrt (rand_x * rand_x + rand_y * rand_y)
return (if dist < 1 then 1 else 0)

View file

@ -0,0 +1,23 @@
import Control.Monad (foldM, (>=>))
import System.Random (randomRIO)
import Data.Functor ((<&>))
------- APPROXIMATION TO PI BY A MONTE CARLO METHOD ------
monteCarloPi :: Int -> IO Double
monteCarloPi n =
(/ fromIntegral n) . (4 *) . fromIntegral
<$> foldM go 0 [1 .. n]
where
rnd = randomRIO (0, 1) :: IO Double
go a _ = rnd >>= ((<&>) rnd . f a)
f a x y
| 1 > x ** 2 + y ** 2 = succ a
| otherwise = a
--------------------------- TEST -------------------------
main :: IO ()
main =
mapM_
(monteCarloPi >=> print)
[1000, 10000, 100000, 1000000]