Skip to content

Instantly share code, notes, and snippets.

@b-rodrigues
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save b-rodrigues/cdf3d30ea7e0938023db to your computer and use it in GitHub Desktop.
Save b-rodrigues/cdf3d30ea7e0938023db to your computer and use it in GitHub Desktop.
#Monte Carlo Integration
#Example taken from Miranda and Fackler, Chapter 5, page 94
#We want to computer the following integral:
# \int_{-1}^1 \int_{-1}^1 \exp(-x_1) * cos (x_2^2)dx_1 dx_2
#which should be equal to 4.25199
#If you don't have sciki-monaco, install it with pip
#pip-install -U scikit-monaco
from numpy import mean, cos, exp, sqrt
from numpy.random import uniform, seed
from skmonaco import mcquad
#Set the number of processors you have
nprocs = 2
def integrand(x):
return((exp(-x[0]) * cos(x[1]*x[1])))
mcquad(integrand, xl=[-1.,-1.], xu=[1.,1.], npoints=1000000, nprocs=nprocs)
#Another example: volume of the unit sphere
def unit_sphere(x):
if (x[0]**2 + x[1]**2 + x[2]**2 < 1):
res = 1
else:
res = 0
return(res)
#should be equal to (4*pi)/3
mcquad(unit_sphere, xl=[-1., -1., -1.], xu=[1., 1., 1.], npoints=500000, nprocs=nprocs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment