% --------------------------------------------------- 
% pi_mc2.m
% Monte Carlo estimate for pi
% comment: many random numbers generated at a time 
%          => better Matlab performance than in pi_mc
% ---------------------------------------------------
clear all; close all;
Nr=1000;
N=10;
fprintf('%20s %20s %20s\n','N','approx pi','deviation');
tab = [];
tic
while N*Nr<10^10
    Nin = 0;  
    for i=1:N
        x = rand(1,Nr);  % random point 
        y = rand(1,Nr);  
        d  = x.^2+y.^2; % distance from origin
        test = d <= 1;          
        Nin = Nin + sum(test);
    end
    piappr = 4*Nin/(N*Nr);
    fprintf('%20g %20.15f %20f15\n',N*Nr,piappr,pi-piappr);
    tab = [tab;[N*Nr piappr]];
    N = 2*N;
end
semilogx(tab(:,1),tab(:,2),'bo-',tab(:,1),pi*ones(size(tab(:,1),1)),'r-');
toc
   
%                   N            approx pi            deviation
% 10000.000000000000000    3.152400000000000            -0.01080715
% 20000.000000000000000    3.138800000000000             0.00279315
% 40000.000000000000000    3.152000000000000            -0.01040715
% 80000.000000000000000    3.131450000000000             0.01014315
% 160000.000000000000000    3.137400000000000             0.00419315
% 320000.000000000000000    3.135425000000000             0.00616815
% 640000.000000000000000    3.140237500000000             0.00135515
% 1280000.000000000000000    3.141162500000000             0.00043015
% 2560000.000000000000000    3.141882812500000            -0.00029015
% 5120000.000000000000000    3.141764843750000            -0.00017215
% 10240000.000000000000000    3.142005078125000            -0.00041215
% 20480000.000000000000000    3.141849414062500            -0.00025715
% 40960000.000000000000000    3.141179199218750             0.00041315
% 81920000.000000000000000    3.141441748046875             0.00015115
% 163840000.000000000000000    3.141483764648437             0.00010915
% 327680000.000000000000000    3.141615808105469            -0.00002315
% 655360000.000000000000000    3.141599737548828            -0.00000715
% 1310720000.000000000000000    3.141581576538086             0.00001115
% 2621440000.000000000000000    3.141622692871094            -0.00003015
% 5242880000.000000000000000    3.141595706939697            -0.00000315
% Elapsed time is 377.386487 seconds.