Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The rand function in Matlab generates a uniform random number between Zero and 1

ID: 3695096 • Letter: T

Question

The rand function in Matlab generates a uniform random number between Zero and 1. Thus x = rand - 0.5 generates a uniform random number between 0.5. Visualize a square with sides of length 1, centered at (0,0) in the x - y plane, and a circle of radius 0.5 inscribed inside it. The commands x - rand - 0.5 and y = rand - 0.5 generate a point with random coordinates (x, y) in the range 0.5, i.e. inside the square. This point may or may not be inside the circle. Write a program that repeatedly generates these random points and counts the number of times they fall inside the circle. For a large number N, say 10000, find the fraction of times the points fall within the circle. Multiply this fraction by 4 and see it the number is close to a well known constant. Identify the constant.

Explanation / Answer

%This value is close to pi. The area of circle is pi*0.25. The area of square is 1, so the fraction of points inside the circle is its area. That value multiplied by 4 should be pi.

count=0;
for i=1:10000
x = rand-0.5;
y = rand-0.5;
if(x*x+y*y<=0.25)
count+=1;
end
end
frac = count/10000;
disp(frac*4);