Monte Carlo methods: Difference between revisions

Content added Content deleted
(→‎{{header|Haskell}}: Added a variant using foldM and dropping sqrt)
Line 1,272: Line 1,272:


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>
<lang haskell>import System.Random
import System.Random
import Control.Monad
import Control.Monad


Line 1,283: Line 1,282:
let dist :: Double
let dist :: Double
dist = sqrt (rand_x*rand_x + rand_y*rand_y)
dist = sqrt (rand_x*rand_x + rand_y*rand_y)
return (if dist < 1 then 1 else 0)
return (if dist < 1 then 1 else 0)</lang>
{{Out}}
</lang>
Example:
<pre>Example:
Prelude System.Random Control.Monad> get_pi 10000
Prelude System.Random Control.Monad> get_pi 10000
3.1352
3.1352
Line 1,291: Line 1,290:
3.15184
3.15184
Prelude System.Random Control.Monad> get_pi 1000000
Prelude System.Random Control.Monad> get_pi 1000000
3.145024
3.145024</pre>

Or, using foldM, and dropping sqrt:

<lang haskell>import Control.Monad (foldM, (>=>))
import System.Random (randomRIO)

monteCarloPi :: Int -> IO Double
monteCarloPi n = do
m <- foldM go 0 [1 .. n]
return (4 * fromIntegral m / fromIntegral n)
where
rnd = randomRIO (0, 1) :: IO Double
f x y
| 1 > x ** 2 + y ** 2 = succ
| otherwise = id
go a x = do
rx <- rnd
ry <- rnd
return $ f rx ry a

main :: IO ()
main =
mapM_
(monteCarloPi >=> print)
[1000, 10000, 100000, 1000000]</lang>
{{Out}}
For example:
<pre>3.244
3.1116
3.14116
3.141396</pre>


=={{header|HicEst}}==
=={{header|HicEst}}==