60 likes | 182 Vues
This document outlines a method for estimating the value of π using random number generation within CSCI 317. It explains the geometric probability concept where points are randomly picked inside a square that encloses a circle. As each point's distance from the circle's center is computed, we determine how many points fall inside the circle. The ratio of points inside the circle to total points, multiplied by 4, approaches the value of π. The implementation in MATLAB is illustrated with graphics, demonstrating the convergence of the estimate with increased sample size.
E N D
A Brief Look at Random Numbers CSCI 317 Mike Heroux CSCI 317 Mike Heroux
Computing Estimate of Pi • Area of circle C is AC = πr2. • Area of square S is AS = s2. • Pick random (x,y) pairs with x and y between (-1/2, 1/2). • Probability of (x, y) being inside C is AC / AS. • In our case: • AC = π(1/2)2 = π/4. • AS = 12 = 1. • AC / AS = π/4. Circle Radius r=1/2 (x, y) CSCI 317 Mike Heroux
Algorithm to Estimate Pi • Get ntotal 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 (ninside ) by 1. • Theory tells us: ninside / ntotal≈ π/4. • Multiplying both sides above by 4, we have: π ≈ 4* (ninside / ntotal ). CSCI 317 Mike Heroux
Matlab Pi Estimator ‘mypi.m’ % Graphics (no C++ equivalent) pivals = zeros(size(mypivals)); pivals = pi; mypimin = min(mypivals); mypimax = max(mypivals); v = [0 ntry mypimin mypimax]; axis(v); plot([1:ntry],mypivals,[1:ntry],pivals); xlabel('Number of random samples'); ylabel('Estimate of Pi'); hold off nsample = 100000; ntry = 500; ntotal = 0; mypivals = zeros(ntry,1); xy = zeros(nsample,2); ninside = 0; % number of (x,y) within the circle 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); 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
Estimate vs. True Pi CSCI 317 Mike Heroux
Monte Carlo Methods • 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 3-of-a-kind? • Modeling atomic states. • Approximate answers to otherwise intractable problems. CSCI 317 Mike Heroux