In our math club this afternoon, since it’s π day, I’m going to try to lead an activity where we write a program (on the Raspberry Pi, of course) that computes π. The idea I thought of (but we’ll see what the students think of as well) is to use the Monte Carlo method – guess random points (with uniform distribution) in a 2r x 2r square, and compute whether they’re “inCircle” or not (whether the distance from the center of the square <= r). Then use algebra to solve for the unknown quantity π in the formula

π r^{2} / 4r^{2} = inCircle / totalPoints

In my little Python program that does this, it pretty quickly gets to 3.14, but doesn’t get much further. Since these are 4th – 8th graders, I thought I should focus on techniques that have an intuition behind them, so Ramanujan’s fancy equations are out of the question. I’d be keen to hear other suggestions!

Here’s my Python program:

import random
import math
def computePi(count):
inCircle = 0;
for i in range(1,count,1):
x = random.uniform(-1,1)
y = random.uniform(-1,1)
length = math.sqrt(x*x+y*y)
if length 0):
print (str(inCircle) + "/" + str(i) + " = " +
str(4.0*inCircle/i))
print(str(4.0*inCircle/i))
computePi(1000000)

### Like this:

Like Loading...

*Related*

kirby urner

Nov 13, 2016@ 16:31:45I like using a Ramanujan expression for Pi to show off Python’s extended precision decimal capabilities.