Monte Carlo methods: Difference between revisions

Line 2,125:
{{out}}
<pre>loop=1,000,000, count=785,462, pi=3.141848</pre>
 
=={{header|Picat}}==
Of the three different MC simulators, sim_rec/2 (using recursion) is slightly faster than the other two (sim1/2 and sim2/2) which have about the same speed.
<lang Picat>go =>
foreach(N in 0..7)
sim_pi(10**N)
end,
nl.
 
% The specific pi simulation
sim_pi(N) =>
Inside = sim(N,pi_f),
MyPi = 4.0*Inside/N,
Pi = math.pi,
println([n=N, myPi=MyPi, diff=Pi-MyPi]).
 
 
% The simulation function:
% returns 1 if success, 0 otherwise
pi_f() = cond(frand()**2 + frand()**2 <= 1, 1, 0).
 
%
% Some general Monte Carlo simulators.
% N is the number of runs, F is the simulation function.
%
 
% Using while loop
sim1(N, F) = C =>
C = 0,
I = 0,
while (I <= N)
C := C + apply(F),
I := I + 1
end.
 
% List comprehension
% Simpler, but slightly slower.
sim2(N, F) = sum([apply(F) : _I in 1..N]).
 
% Recursive variant.
sim_rec(N,F) = S =>
sim_rec(N,N,F,0,S).
sim_rec(0,_N,_F,S,S).
sim_rec(C,N,F,S0,S) :-
S1 = S0 + apply(F),
sim_rec(C-1,N,F,S1,S).</lang>
 
Output:
<pre>[n = 1,myPi = 4.0,diff = -0.858407346410207]
[n = 10,myPi = 3.2,diff = -0.058407346410207]
[n = 100,myPi = 3.12,diff = 0.021592653589793]
[n = 1000,myPi = 3.152,diff = -0.010407346410207]
[n = 10000,myPi = 3.1672,diff = -0.025607346410207]
[n = 100000,myPi = 3.13888,diff = 0.002712653589793]
[n = 1000000,myPi = 3.14192,diff = -0.000327346410207]
[n = 10000000,myPi = 3.1408988,diff = 0.000693853589793]</pre>
 
 
=={{header|PicoLisp}}==
495

edits