Skip to content

Instantly share code, notes, and snippets.

@csetzkorn
Created August 29, 2018 08:28
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 csetzkorn/0440cf16f27011609aceda8d052f7877 to your computer and use it in GitHub Desktop.
Save csetzkorn/0440cf16f27011609aceda8d052f7877 to your computer and use it in GitHub Desktop.
monte carlo integration - see data camp
# Define the sim_integrate function
def sim_integrate(func, xmin, xmax, sims):
x = np.random.uniform(xmin, xmax, sims)
y = np.random.uniform(min(min(func(x)), 0), max(func(x)), sims)
area = (max(y) - min(y))*(xmax-xmin)
result = area * sum(abs(y) < abs(func(x)))/sims
return result
# Call the sim_integrate function and print results
result = sim_integrate(func = lambda x: x*np.exp(x), xmin = 0, xmax = 1, sims = 50)
print("Simulated answer = {}, Actual Answer = 1".format(result))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment