COMP 110-1



COMP 110-1, Fall 2009

Assignment 3: Random PI (or "May I have a large container of coffee. Thank you.")[1]

Objectives: write a simple JavaScript program with I/O, a loop, and selection.

PI (or, in Greek, () is the classic ratio of the circumfrance of a circle to its diameter[2]. It has an infinite number of fraction digits, but is approximately 3.14159. If you want to see more digits, check out which has the first million digits of (.

There are several ways to derive (. We will approximate ( by using random numbers. If you have a square that is 1 by 1 (units don't matter) and inscribe inside that square a quarter of a circle with radius 1, then the area of the square is 1 and the area of the quarter circle (/4 since the area of a circle is (*r2 where r is the radius of the circle which is 1 in this case. So the ratio of the area of the quarter circle to the area of the square is (/4.

If you drop n random points into the square, then you would expect the ratio of the number of points that are in or on the quarter circle to the total number of points to also be (/4.

Generating random numbers in JavaScript

A call to the function Math.random() returns a random number in the range 0 up to but not including 1. So to generate a random point (x,y) in the square, just call Math.random() twice.

x = Math.random();

y = Math.random();

Then to determine if the point is inside or on the quarter circle, just see if x2 + y2 is less than or equal to 1. If it is, then the point is inside (or on) the quarter of a circle. If not, then the point is outside the quarter circle.

Program

You program should prompt the user for the number of points to drop. Then it should generate those points keeping track of how many fall within the quarter circle. Finally, report, with an appropriately labeled alert statement the approximation to (.

Hint

My version of this program (including both the HTML and JavaScript code) is about 20 lines long.

Here is a 1x1 square with a quarter circle inside. Every point in the square can be indicated by a pair (x,y) where x is the horizontal position 0…1, and y is the vertical position 0…1. The lower left corner is (0, 0); the upper right corner is (1, 1). The point half way along the bottom is (0.5, 0); the point half way along the top is (0.5, 1). And the point right in the middle is (0.5, 0.5). The area of the square is 1; the area of the quarter circle is (/4.

[pic]

-----------------------

[1] What is the significance of the quoted sentences? Hint: this is something that is related to this assignment and that will be useful to you forever.

[2] The circumference of a circle with diameter d is (*d.

-----------------------

1

1

(0,0)

(1,1)

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download