Monte Carlo methods: Difference between revisions

→‎{{header|Erlang}}: Added a second example that avoids the inline test in a function call
(→‎{{header|Erlang}}: Added a second example that avoids the inline test in a function call)
Line 595:
 
=={{header|Erlang}}==
===With inline test===
<lang ERLANG>
-module(monte).
Line 622 ⟶ 623:
PI: 3.1416704
[ok,ok,ok,ok]
 
</pre>
===With test in a function===
<lang ERLANG>
-module(monte2).
-export([main/1]).
 
monte(N)->
monte(N,0,0).
 
monte(0,InCircle,NumPoints) ->
4 * InCircle / NumPoints;
 
monte(N,InCircle,NumPoints)->
X = rand:uniform(),
Y = rand:uniform(),
monte(N-1, within(X,Y,InCircle), NumPoints + 1).
 
within(X,Y,IN)->
if X*X + Y*Y < 1 -> IN + 1;
true -> IN
end.
 
main(N) -> io:format("PI: ~w~n", [ monte(N) ]).
</lang>
{{out}}
<pre>Xcoord
6> [monte2:main(X) || X <- [10000000,1000000,100000,10000] ].
PI: 3.1424172
PI: 3.140544
PI: 3.14296
PI: 3.1252
[ok,ok,ok,ok]
 
 
</pre>
Anonymous user