Search This Blog

Optimized Matlab Program to Find Pi using Random Numbers (Using Monte Carlo Method)

% pimc2.m% Optimized Matlab Program to Find Pi using Random Numbers% Tom Huber, June 15, 1996Nrand = 8192; % Largest size of an array in Student Version of MatlabNmax = input(
NTrand = 0;
NInside = 0;

Xrand = rand(1,Nrand);
'How Many Loops (of 8192 Random Numbers Each) ');for nloops=1:Nmax% Generates 8192 Random XY Points
Yrand = rand(1,Nrand);
Rrand = Xrand.^2 + Yrand.^2;
% Finds the radius for all 8192 random pointsCheckValue = Rrand<=1.; % Has 1 if True & 0 if False for each elementNInside = NInside + sum(CheckValue); % Total number of Points InsideNTrand = NTrand + Nrand; % Total number of Points Generatedenddisp(['Total Generated: ' num2str(NTrand) ' Inside Pts: ' ...
num2str(NInside)]);
piapprox = 4*NInside/NTrand;
pierror = 4*sqrt(NInside)/NTrand;
disp([
' Approximation to pi = ' num2str(piapprox) ...' With Error ' num2str(pierror)]);