Computing Approximate Value of PI using Monte Carlo in Python


The method of Monte Carlo (MC) relies on repeated random sampling. It is often used in computing simulations. For example, to compute the PI value, one can generate as many points as possible within a square (length = 1, area = 1), and compute the ratio between the number of points that fall into the 1/4 circle and the total sampling number. The ratio approximates the PI/4.

However, using MC may converge slowly. Using intel i7 quad core, 8GB RAM,  Win 7, Python 2.7.3 (64-bit), the following code gives the results roughly in 7 seconds.

from random import *

MAXN = 10000000

def dist(x, y):
    return (x * x + y * y)

i = 0
j = 0

seed()

while i < MAXN:
    x = random()
    y = random()
    if dist(x, y) <= 1.0:
        j += 1
    i += 1

print j, '* 4.0 /', MAXN, '=', j * 4.0 / MAXN

The output is

7854284 * 4.0 / 10000000 = 3.1417136

Monte Carlo Simulation Algorithms to compute the Pi based on Randomness:

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
566 words
Last Post: Codeforces: A. Double Cola
Next Post: Two Simple Equations to Compute PI

The Permanent URL is: Computing Approximate Value of PI using Monte Carlo in Python

Leave a Reply