Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import math
- import numpy as np
- import random
- def get_rand_number(min_value, max_value):
- _range = max_value - min_value
- choice = random.uniform(0,1)
- return min_value + _range*choice
- def f_of_x(x):
- return x**2
- def crude_monte_carlo(num_samples=5000):
- lower_bound = 0
- upper_bound = 1
- sum_of_samples = 0
- for i in range(num_samples):
- x = get_rand_number(lower_bound, upper_bound)
- sum_of_samples += f_of_x(x)
- return (upper_bound - lower_bound) * float(sum_of_samples/num_samples)
- n = [10, 20, 50, 500, 1000, 10000]
- for i in range (0, 6):
- fs = crude_monte_carlo(n[i])
- print(fs, '\t', abs(fs - 1./3))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement