Monte Carlo Method and pi
Robert Brewer
fumanchu at amor.org
Thu Jul 8 17:51:02 EDT 2004
Karl Pech wrote:
> import random
> import math
>
> n = long(raw_input("Please enter the number of iterations: "))
> sy = 0 # sum of the function-values
>
> for i in range(0, n):
> x = random.random() # coordinates
> sy += math.sqrt(1-math.sqrt(x)) # calculate y and add to sy
>
> print 4*sy/n # compute pi
> ---
>
> Unfortunately, even for n = 2000000 the result is ~2,13... .
> It converges very slow to pi and I don't know why.
Start by localizing the functions and using xrange...
random = random.random
sqrt = math.sqrt
for i in xrange(n):
x = random() # coordinates
sy += sqrt(1-sqrt(x)) # calculate y and add to sy
Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org
More information about the Python-list
mailing list