MC Monte Carlo method - Stack Overflow

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import scipy.integrate as integrate

'''
Monte Carlo method (Monte Carlo method, also translated as "Monte Carlo method") is a numerical calculation method based on the theory and method of probability and statistics.
The problem to be solved is related to a certain probability model, and statistical simulation or sampling is realized by computer to obtain an approximate solution of the problem, so it is also called random sampling method or statistical test method.
The above are the basic concepts of the Monte Carlo method, which are relatively abstract. Let's talk about some understandings of the Monte Carlo method based on the understanding in practical work.

(1) The mathematician von Neumann (the father of computing) named this method in the mid-1940s with Monte Carlo in the world-famous Las Vegas city of Monaco,
    It shows that this method has a natural and close connection with the randomness and probability in gambling. It almost involves the fields of complex numerical computing related to probability (computational physics, economic finance, statistics, machine learning, etc.).

(2) Monte Carlo is a method or strategy without any deep theoretical support (if there is a theory, there is only the law of large numbers in probability theory or statistics).
    A simple description of the basic principle of Monte Carlo is to first simulate a large number of times, then count the number of occurrences of an event, and then divide the number of occurrences by the total number of simulations to get the desired result.
    For example, simulate the number of votes N times (number of random samples), and count the number of times C that 6 appear at the same time (C/N is the calculation result).

(3) The Monte Carlo method can be applied in many occasions (the approximate solution is sought). The larger the number of simulated samples, the closer it is to the real value, and the increase in the number of samples will bring about a substantial increase in the amount of calculation.

    Example: Monte Carlo method to find the integral of the function y=x^2 in the interval [0,2] (that is, find the area).
        Note: It is simpler and more accurate to directly use the definite integral formula in mathematics.
    The red area is inside a 2×4 square. Using the Monte Carlo method, a large number of random points (the number is N) are randomly generated in this square,
    Calculate how many points (count is count) fall in the red area (judgment condition is y<x2), count/N is the required integral value, that is, the area of ​​the red area.
'''
np.random.seed(12345)
x = np.linspace(0, 2, 1000) # draw the curve
y = x ** 2
plt.plot(x, y)
plt.fill_between(x, y, where=(y > 0), color='red', alpha=0.5) # fill color
# plt.show()

#simulate 1000 random points
N = 1000
points = [[xy[0] * 2, xy[1] * 4] for xy in np.random.rand(N, 2)]
plt.scatter([x[0] for x in points], [x[1] for x in points], s=5, c=np.random.rand(N), alpha=0.5)
plt.show()

#Calculate the proportion that falls in the red area
count = 0
for xy in points:
    if xy[1] < xy[0] ** 2:
        count += 1
print((count / N) * (2 * 4))  # 2.752
print(integrate.quad(lambda x: x ** 2, 0, 2)[0])

'''
The Monte Carlo method has a certain error, and the size of the error is directly related to the size of the simulated sample. The larger the simulated sample, the smaller the error, but the amount of calculation will also increase significantly.
For simple problems, Monte Carlo is a "dumb" way.
But for simulations and computations involving complex, unanalyzable functions or probability distributions, Monte Carlo methods are an effective, and sometimes the only, approach.
'''

'''
Example 2: The game of hoops, have you ever wondered why you always fail? Use the Monte Carlo method to do the math.
1. Set the coordinates of the center point of the item to be (0,0), and the radius of the item to be 5cm.
'''
#
circle_target = mpatches.Circle([0, 0], radius=5, edgecolor='r', fill=False)
plt.xlim(-80, 80)
plt.ylim(-80, 80)
plt.axes().add_patch(circle_target)
# plt.show()

'''
2. Suppose the radius of the throwing circle is 8cm, the center point of the throwing circle is normally distributed in two dimensions around the center point of the item, the mean value μ=0cm, the standard deviation σ=20cm, and the process of 1000 throwing circles is simulated.
The red circle in the above picture is the item, and the scatter diagram is the distribution of the position of the center point of the circle during the simulation of 1000 circles.
3. Calculate the proportion of objects trapped in the hoops during the 1000 hoops.
'''
N = 1000
u, sigma = 0.20
points = sigma * np.random.randn(N, 2) + u
plt.scatter([x[0] for x in points], [x[1] for x in points], c=np.random.rand(N), alpha=0.5)
plt.show()

print(len([xy for xy in points if xy[0] ** 2 + xy[1] ** 2 < (8 - 5) ** 2]) / N)
#Output result: 0.009, that is, 1000 times, 9 times can catch the item, it is a small probability event, know why you can't catch it.
'''
The Monte Carlo method itself is not an optimization method,
There are similarities with intelligent optimization algorithms such as genetic algorithm and particle swarm optimization.
But they also have essential differences.
First, the levels are different. Monte Carlo can only be called a method, while genetic algorithms are bionic intelligent algorithms, which are more complicated than Monte Carlo methods.
Second, the application fields are different. Monte Carlo is a simulation statistical method. If the problem can be described in the form of a certain statistic, the Monte Carlo method can be used to solve it;
Genetic algorithms, etc. are suitable for large-scale combinatorial optimization problems (location problems, scheduling problems, management scheduling, route optimization), etc., as well as complex function maximization, parameter optimization, etc.
'''

Content taken from the Internet


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325447372&siteId=291194637