Suppose you draw a square that has all side lengths equal to
1. Suppose next that you draw the largest circle you can
that fits inside of the square, with the circle having its center at the center of the square. The circle will have a radius
of
1/2. Now, the area of the square is
12 or just
1 and the area of the circle is
π(12)2 or just
π/4. If you divide these two areas you'll
get
π4. So what?
Now suppose you put your drawing on the wall and threw darts at it. The number of darts landing in the circle, divided by
those landing in the square will be the ratio of these areas or
π/4! Wow! Multiply the ratio by
4 and you have a way to find
π!
But darts would be too much work...let's have the computer do it.
Let's pick two random numbers for an
(x,y) point on the cartesian coordinate system. To stay in the square, let's pick both
x and
y
randomly to be between
0 and
1. This way all points will be in a square of side length
1.
If we call the built in function
math.random()
(without a range as discussed in
this lesson), this is what we'll get...a random
number between
0 and
1. Try it: type a short one-line program with just
print(math.random())
in it, and run it a few times.
Now, when an
(x,y) point is known, we have to see if it lands in the circle. Can you think of how to do this? Hint: What about the distance
formula which says that
d=√(x−x0)2+(y−y0)2. This formula was covered in a
past lesson. You can use this formula to compute how far your
(x,y) point is from the center of
the circle, which is at
(0.5,0.5). If
d<0.5 (
0.5=the circle's radius), then the dart must be fallen within the circle. Use and
if
statement
to check this, and increment a counter each time this occurs.
When this is done a few (thousand) times, the ratio of your hits inside the circle and the total thrown should start to approach
π/4. Neat huh?