Copyright statement: originality is not easy, plagiarism and reprinting are prohibited in this article, and infringement must be investigated!
Table of contents
1. Monte Carlo method
Monte Carlo method, also known as statistical simulation method, random sampling technique, is a random simulation method, a calculation method based on probability and statistical theoretical methods. It is a method of using random numbers to solve many computing problems. Connect the problem to be solved with a certain probability model, and use an electronic computer to realize statistical simulation or sampling to obtain an approximate solution to the problem. In order to symbolically show the probabilistic and statistical characteristics of this method, it is named after the casino city of Monte Carlo.
In the 17th century, people knew that the "frequency" of events was used to determine the "probability" of events. This is also the basic idea of Monte Carlo method. When the sample size is large enough, we can use frequencies to estimate probabilities. This is also a common way to find pi.
2. Find pi
How to estimate the size of π when there is only one random number generator?
When we randomly select a coordinate (x, y) in the range (-1, 1), each coordinate point has an equal probability of being selected. Then the probability of a circle whose coordinates fall within a square of diameter 1 is:
From Chebyshev's inequality , we can get a value as close to pi as possible under the premise of generating a large number of random points.
3. Python algorithm implementation
import numpy as np
def pi(n, batch=1000):
t = 0
for i in range(n // batch): # 随机获取坐标
p = np.random.rand(batch, 2)
p = (p * p).sum(axis=1) # 计算坐标平方和
t += (p <= 1).sum() # 平方和小于1的即为落在圆中的点
print(4 * t / n)
pi(10 ** 4)
pi(10 ** 7)
pi(10 ** 8)
Output result:
As shown in the figure, under the premise of generating a large number of random points, we can get a value as close as possible to the pi
4. Author Info
Author: Xiaohong's fishing routine, Goal: Make programming more interesting!
Focus on algorithms, reptiles, websites, game development, data analysis, natural language processing, AI, etc., looking forward to your attention, let us grow and code together!
Copyright Note: This article prohibits plagiarism and reprinting, and infringement must be investigated!