Monte Carlo method (MC) is a general term for methods that perform simulations and numerical calculations using random numbers. Originally, a method devised by Stanislaw Ulam and named by John von Neumann to explore how neutrons move around in matter. Named after Monte Carlo, one of the four districts (Cartier) of the Principality of Monaco, famous for its casinos. Also called the random method.
Quote wikipedia
In short, it is one of the methods to perform numerical calculation using random numbers.
Euclidean norm to measure whether the distance between the generated point and the origin is 1 or less
\sqrt{x^2+y^2}
Calculate with. The Euclidean distance is the normal distance between two points, as measured by a person with a ruler.
#Install module
import numpy as np
import math
import matplotlib.pyplot as plt
#X and y in a circle
inside_x = []
inside_y = []
#X and y out of the circle
outside_x = []
outside_y = []
count_inside = 0
for count in range(0, N):
d = math.hypot(x[count], y[count])
if d <1:
count_inside +=1
#Combination of x and y when entering the inside of a circle
inside_x.append(x[count])
inside_y.append(y[count])
else:
outside_x.append(x[count])
outside_y.append(y[count])
print('Number inside the circle:', count_inside)
output
Number inside the circle: 7875
#Figure size
plt.figure(figsize=(5,5))
#Data for drawing a circle
circle_x = np.arange(0,1,0.001)
circle_y = np.sqrt(1 - circle_x * circle_x)
#Draw a circle
plt.plot(circle_x, circle_y)
#Red is in the circle
plt.scatter(inside_x, inside_y, color = 'r')
#Blue is out of the circle
plt.scatter(outside_x, outside_y, color = 'b')
#Give a name
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True) #Have a grid
#Because it is the area of a unit circle divided into four equal parts of a circle with a radius of 1.
print('Approximate value of pi:'4.0 * count_inside / N)
output
Approximate value of pi: 3.144
The Monte Carlo method becomes more accurate as the number of dots is increased, but it takes longer to execute.
Recommended Posts