Monte Carlo simulation in Python #1

July 05, 2007 at 11:15 AM | categories: Technical, Maths, Python | View Comments |

I became interested in Monte Carlo simulation after reading Fooled By Randomness, the author of which makes numerous references to the power of these simulators. One of the first things I learned was that "Monte Carlo methods" is a term covering pretty much any use of pseudo-randomness to help solve any kind of problem. Apparently, Monte Carlo is an old name for what is now commonly known as a roulette wheel, hence the relation to randomness.

One of the fascinating examples of a Monte Carlo simulator described in Fooled by Randomness is the use of pseudo-random numbers to calculate an approximation of the value of Pi. Imagine a dart board inside of a square. If you throw darts, in a random fashion, at the square, counting the number of darts which land on the dart board versus the number which land on the square, you can approximate Pi with some simple arithmetic.

After reading about this, I simply had to write a program to work it out. I figured Python would be a good language in which to hack it out. Indeed, it turns out that Python comes with a good pseudo-random number module in its standard library. Here is the code for my simple Pi approximator, which throws 1,000,000 virtual darts:

from random import random
from math import pow, sqrt

DARTS=1000000
hits = 0
throws = 0
for i in range (1, DARTS):
	throws += 1
	x = random()
	y = random()
	dist = sqrt(pow(x, 2) + pow(y, 2))
	if dist <= 1.0:
		hits = hits + 1.0

# hits / throws = 1/4 Pi
pi = 4 * (hits / throws)

print "pi = %s" %(pi)
And a sample run (timed on a 2.0Ghz Pentium M):
$ time python monte-carlo-pi.py
pi = 3.1422991423
    0m3.89s real 0m3.78s user 0m0.03s system

I have done some other hacking using Monte Carlo methods, specifically exploring methods of stock price prediction, which I hope to write about in the future.

Niall O'Higgins is an author and software developer. He wrote the O'Reilly book MongoDB and Python. He also develops Strider Open Source Continuous Deployment and offers full-stack consulting services at FrozenRidge.co.

blog comments powered by Disqus