Welcome, guest | Sign In | My Account | Store | Cart

Calculating PI using random numbers (Monte Carlo method)

Python, 12 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# Calculating PI using random numbers (Monte Carlo Method)
# FB - 201003265
import math
import random
maxIt = 1000000 # number of iterations (greater the better)

ctr = 0
for i in range(maxIt):
    if math.pow(random.random(), 2.0) + math.pow(random.random(), 2.0) <= 1.0:
        ctr += 1

print "PI = ", 4.0 * ctr / maxIt

3 comments

Fouad Teniou 11 years, 10 months ago  # | flag

Please find the link to the Original Pi Monte Carlo Python Program by Bruno Preiss!!!!!!!

http://www.brpreiss.com/books/opus7/programs/pgm14_17.txt

FB36 (author) 11 years, 10 months ago  # | flag

I did not copy this code from anybody pal! I do math-related programs for so many years! You can see many of my Python and Java codes in this website already!

FB36 (author) 11 years, 7 months ago  # | flag

This method can also be used to calculate "area under the function curve" and numerical integration (when any f(x) and a<=x<=b given) if you think about it!