计算机建模验证概率论中的——贝特朗悖论(结论P=1/3)

import numpy as np
import matplotlib.pyplot as plt
import random
import math

x_size = 100000
X = np.linspace(-1,1,x_size)
Y1 = +np.sqrt(1-np.square(X))
Y2 = -np.sqrt(1-np.square(X))
print('X:',X)
# #   可视化圆
# plt.plot(X,Y1)
# plt.plot(X,Y2)
# plt.show()

#   贝特朗悖论
sample_size = 10000000
# dis_list=[]
hit_num = 0
for i in range(sample_size):
    #point1
    random_index = random.randint(0,x_size-1)
    x1 = X[random_index]
    random_updown = random.randint(0,1)
    if random_updown == 1:
        y1 = Y1[random_index]
    else:
        y1 = Y2[random_index]

        # point2
    random_index2 = random.randint(0, x_size-1)
    x2 = X[random_index2]
    random_updown2 = random.randint(0, 1)
    if random_updown2 == 1:
        y2 = Y1[random_index]
    else:
        y2 = Y2[random_index]

    dis = pow(x1-x2,2)+pow(y1-y2,2)
    # dis_list.append(dis)
    if dis>=3:
        hit_num+=1

print('size:{},hit:{},P:{}'.format(sample_size,hit_num,hit_num/sample_size

实验结果:

 

得出在1000万的实验次数下,频率约等于1/3

原问题:

 

posted @ 2022-09-02 16:19  山…隹  阅读(162)  评论(0编辑  收藏  举报