The second method of estimating π with python

 We here describes how to use the vote Buffon needle problem to estimate π \ piπ , let’s introduce another method, which is essentially the same, using the Monte Carlo method.

 As shown in the figure, a random side length is 1 1Thrownnin the square of 1n beans, suppose there arekkk fell on1 4 \frac{1}{4}41In the unit circle, the red point in the figure. Then according to geometric probability, kn = π 4 1 \frac{k}{n}=\frac{\frac{\pi}{4}}{1}nk=14Fr., Thus π = 4 kn \pi=\frac{4k}{n}Pi=n4 k
Insert picture description here

Implemented in Python:

import numpy as np

def get_pi(n):
    """

    :param n: 实验次数
    :return: π的估计值
    """
    #获得n个服从均匀分布U(0, 1)的随机数X, Y
    X = np.random.uniform(0, 1, n)
    Y = np.random.uniform(0, 1, n)
    #实验成功的次数,用向量形式实现,比用for循环要快的多,特别是n很大的时候
    k = np.sum(X ** 2 + Y ** 2 <= 1)
    #得到π的估计并返回
    pi = 4 * k / n
    return pi

print(get_pi(10000))

Output: 3.1424

 The output result is much worse than the well-known 3.1415926, because we only simulated 10,000 experiments, and the number of experiments can be increased to reduce the error

Guess you like

Origin blog.csdn.net/TSzero/article/details/111928172