Monte Carlo Method in Python

I am trying to use Python to create a script that allows me to generate a large number of points for use in the Monte Carlo method to calculate the score for Pi. script I still have this:

import math import random random.seed() n = 10000 for i in range(n): x = random.random() y = random.random() z = (x,y) if x**2+y**2 <= 1: print z else: del z 

Until now, I could generate all the points I needed, but what I would like to get is the number of points that are created when the script runs for use in the subsequent calculation. I am not looking for incredibly accurate results, a good enough grade. Any suggestions would be greatly appreciated.

+8
python montecarlo
source share
3 answers

If you are doing any kind of heavy duty numerical calculation considering numpy training. Your problem is mostly single-line with numpy setup:

 import numpy as np N = 10000 pts = np.random.random((N,2)) # Select the points according to your condition idx = (pts**2).sum(axis=1) < 1.0 print pts[idx], idx.sum() 

Donation:

 [[ 0.61255615 0.44319463] [ 0.48214768 0.69960483] [ 0.04735956 0.18509277] ..., [ 0.37543094 0.2858077 ] [ 0.43304577 0.45903071] [ 0.30838206 0.45977162]], 7854 

The last number is a counter of the number of counted events, i.e. the number of points whose radius is less than one.

+15
source share

Not sure if this is what you are looking for, but you can run enumerate on range and get the position in your iteration:

 In [1]: for index, i in enumerate(xrange(10, 15)): ...: print index + 1, i ...: ...: 1 10 2 11 3 12 4 13 5 14 

In this case, index + 1 will represent the current point being created ( index itself will be the total number of points created at the beginning of this iteration). Also, if you use Python 2.x, xrange usually better suited for these types of iterations, since it does not load the entire list into memory, but rather accesses it as needed.

+2
source share

Just add the hits variable before the loop, initialize it to 0 and inside your incrementing if increments by one.

Finally, you can calculate the PI value using hits and n.

 import math import random random.seed() n = 10000 hits = 0 # initialize hits with 0 for i in range(n): x = random.random() y = random.random() z = (x,y) if x**2+y**2 <= 1: hits += 1 else: del z # use hits and n to compute PI 
+1
source share

All Articles