Reputation: 33
I'm trying to see how each point in a monte carlo simulation can be seen if it is in the area that is graphed. What is a good method for this?
# Definition of monte carlo operation
def montecarlo(func, x1, y1, x2, y2):
# Define the rectangle for integration
# rectangle = (x2 - x1) * (y2 - y1)
coordinates_list = []
list_random_x_value = []
list_random_y_value = []
# Generate random points in the rectangle
for i in range(0, 100):
random_x_value = random.uniform(x1, x2)
random_y_value = random.uniform(y1, y2)
list_random_x_value.append(random_x_value)
list_random_y_value.append(random_y_value)
# coordinates = [random_x_value, random_y_value]
# coordinates_list.append(coordinates)
# print(coordinates_list)
list_x_values = []
list_y_values = []
# Plot of graph
for values in np.arange(x1, x2, 0.01):
list_x_values.append(values)
y_values = func(values)
list_y_values.append(y_values)
Upvotes: 0
Views: 426
Reputation: 133
I think you mean something like this?
import numpy as np
import random
import matplotlib.pyplot as plt
# Definition of monte carlo operation
def montecarlo(func, x1, y1, x2, y2):
# Define the rectangle for integration
# rectangle = (x2 - x1) * (y2 - y1)
coordinates_list = []
list_random_x_value = []
list_random_y_value = []
# Generate random points in the rectangle
for i in range(0, 100):
random_x_value = random.uniform(x1, x2)
random_y_value = random.uniform(y1, y2)
list_random_x_value.append(random_x_value)
list_random_y_value.append(random_y_value)
# coordinates = [random_x_value, random_y_value]
# coordinates_list.append(coordinates)
# print(coordinates_list)
list_x_values = []
list_y_values = []
# Plot of graph
for values in np.arange(x1, x2, 0.01):
list_x_values.append(values)
y_values = func(values)
list_y_values.append(y_values)
plt.plot(list_x_values, list_y_values, c="b")
plt.scatter(list_random_x_value, list_random_y_value, c="r")
montecarlo(np.exp, 0, 0, 2, 1)
However, this is a very crude implementation of MC integration. Nevertheless, here is an easy and somewhat ok guide on how to implement these crude MC methods in python: https://boyangzhao.github.io/posts/monte-carlo-integration
Upvotes: 1