Last active
August 29, 2015 14:08
-
-
Save b-rodrigues/cdf3d30ea7e0938023db to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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