CSCI 317
Mike Heroux
CSCI 317 Mike Heroux 1
• Area of circle
C is A
C
• Area of square S is A
S
=
= s
πr
2 .
2 .
• Pick random (x,y) pairs with x and y between (-1/2, 1/2).
• Probability of (x, y) being inside C is A
C
• In our case:
/ A
S
.
– A
C
= π(1/2) 2
– A
S
–
A
C
= 1 2 = 1.
/ A
S
=
π/4.
= π/4.
Circle
Radius r=1/2
(x, y)
CSCI 317 Mike Heroux 2
• Get n total number random pairs (x, y).
• For each pair:
– Compute distance from center of circle: d = sqrt(x*x+y*y).
• If d < radius of circle ( d<1/2 ) increase count of points inside circle (n inside
) by 1.
• Theory tells us: n inside
/ n total
≈ π/4.
• Multiplying both sides above by
4 , we have:
π ≈ 4* ( n inside
/ n total
) .
CSCI 317 Mike Heroux 3
nsample = 100000; ntry = 500; ntotal = 0; mypivals = zeros(ntry,1); xy = zeros(nsample,2); ninside = 0; % number of (x,y) within the circle
% Graphics (no C++ equivalent) pivals = zeros(size(mypivals)); pivals = pi; for j=1:ntry
% random x and y between -1/2 and 1/2 xy=rand(nsample,2) - 0.5; for k=1:nsample x = xy(k,1); mypimin = min(mypivals); mypimax = max(mypivals); v = [0 ntry mypimin mypimax]; axis(v); plot([1:ntry],mypivals,[1:ntry],pivals); y = xy(k,2);
% distance from center of circle r = sqrt(x*x+y*y); if r <= 0.5
ninside = ninside + 1; end end ntotal = ntotal + nsample; mypivals(j) = 4*ninside/ntotal; end mypi_estimate = 4*ninside/ntotal
CSCI 317 Mike Heroux xlabel('Number of random samples'); ylabel('Estimate of Pi'); hold off
4
CSCI 317 Mike Heroux 5
• Methods that use random numbers this way are called Monte Carlo methods.
• Other simple applications:
– Estimating the likelihood of random events.
• Example: Poker hands: What is the probability of 3of-a-kind?
– Modeling atomic states.
– Approximate answers to otherwise intractable problems.
CSCI 317 Mike Heroux 6