Calculating PI using random numbers (Monte Carlo method)
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
|
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
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!
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!