monte carlo integration

385 days ago by jgreek

 
       
# Monte Carlo Integration import math import numpy as np import matplotlib.pyplot as plt a = 0. # Lower limit b = 1 # Upper limit Trials = 100000 # Number of sampling nodes f = lambda x: x^3 # function you want to integrate goodthrows = 0. throws=0. for i in range (1, Trials): x = np.random.rand(1) y = np.random.rand(1) if y <= f(x) : goodthrows = goodthrows + 1 throws = throws + 1 final = goodthrows/throws print final 
       
0.250742507425074
0.250742507425074