Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
13
Task/Monte-Carlo-methods/Haskell/monte-carlo-methods-1.hs
Normal file
13
Task/Monte-Carlo-methods/Haskell/monte-carlo-methods-1.hs
Normal 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)
|
||||
23
Task/Monte-Carlo-methods/Haskell/monte-carlo-methods-2.hs
Normal file
23
Task/Monte-Carlo-methods/Haskell/monte-carlo-methods-2.hs
Normal 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]
|
||||
Loading…
Add table
Add a link
Reference in a new issue