Monte Carlo Method and pi
Jeff Epler
jepler at unpythonic.net
Fri Jul 9 00:12:33 CEST 2004
Others spotted the problem with your implementation of the approximatoin
method.
You can greatly speed things up with numarray. It gets "3.141..." as
the approximation using n=2000000 in about 4 seconds on this sub-GHz
laptop. Of course, a method with faster convergence would get to 3.141
in a lot less than 4 seconds, even if written in pure Python.
Jeff
import numarray
import numarray.random_array
def approx_pi(n):
a = numarray.random_array.uniform(0, 1, n)
return 4 * numarray.sum(numarray.sqrt(1 - a**2)) / n
if __name__ == '__main__':
n = int(raw_input("Please enter the number of iterations: "))
print approx_pi(n)
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20040708/4f072e8e/attachment.sig>
More information about the Python-list
mailing list