Advertisement
Infiniti_Inter

Monte Carlo

Apr 18th, 2022
734
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.70 KB | None | 0 0
  1.  
  2. import math
  3. import numpy as np
  4. import random
  5.  
  6.  
  7. def get_rand_number(min_value, max_value):
  8.     _range = max_value - min_value
  9.     choice = random.uniform(0,1)
  10.     return min_value + _range*choice
  11.  
  12.  
  13. def f_of_x(x):
  14.     return x**2
  15.  
  16.  
  17. def crude_monte_carlo(num_samples=5000):
  18.     lower_bound = 0
  19.     upper_bound = 1
  20.     sum_of_samples = 0
  21.    
  22.     for i in range(num_samples):
  23.         x = get_rand_number(lower_bound, upper_bound)
  24.         sum_of_samples += f_of_x(x)
  25.    
  26.     return (upper_bound - lower_bound) * float(sum_of_samples/num_samples)
  27.  
  28.  
  29.  
  30.  
  31.  
  32.  
  33. n = [10, 20, 50, 500, 1000, 10000]
  34.  
  35. for i in range (0, 6):
  36.     fs = crude_monte_carlo(n[i])
  37.     print(fs, '\t', abs(fs - 1./3))
  38.  
  39.  
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement