Monte Carlo methods: Difference between revisions

Content added Content deleted
m (→‎{{header|Phix}}: added syntax colouring, marked p2js compatible)
Line 1,802: Line 1,802:
<lang Mathematica>monteCarloPi = 4. Mean[UnitStep[1 - Total[RandomReal[1, {2, #}]^2]]] &;
<lang Mathematica>monteCarloPi = 4. Mean[UnitStep[1 - Total[RandomReal[1, {2, #}]^2]]] &;
monteCarloPi /@ (10^Range@6)</lang>
monteCarloPi /@ (10^Range@6)</lang>

A less elegant way to solve the problem, is to imagine a (well-trained) monkey, throwing a number of darts at a dartboard.

The darts land randomly on the board, at different x and y coordinates. We want to know how many darts land inside the circle. We then guess Pi by dividing the total number of darts inside the circle by the total number of darts thrown (assuming they all hit the square board), and multiplying the whole lot by 4.

We create a function ''MonkeyDartsPi'', which can take a variable number of throws as input:
<lang Wolfram Language>MonkeyDartsPi[numberOfThrows_] := (
xyCoordinates = RandomReal[{0, 1}, {numberOfThrows, 2}];
InsideCircle = Length[Select[Total[xyCoordinates^2, {2}],#<=1&]] ;
4*N[InsideCircle / Length[xyCoordinates],1+Log10[numberOfThrows]])</lang>

We do several runs with a larger number of throws each time, increasing by powers of 10.
<lang Wolfram Language>Grid[Table[{n, MonkeyDartsPi[n]}, {n, 10^Range[7]} ], Alignment -> Left]</lang>

We see that as the number of throws increases, we get closer to the value of Pi:
<pre>10 2.8
100 3.20
1000 3.176
10000 3.1356
100000 3.13700
1000000 3.142624
10000000 3.1416328</pre>


=={{header|MATLAB}}==
=={{header|MATLAB}}==