MATLAB: How to get value pi with monte carlo in 3D case

3dmonte carlo

Hello Everybody, I want to find the value of pi using random numbers. For the 2-D case my script works, but when I want to change it in a 3-D case I don't get the right value for pi. I have the following script written:
%r=1; % Radius sphere
%V=3/4 pi*r^3; % Volume of sphere
% Where r = 1, so V = 3/4*pi
%L=2*r; % length square
%V=L^3; % Volume of square is 2^3 = 8
% Therefore our ratio will be 3/4pi : 8.
% Which means we must multiply our result by 32/3 to get pi.
clear all
n=10^5;
inside=0;
x=rand(1,n); %creating random numbers
y=rand(1,n);
z=rand(1,n);
r = sqrt(x.^2 + y.^2 + z.^2);
for i = 1:n;
if r(i)<=1; %look if inside sphere
inside = inside +1; %calculate number of times inside sphere
else
end
end
pi= (32/3)*(inside/n) %calculating pi
Does anybody know what I am doing wrong? Thanks in advance

Best Answer

:-)
%V=3/4 pi*r^3;
No, it is 4/3 pi*r^3. Then the approximation is:
pi_approx = 6 * inside / n
You can simplify the code:
n = 10^5;
x = rand(1,n);
y = rand(1,n);
z = rand(1,n);
r2 = x.^2 + y.^2 + z.^2;
inside = sum(r2 < 1); % Compare the squared radius