
The Monte Carlo method is a technique that uses random numbers to solve complex problems.
For example, consider the following types of problems:
- Estimating the value of π (pi)
- Calculating the volume of a complex shape
- Predicting the price of financial products
- Performing physical simulations
These problems can be difficult to solve analytically. The Monte Carlo method involves performing experiments using a large number of randomly generated numbers and making statistical estimations based on the results.
Origin of the name: It’s named after Monaco, where gambling games like roulette are played in casinos, evoking the image of using random numbers.
Basic Idea of the Monte Carlo Method
- Generate Random Numbers: Generate a large number of random numbers necessary to solve the problem.
- Perform Experiments: Run experiments that simulate the problem using the generated random numbers.
- Statistical Estimation: Collect the results of the experiments and calculate statistics such as averages or probabilities to estimate the solution to the problem.
Example: Estimating π (pi) (Sample Code)
As a simple example of the Monte Carlo method, let’s look at how to estimate the value of π.
import random
def estimate_pi(num_samples):
"""
Estimates pi using the Monte Carlo method.
Args:
num_samples: The number of random numbers to generate.
Returns:
An estimation of pi.
"""
inside_circle = 0
for _ in range(num_samples):
x = random.uniform(-1, 1) # Generate a random number between -1 and 1
y = random.uniform(-1, 1) # Generate a random number between -1 and 1
# If the distance from the origin is less than or equal to 1, consider it inside the circle
if x**2 + y**2 <= 1:
inside_circle += 1
# Since the area of the circle / area of the square = π/4, estimate pi.
pi_estimate = 4 * inside_circle / num_samples
return pi_estimate
# Estimate pi by specifying the number of random numbers
num_samples = 1000000
pi_value = estimate_pi(num_samples)
print(f"Estimated value of pi: {pi_value}")
Code Explanation:
random.uniform(-1, 1)generates random numbersxandybetween -1 and 1.- These
xandycan be considered as coordinates of points randomly falling within a square with side length 2. - Points whose distance from the origin (0, 0) is less than or equal to 1 are inside a circle with radius 1.
- Generate a large number of random numbers and count the number of points
inside_circlethat fall within the circle. - The area of the circle is π * r^2 = π. The area of the square is 2 * 2 = 4.
- Therefore, the ratio of points inside the circle to the total number of points is equal to π/4.
- Consequently,
pi_estimate = 4 * inside_circle / num_samplesestimates pi.
Key Points:
- The more random numbers
num_samples, the closer the estimation will be to the true value. - The Monte Carlo method can take a significant amount of computation time.
Advantages and Disadvantages of the Monte Carlo Method
Advantages:
- Can solve complex problems
- Applicable to problems where analytical solutions are difficult
- Suitable for parallel processing
Disadvantages:
- May require considerable computation time
- Estimations contain errors
- Dependent on the quality of random numbers
The Monte Carlo method is a powerful tool for solving complex problems using random numbers. It’s used in various fields and is expected to be increasingly utilized in the future.
Plot the dots
import random
import matplotlib.pyplot as plt
def estimate_pi(num_samples):
"""
Estimates pi using the Monte Carlo method and plots the points.
Args:
num_samples: The number of random numbers to generate.
Returns:
An estimation of pi.
"""
inside_circle = 0
x_points = []
y_points = []
in_circle_x = []
in_circle_y = []
for _ in range(num_samples):
x = random.uniform(-1, 1) # Generate a random number between -1 and 1
y = random.uniform(-1, 1) # Generate a random number between -1 and 1
x_points.append(x)
y_points.append(y)
# If the distance from the origin is less than or equal to 1, consider it inside the circle
if x**2 + y**2 <= 1:
inside_circle += 1
in_circle_x.append(x)
in_circle_y.append(y)
# Since the area of the circle / area of the square = π/4, estimate pi.
pi_estimate = 4 * inside_circle / num_samples
# Plotting
plt.figure(figsize=(6, 6)) # Specify the figure size
plt.scatter(x_points, y_points, s=1, label="Random Points") # Plot random points
plt.scatter(in_circle_x, in_circle_y, color='red', s=1, label="Points Inside Circle") # Plot points inside the circle in red
plt.xlabel("X")
plt.ylabel("Y")
plt.title(f"Monte Carlo Estimation of Pi (n={num_samples}) - Estimated Pi: {pi_estimate:.4f}")
plt.xlim(-1, 1) # Specify the range of the X-axis
plt.ylim(-1, 1) # Specify the range of the Y-axis
plt.gca().set_aspect('equal', adjustable='box') # Set aspect ratio to 1:1
plt.legend()
plt.grid(True)
plt.show()
return pi_estimate
# Estimate pi by specifying the number of random numbers
num_samples = 10000
pi_value = estimate_pi(num_samples)
print(f"Estimated value of pi: {pi_value}")