SHARE
TWEET

Untitled

a guest Feb 28th, 2020 73 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import numpy as np
  2.  
  3.  
  4. def monte_carlo_integral(interval, num_samples, function):
  5.     points = np.random.uniform(*interval, size=num_samples)
  6.     samples = function(points)
  7.     return np.mean(samples)*(interval[1] - interval[0])
  8.  
  9.  
  10. # number of MC samples
  11. num_samples = 100
  12.  
  13. interval = (0, 1)
  14. function = lambda x: x**2
  15.  
  16. # trapezoidal rule
  17. xs = np.linspace(*interval, 100)
  18. print(f"numpy.trapz: {np.trapz(function(xs), xs)}")
  19.  
  20. # Monte Carlo integral
  21. print(f"Monte Carlo: {monte_carlo_integral(interval, num_samples, function)}")
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top