MATLAB Code
%Calculates for a given number of points an approximation of pi.
close all
clear
clc
num = input('How many points would you like to use?\n');
if (num < 3) || ((fix(num)-num) ~= 0 )
error('Input must be a positive integer greater than 2')
end
type = input('Would you like to make a graph?[Y/N]\n','s');
% Variables
numcirpt = 0;
allpt = num;
%Using a for loop, x and y coord are created and their
% distance from the origin is calculated.
% If it is less than or equal to 1 it is a point that is in the area of a circle
% otherwise it is in the area of the square along with all of the generated points
%
%
rng("shuffle");
switch(type)
case('Y')
figure
hold on
for i = 1:num
x = rand(1);
y = rand(1);
dist = sqrt(x^2+y^2);
if dist <= 1
numcirpt = numcirpt + 1;
plot(x,y,'.r');
else
plot(x,y,'.k');
end
end
hold off
case 'N'
for i = 1:num
x = rand(1);
y = rand(1);
dist = sqrt(x^2+y^2);
if dist <= 1
numcirpt = numcirpt + 1;
end
end
end
%The ratio of
piapprox = 4 * numcirpt / allpt;
if piapprox == 0
error('Make sure your inputs are correct!')
end
sprintf('The approx value of pi is %f',piapprox)
sprintf('The value of pi is %f',pi)
Again! Value is definitely not consistent
O(n) time complexity, obvious enough. Plotting over 100 000 points starts to take too long and lags MATLAB like crazy so I made it so you can turn it off. So bad it almost crashes MATLAB on my poor device.
What 175001 points looks like. Couldn't even save the image the right way with how bad it was!
50 000 points very reasonable and a pretty good estimation.
As far as without graphing pi estimation goes. 100 000 000 is the limit of my patience.
In terms of powers of 10, a billion points begins to take minutes not seconds to compute.