Lab 7.4 - Slice of Pi


We all know that π is a mathematical constant that is the ratio of a circle's circumference to its diameter, but what is it really? We could look it up, but that's boring. Figuring it out would be more fun. Even more fun if it involves random numbers.

A "Monte Carlo" method of finding an answer involves using a lot random numbers and figuring out what your answer is from the result. There are a couple of Monte Carlo methods of finding π. The version we'll use is the inscribed circle method (the one in the pic). The basic idea is that if we draw a quarter circle on a square napkin and then sprinkle pie crumbs on it, the ratio of the pie crumbs in the quarter circle to the crumbs on the entire napkin is equal to a quarter of π. Ask your instructor if you want to know how that works; we're just going to do it.

Your program will have a napkin made out of a two-dimensional array of booleans. The array's size should be big (like 2,500 by 2,500, for example). Then, it takes a number of crumbs from the user (between 1 and about 2/3 the number of members in the array (our example's case would be about 4,166,667) and "sprinkles" them into the array. It will make sure not to sprinkle a crumb onto a place that already has a crumb. It then traverses the array, counting the number of crumbs that landed inside the arc, dividing that number by the number of total crumbs, multiplies by 4, and displays the answer. Which should be really close to the real π; the more crumbs, the closer to π it should be.

HINTS: We're going to be using large integers, so you might want to use Long variables instead of Integer variables. Of course, π is a real number, so you'll need to work in Double time (get it?). A crumb is inside the arc if the distance from the origin is equal to or less than the size of one dimension of the array (use the crumb's indicies as its coordinates).

As always, design a useful and proper interface, including tab order and access keys.